From 99c5ea5368b2a58c6e93d4c76fccf5707c9469f8 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 29 Apr 2009 20:03:09 +0400 Subject: [PATCH 001/215] 6660539: Introspector shares cache of mutable BeanInfo between AppContexts Reviewed-by: peterz --- .../classes/java/beans/Introspector.java | 29 ++++++-- .../java/beans/Introspector/Test6660539.java | 68 +++++++++++++++++++ 2 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 jdk/test/java/beans/Introspector/Test6660539.java diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 6a50cbe7f7d..2a49db1794c 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,6 +45,7 @@ import java.util.EventListener; import java.util.List; import java.util.WeakHashMap; import java.util.TreeMap; +import sun.awt.AppContext; import sun.reflect.misc.ReflectUtil; /** @@ -111,8 +112,8 @@ public class Introspector { // Static Caches to speed up introspection. private static Map declaredMethodCache = Collections.synchronizedMap(new WeakHashMap()); - private static Map beanInfoCache = - Collections.synchronizedMap(new WeakHashMap()); + + private static final Object BEANINFO_CACHE = new Object(); private Class beanClass; private BeanInfo explicitBeanInfo; @@ -175,10 +176,18 @@ public class Introspector { if (!ReflectUtil.isPackageAccessible(beanClass)) { return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo(); } - BeanInfo bi = (BeanInfo)beanInfoCache.get(beanClass); + Map, BeanInfo> map; + synchronized (BEANINFO_CACHE) { + map = (Map, BeanInfo>) AppContext.getAppContext().get(BEANINFO_CACHE); + if (map == null) { + map = Collections.synchronizedMap(new WeakHashMap, BeanInfo>()); + AppContext.getAppContext().put(BEANINFO_CACHE, map); + } + } + BeanInfo bi = map.get(beanClass); if (bi == null) { bi = (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo(); - beanInfoCache.put(beanClass, bi); + map.put(beanClass, bi); } return bi; } @@ -351,7 +360,10 @@ public class Introspector { */ public static void flushCaches() { - beanInfoCache.clear(); + Map map = (Map) AppContext.getAppContext().get(BEANINFO_CACHE); + if (map != null) { + map.clear(); + } declaredMethodCache.clear(); } @@ -374,7 +386,10 @@ public class Introspector { if (clz == null) { throw new NullPointerException(); } - beanInfoCache.remove(clz); + Map map = (Map) AppContext.getAppContext().get(BEANINFO_CACHE); + if (map != null) { + map.remove(clz); + } declaredMethodCache.remove(clz); } diff --git a/jdk/test/java/beans/Introspector/Test6660539.java b/jdk/test/java/beans/Introspector/Test6660539.java new file mode 100644 index 00000000000..b0678a5a04b --- /dev/null +++ b/jdk/test/java/beans/Introspector/Test6660539.java @@ -0,0 +1,68 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6660539 + * @summary Tests changeable BeanInfo cache in different application contexts + * @author Sergey Malenkov + */ + +import sun.awt.SunToolkit; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; + +public class Test6660539 implements Runnable { + private static final String NAME = "$$$"; + + public static void main(String[] args) throws Exception { + for (PropertyDescriptor pd : getPropertyDescriptors()) { + pd.setDisplayName(NAME); + } + ThreadGroup group = new ThreadGroup(NAME); + Thread thread = new Thread(group, new Test6660539()); + thread.start(); + thread.join(); + } + + public void run() { + SunToolkit.createNewAppContext(); + for (PropertyDescriptor pd : getPropertyDescriptors()) { + if (pd.getDisplayName().equals(NAME)) + throw new Error("shared BeanInfo cache"); + } + } + + private static PropertyDescriptor[] getPropertyDescriptors() { + try { + BeanInfo info = Introspector.getBeanInfo(Test6660539.class); + return info.getPropertyDescriptors(); + } + catch (IntrospectionException exception) { + throw new Error("unexpected", exception); + } + } +} From de6e2fb6e267b377c94c9179cd474d1689b4a0e6 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 29 Apr 2009 20:55:13 +0400 Subject: [PATCH 002/215] 6777487: Encoder allows reading private variables with certain names Reviewed-by: peterz --- .../share/classes/java/beans/MetaData.java | 83 ++++++++++--------- .../beans/XMLEncoder/6777487/TestBox.java | 52 ++++++++++++ .../6777487/TestCheckedCollection.java | 48 +++++++++++ .../XMLEncoder/6777487/TestCheckedList.java | 48 +++++++++++ .../XMLEncoder/6777487/TestCheckedMap.java | 49 +++++++++++ .../6777487/TestCheckedRandomAccessList.java | 48 +++++++++++ .../XMLEncoder/6777487/TestCheckedSet.java | 48 +++++++++++ .../6777487/TestCheckedSortedMap.java | 49 +++++++++++ .../6777487/TestCheckedSortedSet.java | 48 +++++++++++ .../beans/XMLEncoder/6777487/TestEncoder.java | 60 ++++++++++++++ .../beans/XMLEncoder/6777487/TestEnumMap.java | 47 +++++++++++ .../beans/XMLEncoder/6777487/TestEnumSet.java | 47 +++++++++++ 12 files changed, 589 insertions(+), 38 deletions(-) create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestBox.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedCollection.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedList.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedMap.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedRandomAccessList.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSet.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedMap.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedSet.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestEncoder.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestEnumMap.java create mode 100644 jdk/test/java/beans/XMLEncoder/6777487/TestEnumSet.java diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index defd196457e..75c3945106d 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -333,31 +333,6 @@ abstract class java_util_Collections extends PersistenceDelegate { return (oldC.size() == newC.size()) && oldC.containsAll(newC); } - static Object getPrivateField(final Object instance, final String name) { - return AccessController.doPrivileged( - new PrivilegedAction() { - public Object run() { - Class type = instance.getClass(); - while ( true ) { - try { - Field field = type.getDeclaredField(name); - field.setAccessible(true); - return field.get( instance ); - } - catch (NoSuchFieldException exception) { - type = type.getSuperclass(); - if (type == null) { - throw new IllegalStateException("Could not find field " + name, exception); - } - } - catch (Exception exception) { - throw new IllegalStateException("Could not get value " + type.getName() + '.' + name, exception); - } - } - } - } ); - } - static final class EmptyList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { return new Expression(oldInstance, Collections.class, "emptyList", null); @@ -498,7 +473,7 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedCollection_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object type = getPrivateField(oldInstance, "type"); + Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedCollection", new Object[]{list, type}); } @@ -506,7 +481,7 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object type = getPrivateField(oldInstance, "type"); + Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new LinkedList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedList", new Object[]{list, type}); } @@ -514,7 +489,7 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedRandomAccessList_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object type = getPrivateField(oldInstance, "type"); + Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); List list = new ArrayList((Collection) oldInstance); return new Expression(oldInstance, Collections.class, "checkedList", new Object[]{list, type}); } @@ -522,7 +497,7 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object type = getPrivateField(oldInstance, "type"); + Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); Set set = new HashSet((Set) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSet", new Object[]{set, type}); } @@ -530,7 +505,7 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedSortedSet_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object type = getPrivateField(oldInstance, "type"); + Object type = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedCollection.type"); SortedSet set = new TreeSet((SortedSet) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSortedSet", new Object[]{set, type}); } @@ -538,8 +513,8 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object keyType = getPrivateField(oldInstance, "keyType"); - Object valueType = getPrivateField(oldInstance, "valueType"); + Object keyType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.keyType"); + Object valueType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.valueType"); Map map = new HashMap((Map) oldInstance); return new Expression(oldInstance, Collections.class, "checkedMap", new Object[]{map, keyType, valueType}); } @@ -547,8 +522,8 @@ abstract class java_util_Collections extends PersistenceDelegate { static final class CheckedSortedMap_PersistenceDelegate extends java_util_Collections { protected Expression instantiate(Object oldInstance, Encoder out) { - Object keyType = getPrivateField(oldInstance, "keyType"); - Object valueType = getPrivateField(oldInstance, "valueType"); + Object keyType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.keyType"); + Object valueType = MetaData.getPrivateFieldValue(oldInstance, "java.util.Collections$CheckedMap.valueType"); SortedMap map = new TreeMap((SortedMap) oldInstance); return new Expression(oldInstance, Collections.class, "checkedSortedMap", new Object[]{map, keyType, valueType}); } @@ -570,7 +545,7 @@ class java_util_EnumMap_PersistenceDelegate extends PersistenceDelegate { } private static Object getType(Object instance) { - return java_util_Collections.getPrivateField(instance, "keyType"); + return MetaData.getPrivateFieldValue(instance, "java.util.EnumMap.keyType"); } } @@ -589,7 +564,7 @@ class java_util_EnumSet_PersistenceDelegate extends PersistenceDelegate { } private static Object getType(Object instance) { - return java_util_Collections.getPrivateField(instance, "elementType"); + return MetaData.getPrivateFieldValue(instance, "java.util.EnumSet.elementType"); } } @@ -1280,7 +1255,7 @@ class javax_swing_Box_PersistenceDelegate extends DefaultPersistenceDelegate { private Integer getAxis(Object object) { Box box = (Box) object; - return (Integer) java_util_Collections.getPrivateField(box.getLayout(), "axis"); + return (Integer) MetaData.getPrivateFieldValue(box.getLayout(), "javax.swing.BoxLayout.axis"); } } @@ -1363,6 +1338,7 @@ final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Persisten } class MetaData { + private static final Map fields = Collections.synchronizedMap(new WeakHashMap()); private static Hashtable internalPersistenceDelegates = new Hashtable(); private static PersistenceDelegate nullPersistenceDelegate = new NullPersistenceDelegate(); @@ -1501,4 +1477,35 @@ class MetaData { return null; } } + + static Object getPrivateFieldValue(Object instance, String name) { + Field field = fields.get(name); + if (field == null) { + int index = name.lastIndexOf('.'); + final String className = name.substring(0, index); + final String fieldName = name.substring(1 + index); + field = AccessController.doPrivileged(new PrivilegedAction() { + public Field run() { + try { + Field field = Class.forName(className).getDeclaredField(fieldName); + field.setAccessible(true); + return field; + } + catch (ClassNotFoundException exception) { + throw new IllegalStateException("Could not find class", exception); + } + catch (NoSuchFieldException exception) { + throw new IllegalStateException("Could not find field", exception); + } + } + }); + fields.put(name, field); + } + try { + return field.get(instance); + } + catch (IllegalAccessException exception) { + throw new IllegalStateException("Could not get value of the field", exception); + } + } } diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestBox.java b/jdk/test/java/beans/XMLEncoder/6777487/TestBox.java new file mode 100644 index 00000000000..1287f4414b5 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestBox.java @@ -0,0 +1,52 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for BoxLayout + * @author Sergey Malenkov + */ + +import java.awt.FlowLayout; +import javax.swing.Box; +import javax.swing.BoxLayout; + +public final class TestBox { + private static final Integer OBJECT = Integer.valueOf(-123); + + public static void main(String[] args) { + TestEncoder.test( + new Box(BoxLayout.LINE_AXIS), + new Box(BoxLayout.PAGE_AXIS) { + @Override + public FlowLayout getLayout() { + return new FlowLayout() { + private final Object axis = OBJECT; + }; + } + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedCollection.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedCollection.java new file mode 100644 index 00000000000..805f05f4299 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedCollection.java @@ -0,0 +1,48 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedCollection + * @author Sergey Malenkov + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class TestCheckedCollection { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + List list = Collections.emptyList(); + TestEncoder.test( + Collections.checkedCollection(list, String.class), + new ArrayList() { + private final Object type = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedList.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedList.java new file mode 100644 index 00000000000..69d6ca9c8ba --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedList.java @@ -0,0 +1,48 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedList + * @author Sergey Malenkov + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class TestCheckedList { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + List list = Collections.emptyList(); + TestEncoder.test( + Collections.checkedList(list, String.class), + new ArrayList() { + private final Object type = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedMap.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedMap.java new file mode 100644 index 00000000000..7105782b179 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedMap.java @@ -0,0 +1,49 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedMap + * @author Sergey Malenkov + */ + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public final class TestCheckedMap { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + Map map = Collections.emptyMap(); + TestEncoder.test( + Collections.checkedMap(map, String.class, String.class), + new HashMap() { + private final Object keyType = OBJECT; + private final Object valueType = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedRandomAccessList.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedRandomAccessList.java new file mode 100644 index 00000000000..5141bc80620 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedRandomAccessList.java @@ -0,0 +1,48 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedRandomAccessList + * @author Sergey Malenkov + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class TestCheckedRandomAccessList { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + List list = new ArrayList(); + TestEncoder.test( + Collections.checkedList(list, String.class), + new ArrayList() { + private final Object type = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSet.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSet.java new file mode 100644 index 00000000000..d4dd04160b0 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSet.java @@ -0,0 +1,48 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedSet + * @author Sergey Malenkov + */ + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public final class TestCheckedSet { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + Set set = Collections.emptySet(); + TestEncoder.test( + Collections.checkedSet(set, String.class), + new HashSet() { + private final Object type = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedMap.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedMap.java new file mode 100644 index 00000000000..f39e7e2e060 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedMap.java @@ -0,0 +1,49 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedSortedMap + * @author Sergey Malenkov + */ + +import java.util.Collections; +import java.util.SortedMap; +import java.util.TreeMap; + +public final class TestCheckedSortedMap { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + SortedMap map = new TreeMap(); + TestEncoder.test( + Collections.checkedSortedMap(map, String.class, String.class), + new TreeMap() { + private final Object keyType = OBJECT; + private final Object valueType = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedSet.java b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedSet.java new file mode 100644 index 00000000000..f49c6ea3d94 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestCheckedSortedSet.java @@ -0,0 +1,48 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for CheckedSortedSet + * @author Sergey Malenkov + */ + +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; + +public final class TestCheckedSortedSet { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + SortedSet set = new TreeSet(); + TestEncoder.test( + Collections.checkedSortedSet(set, String.class), + new TreeSet() { + private final Object type = OBJECT; + }, + OBJECT + ); + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestEncoder.java b/jdk/test/java/beans/XMLEncoder/6777487/TestEncoder.java new file mode 100644 index 00000000000..a06289c8738 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestEncoder.java @@ -0,0 +1,60 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +import java.beans.Expression; +import java.beans.XMLEncoder; + +final class TestEncoder extends XMLEncoder { + private Expression expression; + + private TestEncoder() { + super(System.out); + } + + @Override + public void writeExpression(Expression expression) { + if (this.expression == null) { + this.expression = expression; + } + super.writeExpression(expression); + } + + public static void test(Object provider, Object object, Object value) { + System.setSecurityManager(new SecurityManager()); + + TestEncoder encoder = new TestEncoder(); + encoder.setPersistenceDelegate( + object.getClass(), + encoder.getPersistenceDelegate(provider.getClass())); + encoder.writeObject(object); + encoder.close(); + + if (encoder.expression != null) { + for (Object argument : encoder.expression.getArguments()) { + if (value.equals(argument)) { + throw new Error("Found private value!"); + } + } + } + } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestEnumMap.java b/jdk/test/java/beans/XMLEncoder/6777487/TestEnumMap.java new file mode 100644 index 00000000000..1d046c63e88 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestEnumMap.java @@ -0,0 +1,47 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for EnumMap + * @author Sergey Malenkov + */ + +import java.util.EnumMap; +import java.util.HashMap; + +public final class TestEnumMap { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + TestEncoder.test( + new EnumMap(Point.class), + new HashMap() { + private final Object keyType = OBJECT; + }, + OBJECT); + } + + public enum Point { X, Y, Z } +} diff --git a/jdk/test/java/beans/XMLEncoder/6777487/TestEnumSet.java b/jdk/test/java/beans/XMLEncoder/6777487/TestEnumSet.java new file mode 100644 index 00000000000..b9f518d9979 --- /dev/null +++ b/jdk/test/java/beans/XMLEncoder/6777487/TestEnumSet.java @@ -0,0 +1,47 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6777487 + * @summary Tests private field access for EnumSet + * @author Sergey Malenkov + */ + +import java.util.EnumSet; +import java.util.HashSet; + +public final class TestEnumSet { + private static final Object OBJECT = new Object(); + + public static void main(String[] args) { + TestEncoder.test( + EnumSet.noneOf(Point.class), + new HashSet() { + private final Object elementType = OBJECT; + }, + OBJECT); + } + + public enum Point { X, Y, Z } +} From d663bac9312a84730da246fa8fcd8ce080e220fd Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Tue, 5 May 2009 12:07:37 +0400 Subject: [PATCH 003/215] 6837293: Reapply fix for 6588003 to JDK7 Reviewed-by: alexp --- .../classes/javax/swing/text/LayoutQueue.java | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/LayoutQueue.java b/jdk/src/share/classes/javax/swing/text/LayoutQueue.java index 38fd665c40e..f1d73ffc0d8 100644 --- a/jdk/src/share/classes/javax/swing/text/LayoutQueue.java +++ b/jdk/src/share/classes/javax/swing/text/LayoutQueue.java @@ -25,6 +25,7 @@ package javax.swing.text; import java.util.Vector; +import sun.awt.AppContext; /** * A queue of text layout tasks. @@ -35,10 +36,10 @@ import java.util.Vector; */ public class LayoutQueue { - Vector tasks; - Thread worker; + private static final Object DEFAULT_QUEUE = new Object(); - static LayoutQueue defaultQueue; + private Vector tasks; + private Thread worker; /** * Construct a layout queue. @@ -51,10 +52,15 @@ public class LayoutQueue { * Fetch the default layout queue. */ public static LayoutQueue getDefaultQueue() { - if (defaultQueue == null) { - defaultQueue = new LayoutQueue(); + AppContext ac = AppContext.getAppContext(); + synchronized (DEFAULT_QUEUE) { + LayoutQueue defaultQueue = (LayoutQueue) ac.get(DEFAULT_QUEUE); + if (defaultQueue == null) { + defaultQueue = new LayoutQueue(); + ac.put(DEFAULT_QUEUE, defaultQueue); + } + return defaultQueue; } - return defaultQueue; } /** @@ -63,7 +69,9 @@ public class LayoutQueue { * @param q the new queue. */ public static void setDefaultQueue(LayoutQueue q) { - defaultQueue = q; + synchronized (DEFAULT_QUEUE) { + AppContext.getAppContext().put(DEFAULT_QUEUE, q); + } } /** From b23fe07b43057fcb66d2a463e8e8371ce6b2069c Mon Sep 17 00:00:00 2001 From: Jean-Christophe Collet Date: Tue, 5 May 2009 11:02:51 +0200 Subject: [PATCH 004/215] 6801497: Proxy is assumed to be immutable but is non-final Cloned the proxy instance when necessary Reviewed-by: chegar --- jdk/src/share/classes/java/net/Socket.java | 13 +++++++++---- jdk/src/share/classes/java/net/URL.java | 8 +++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/jdk/src/share/classes/java/net/Socket.java b/jdk/src/share/classes/java/net/Socket.java index e0769176af3..110a6a5f1a9 100644 --- a/jdk/src/share/classes/java/net/Socket.java +++ b/jdk/src/share/classes/java/net/Socket.java @@ -114,9 +114,14 @@ class Socket implements java.io.Closeable { * @since 1.5 */ public Socket(Proxy proxy) { - if (proxy != null && proxy.type() == Proxy.Type.SOCKS) { + // Create a copy of Proxy as a security measure + if (proxy == null) { + throw new IllegalArgumentException("Invalid Proxy"); + } + Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : new Proxy(proxy.type(), proxy.address()); + if (p.type() == Proxy.Type.SOCKS) { SecurityManager security = System.getSecurityManager(); - InetSocketAddress epoint = (InetSocketAddress) proxy.address(); + InetSocketAddress epoint = (InetSocketAddress) p.address(); if (security != null) { if (epoint.isUnresolved()) security.checkConnect(epoint.getHostName(), @@ -125,10 +130,10 @@ class Socket implements java.io.Closeable { security.checkConnect(epoint.getAddress().getHostAddress(), epoint.getPort()); } - impl = new SocksSocketImpl(proxy); + impl = new SocksSocketImpl(p); impl.setSocket(this); } else { - if (proxy == Proxy.NO_PROXY) { + if (p == Proxy.NO_PROXY) { if (factory == null) { impl = new PlainSocketImpl(); impl.setSocket(this); diff --git a/jdk/src/share/classes/java/net/URL.java b/jdk/src/share/classes/java/net/URL.java index bb934d9b745..73818e960d8 100644 --- a/jdk/src/share/classes/java/net/URL.java +++ b/jdk/src/share/classes/java/net/URL.java @@ -1004,16 +1004,18 @@ public final class URL implements java.io.Serializable { throw new IllegalArgumentException("proxy can not be null"); } + // Create a copy of Proxy as a security measure + Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : new Proxy(proxy.type(), proxy.address()); SecurityManager sm = System.getSecurityManager(); - if (proxy.type() != Proxy.Type.DIRECT && sm != null) { - InetSocketAddress epoint = (InetSocketAddress) proxy.address(); + if (p.type() != Proxy.Type.DIRECT && sm != null) { + InetSocketAddress epoint = (InetSocketAddress) p.address(); if (epoint.isUnresolved()) sm.checkConnect(epoint.getHostName(), epoint.getPort()); else sm.checkConnect(epoint.getAddress().getHostAddress(), epoint.getPort()); } - return handler.openConnection(this, proxy); + return handler.openConnection(this, p); } /** From 2453a64fc4954f7a2b13cf20f13583cc542fa0a3 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Tue, 5 May 2009 17:47:04 +0400 Subject: [PATCH 005/215] 6805231: Security Warning Icon is missing in Windows 2000 Prof from Jdk build 6u12 The icon becomes layered only when the fading-out effect is being performed. Reviewed-by: art, dcherepanov --- .../windows/native/sun/windows/awt_Window.cpp | 36 ++++++++++++++----- .../windows/native/sun/windows/awt_Window.h | 3 ++ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp index 88bcd8ecc45..3e31a1c8db8 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp @@ -524,7 +524,7 @@ void AwtWindow::CreateWarningWindow(JNIEnv *env) RegisterWarningWindowClass(); warningWindow = ::CreateWindowEx( - WS_EX_NOACTIVATE | WS_EX_LAYERED, + WS_EX_NOACTIVATE, GetWarningWindowClassName(), warningString, WS_POPUP, @@ -536,7 +536,7 @@ void AwtWindow::CreateWarningWindow(JNIEnv *env) NULL // lParam ); if (warningWindow == NULL) { - //XXX: actually this is bad... We didn't manage to create the widow. + //XXX: actually this is bad... We didn't manage to create the window. return; } @@ -836,6 +836,19 @@ void AwtWindow::RepaintWarningWindow() ::ReleaseDC(warningWindow, hdc); } +void AwtWindow::SetLayered(HWND window, bool layered) +{ + const LONG ex_style = ::GetWindowLong(window, GWL_EXSTYLE); + ::SetWindowLong(window, GWL_EXSTYLE, layered ? + ex_style | WS_EX_LAYERED : ex_style & ~WS_EX_LAYERED); +} + +bool AwtWindow::IsLayered(HWND window) +{ + const LONG ex_style = ::GetWindowLong(window, GWL_EXSTYLE); + return ex_style & WS_EX_LAYERED; +} + void AwtWindow::StartSecurityAnimation(AnimationKind kind) { if (!IsUntrusted()) { @@ -858,8 +871,14 @@ void AwtWindow::StartSecurityAnimation(AnimationKind kind) ::SetLayeredWindowAttributes(warningWindow, RGB(0, 0, 0), 0xFF, LWA_ALPHA); + AwtWindow::SetLayered(warningWindow, false); ::RedrawWindow(warningWindow, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); + } else if (securityAnimationKind == akPreHide) { + // Pre-hiding means fading-out. We have to make the window layered. + // Note: Some VNC clients do not support layered windows, hence + // we dynamically turn it on and off. See 6805231. + AwtWindow::SetLayered(warningWindow, true); } } @@ -2528,8 +2547,6 @@ void AwtWindow::SetTranslucency(BYTE opacity, BOOL opaque) HWND hwnd = GetHWnd(); - LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); - if (opaque != old_opaque) { ::EnterCriticalSection(&contentBitmapCS); if (hContentBitmap != NULL) { @@ -2541,21 +2558,22 @@ void AwtWindow::SetTranslucency(BYTE opacity, BOOL opaque) if (opaque && opacity == 0xff) { // Turn off all the effects - ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style & ~WS_EX_LAYERED); + AwtWindow::SetLayered(hwnd, false); + // Ask the window to repaint itself and all the children RedrawWindow(); } else { // We're going to enable some effects - if (!(ex_style & WS_EX_LAYERED)) { - ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style | WS_EX_LAYERED); + if (!AwtWindow::IsLayered(hwnd)) { + AwtWindow::SetLayered(hwnd, true); } else { if ((opaque && opacity < 0xff) ^ (old_opaque && old_opacity < 0xff)) { // _One_ of the modes uses the SetLayeredWindowAttributes. // Need to reset the style in this case. // If both modes are simple (i.e. just changing the opacity level), // no need to reset the style. - ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style & ~WS_EX_LAYERED); - ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style | WS_EX_LAYERED); + AwtWindow::SetLayered(hwnd, false); + AwtWindow::SetLayered(hwnd, true); } } diff --git a/jdk/src/windows/native/sun/windows/awt_Window.h b/jdk/src/windows/native/sun/windows/awt_Window.h index bf43150a7e8..40da9979bcd 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.h +++ b/jdk/src/windows/native/sun/windows/awt_Window.h @@ -332,6 +332,9 @@ private: void RepositionSecurityWarning(JNIEnv *env); + static void SetLayered(HWND window, bool layered); + static bool IsLayered(HWND window); + public: void UpdateSecurityWarningVisibility(); static bool IsWarningWindow(HWND hWnd); From dfb6852a1624bfa42b89ad993ec832bfab0b5d89 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Tue, 5 May 2009 17:56:31 +0400 Subject: [PATCH 006/215] 6818787: It is possible to reposition the security icon too far from the border of the window on X11 The constraints for the position of the icon are moved to the shared code Reviewed-by: art, dcherepanov --- jdk/src/share/classes/java/awt/Window.java | 54 ++++++++++++++++--- .../windows/native/sun/windows/awt_Window.cpp | 25 --------- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index 01d9ff59d00..faff2758726 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -3593,16 +3593,56 @@ public class Window extends Container implements Accessible { // ****************** END OF MIXING CODE ******************************** - // This method gets the window location/size as reported by the native - // system since the locally cached values may represent outdated data. - // NOTE: this method is invoked on the toolkit thread, and therefore - // is not supposed to become public/user-overridable. + /** + * Limit the given double value with the given range. + */ + private static double limit(double value, double min, double max) { + value = Math.max(value, min); + value = Math.min(value, max); + return value; + } + + /** + * Calculate the position of the security warning. + * + * This method gets the window location/size as reported by the native + * system since the locally cached values may represent outdated data. + * + * The method is used from the native code, or via AWTAccessor. + * + * NOTE: this method is invoked on the toolkit thread, and therefore is not + * supposed to become public/user-overridable. + */ private Point2D calculateSecurityWarningPosition(double x, double y, double w, double h) { - return new Point2D.Double( - x + w * securityWarningAlignmentX + securityWarningPointX, - y + h * securityWarningAlignmentY + securityWarningPointY); + // The position according to the spec of SecurityWarning.setPosition() + double wx = x + w * securityWarningAlignmentX + securityWarningPointX; + double wy = y + h * securityWarningAlignmentY + securityWarningPointY; + + // First, make sure the warning is not too far from the window bounds + wx = Window.limit(wx, + x - securityWarningWidth - 2, + x + w + 2); + wy = Window.limit(wy, + y - securityWarningHeight - 2, + y + h + 2); + + // Now make sure the warning window is visible on the screen + Rectangle screenBounds = graphicsConfig.getBounds(); + Insets screenInsets = + Toolkit.getDefaultToolkit().getScreenInsets(graphicsConfig); + + wx = Window.limit(wx, + screenBounds.x + screenInsets.left, + screenBounds.x + screenBounds.width - screenInsets.right + - securityWarningWidth); + wy = Window.limit(wy, + screenBounds.y + screenInsets.top, + screenBounds.y + screenBounds.height - screenInsets.bottom + - securityWarningHeight); + + return new Point2D.Double(wx, wy); } static { diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp index 3e31a1c8db8..39f61bb7543 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp @@ -707,31 +707,6 @@ void AwtWindow::CalculateWarningWindowBounds(JNIEnv *env, LPRECT rect) env->DeleteLocalRef(point2D); - //Make sure the warning is not far from the window bounds - x = max(x, windowBounds.left - (int)warningWindowWidth - 2); - x = min(x, windowBounds.right + (int)warningWindowWidth + 2); - - y = max(y, windowBounds.top - (int)warningWindowHeight - 2); - y = min(y, windowBounds.bottom + (int)warningWindowHeight + 2); - - // Now make sure the warning window is visible on the screen - HMONITOR hmon = MonitorFromWindow(GetHWnd(), MONITOR_DEFAULTTOPRIMARY); - DASSERT(hmon != NULL); - - RECT monitorBounds; - RECT monitorInsets; - - MonitorBounds(hmon, &monitorBounds); - if (!AwtToolkit::GetScreenInsets(m_screenNum, &monitorInsets)) { - ::ZeroMemory(&monitorInsets, sizeof(monitorInsets)); - } - - x = max(x, monitorBounds.left + monitorInsets.left); - x = min(x, monitorBounds.right - monitorInsets.right - (int)warningWindowWidth); - - y = max(y, monitorBounds.top + monitorInsets.top); - y = min(y, monitorBounds.bottom - monitorInsets.bottom - (int)warningWindowHeight); - rect->left = x; rect->top = y; rect->right = rect->left + warningWindowWidth; From f6e8569c858067188a8d84e91d91dafa4aaa0a71 Mon Sep 17 00:00:00 2001 From: Artem Ananiev Date: Wed, 6 May 2009 15:17:22 +0400 Subject: [PATCH 007/215] 6656586: Cursor.predefined is protected static mutable (findbugs) Reviewed-by: hawtin, igor --- jdk/src/share/classes/java/awt/Cursor.java | 21 ++++++-- .../PredefinedPrivate/PredefinedPrivate.java | 49 +++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 jdk/test/java/awt/Cursor/PredefinedPrivate/PredefinedPrivate.java diff --git a/jdk/src/share/classes/java/awt/Cursor.java b/jdk/src/share/classes/java/awt/Cursor.java index cc1b20b999a..0187eac69b9 100644 --- a/jdk/src/share/classes/java/awt/Cursor.java +++ b/jdk/src/share/classes/java/awt/Cursor.java @@ -118,8 +118,18 @@ public class Cursor implements java.io.Serializable { */ public static final int MOVE_CURSOR = 13; + /** + * @deprecated As of JDK version 1.7, the {@link #getPredefinedCursor()} + * method should be used instead. + */ + @Deprecated protected static Cursor predefined[] = new Cursor[14]; + /** + * This field is a private replacement for 'predefined' array. + */ + private final static Cursor[] predefinedPrivate = new Cursor[14]; + /* Localization names and default values */ static final String[][] cursorProperties = { { "AWT.DefaultCursor", "Default Cursor" }, @@ -253,10 +263,15 @@ public class Cursor implements java.io.Serializable { if (type < Cursor.DEFAULT_CURSOR || type > Cursor.MOVE_CURSOR) { throw new IllegalArgumentException("illegal cursor type"); } - if (predefined[type] == null) { - predefined[type] = new Cursor(type); + Cursor c = predefinedPrivate[type]; + if (c == null) { + predefinedPrivate[type] = c = new Cursor(type); } - return predefined[type]; + // fill 'predefined' array for backwards compatibility. + if (predefined[type] == null) { + predefined[type] = c; + } + return c; } /** diff --git a/jdk/test/java/awt/Cursor/PredefinedPrivate/PredefinedPrivate.java b/jdk/test/java/awt/Cursor/PredefinedPrivate/PredefinedPrivate.java new file mode 100644 index 00000000000..a4ba1daaca4 --- /dev/null +++ b/jdk/test/java/awt/Cursor/PredefinedPrivate/PredefinedPrivate.java @@ -0,0 +1,49 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6656586 + * @summary Test that Cursor.predefined array is not used in +Cursor.getPredefinedCursor() method + * @author Artem Ananiev + * @run main PredefinedPrivate + */ + +import java.awt.*; + +public class PredefinedPrivate { + public static void main(String args[]) { + new MyCursor(); + if (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) instanceof MyCursor) { + throw new RuntimeException("Test FAILED: getPredefinedCursor() returned modified cursor"); + } + } +} + +class MyCursor extends Cursor { + public MyCursor() { + super(DEFAULT_CURSOR); + Cursor.predefined[DEFAULT_CURSOR] = this; + } +} From ec41d4d0e931bf22dbfbcda44d506c9a44a3091d Mon Sep 17 00:00:00 2001 From: Eamonn McManus Date: Thu, 7 May 2009 10:44:45 +0200 Subject: [PATCH 008/215] 6736293: OpenType checks can be bypassed through finalizer resurrection Reviewed-by: hawtin --- jdk/src/share/classes/java/awt/Window.java | 2 ++ .../openmbean/OpenMBeanAttributeInfoSupport.java | 8 ++++---- .../classes/javax/management/openmbean/OpenType.java | 5 +++++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index faff2758726..920b499c9a3 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -3629,6 +3629,8 @@ public class Window extends Container implements Accessible { y + h + 2); // Now make sure the warning window is visible on the screen + GraphicsConfiguration graphicsConfig = + getGraphicsConfiguration_NoClientCode(); Rectangle screenBounds = graphicsConfig.getBounds(); Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(graphicsConfig); diff --git a/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java b/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java index 3ad03ef58ae..f2f86e1bf72 100644 --- a/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java +++ b/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java @@ -690,7 +690,7 @@ public class OpenMBeanAttributeInfoSupport private static T convertFromString(String s, OpenType openType) { Class c; try { - c = cast(Class.forName(openType.getClassName())); + c = cast(Class.forName(openType.safeGetClassName())); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.toString()); // can't happen } @@ -711,7 +711,7 @@ public class OpenMBeanAttributeInfoSupport } catch (Exception e) { final String msg = "Could not convert \"" + s + "\" using method: " + valueOf; - throw new IllegalArgumentException(msg); + throw new IllegalArgumentException(msg, e); } } @@ -728,7 +728,7 @@ public class OpenMBeanAttributeInfoSupport } catch (Exception e) { final String msg = "Could not convert \"" + s + "\" using constructor: " + con; - throw new IllegalArgumentException(msg); + throw new IllegalArgumentException(msg, e); } } @@ -757,7 +757,7 @@ public class OpenMBeanAttributeInfoSupport stringArrayClass = Class.forName(squareBrackets + "Ljava.lang.String;"); targetArrayClass = - Class.forName(squareBrackets + "L" + baseType.getClassName() + + Class.forName(squareBrackets + "L" + baseType.safeGetClassName() + ";"); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.toString()); // can't happen diff --git a/jdk/src/share/classes/javax/management/openmbean/OpenType.java b/jdk/src/share/classes/javax/management/openmbean/OpenType.java index 3f74c3cda60..b6d40d008c7 100644 --- a/jdk/src/share/classes/javax/management/openmbean/OpenType.java +++ b/jdk/src/share/classes/javax/management/openmbean/OpenType.java @@ -304,7 +304,12 @@ public abstract class OpenType implements Serializable { * @return the class name. */ public String getClassName() { + return className; + } + // A version of getClassName() that can only be called from within this + // package and that cannot be overridden. + String safeGetClassName() { return className; } From 10f62128a45fa6384621e57b86cc18475ee7fa27 Mon Sep 17 00:00:00 2001 From: Andrew Brygin Date: Fri, 8 May 2009 15:38:21 +0400 Subject: [PATCH 009/215] 6656625: ImageReaderSpi.STANDARD_INPUT_TYPE/ImageWriterSpi.STANDARD_OUTPUT_TYPE are mutable static (findbugs) Reviewed-by: prr --- .../sun/imageio/plugins/bmp/BMPImageReaderSpi.java | 2 +- .../sun/imageio/plugins/bmp/BMPImageWriterSpi.java | 3 ++- .../sun/imageio/plugins/gif/GIFImageReaderSpi.java | 2 +- .../sun/imageio/plugins/gif/GIFImageWriterSpi.java | 3 ++- .../imageio/plugins/jpeg/JPEGImageReaderSpi.java | 2 +- .../imageio/plugins/jpeg/JPEGImageWriterSpi.java | 3 ++- .../sun/imageio/plugins/png/PNGImageReaderSpi.java | 2 +- .../sun/imageio/plugins/png/PNGImageWriterSpi.java | 3 ++- .../imageio/plugins/wbmp/WBMPImageReaderSpi.java | 2 +- .../imageio/plugins/wbmp/WBMPImageWriterSpi.java | 3 ++- .../classes/javax/imageio/spi/ImageReaderSpi.java | 9 ++++++++- .../classes/javax/imageio/spi/ImageWriterSpi.java | 13 ++++++++++--- 12 files changed, 33 insertions(+), 14 deletions(-) diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java index 9cea55911f7..2966a4b883c 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageReaderSpi.java @@ -51,7 +51,7 @@ public class BMPImageReaderSpi extends ImageReaderSpi { entensions, mimeType, "com.sun.imageio.plugins.bmp.BMPImageReader", - STANDARD_INPUT_TYPE, + new Class[] { ImageInputStream.class }, writerSpiNames, false, null, null, null, null, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java index f5e322e01da..4ae73d4c897 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/bmp/BMPImageWriterSpi.java @@ -32,6 +32,7 @@ import java.awt.image.SinglePixelPackedSampleModel; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.spi.ServiceRegistry; import javax.imageio.spi.IIORegistry; +import javax.imageio.stream.ImageOutputStream; import javax.imageio.ImageWriter; import javax.imageio.ImageTypeSpecifier; import javax.imageio.IIOException; @@ -55,7 +56,7 @@ public class BMPImageWriterSpi extends ImageWriterSpi { entensions, mimeType, "com.sun.imageio.plugins.bmp.BMPImageWriter", - STANDARD_OUTPUT_TYPE, + new Class[] { ImageOutputStream.class }, readerSpiNames, false, null, null, null, null, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java index 0dc0a40a6d7..3832b1eb923 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReaderSpi.java @@ -60,7 +60,7 @@ public class GIFImageReaderSpi extends ImageReaderSpi { suffixes, MIMETypes, readerClassName, - STANDARD_INPUT_TYPE, + new Class[] { ImageInputStream.class }, writerSpiNames, true, GIFStreamMetadata.nativeMetadataFormatName, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java index 796e3b2a458..42b81e4c8b8 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageWriterSpi.java @@ -31,6 +31,7 @@ import java.util.Locale; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriter; import javax.imageio.spi.ImageWriterSpi; +import javax.imageio.stream.ImageOutputStream; import com.sun.imageio.plugins.common.PaletteBuilder; public class GIFImageWriterSpi extends ImageWriterSpi { @@ -59,7 +60,7 @@ public class GIFImageWriterSpi extends ImageWriterSpi { suffixes, MIMETypes, writerClassName, - STANDARD_OUTPUT_TYPE, + new Class[] { ImageOutputStream.class }, readerSpiNames, true, GIFWritableStreamMetadata.NATIVE_FORMAT_NAME, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java index 13327e3ea9c..25aabe32e90 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReaderSpi.java @@ -46,7 +46,7 @@ public class JPEGImageReaderSpi extends ImageReaderSpi { JPEG.suffixes, JPEG.MIMETypes, "com.sun.imageio.plugins.jpeg.JPEGImageReader", - STANDARD_INPUT_TYPE, + new Class[] { ImageInputStream.class }, writerSpiNames, true, JPEG.nativeStreamMetadataFormatName, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java index 717b4360794..02fade632ed 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriterSpi.java @@ -28,6 +28,7 @@ package com.sun.imageio.plugins.jpeg; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.spi.ServiceRegistry; import javax.imageio.spi.IIORegistry; +import javax.imageio.stream.ImageOutputStream; import javax.imageio.ImageWriter; import javax.imageio.ImageTypeSpecifier; import javax.imageio.IIOException; @@ -49,7 +50,7 @@ public class JPEGImageWriterSpi extends ImageWriterSpi { JPEG.suffixes, JPEG.MIMETypes, "com.sun.imageio.plugins.jpeg.JPEGImageWriter", - STANDARD_OUTPUT_TYPE, + new Class[] { ImageOutputStream.class }, readerSpiNames, true, JPEG.nativeStreamMetadataFormatName, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java index 44ee5b80101..6576b83df58 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReaderSpi.java @@ -60,7 +60,7 @@ public class PNGImageReaderSpi extends ImageReaderSpi { suffixes, MIMETypes, readerClassName, - STANDARD_INPUT_TYPE, + new Class[] { ImageInputStream.class }, writerSpiNames, false, null, null, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java index 0dabd881816..4f69fcd70de 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageWriterSpi.java @@ -34,6 +34,7 @@ import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; import javax.imageio.spi.ImageWriterSpi; +import javax.imageio.stream.ImageOutputStream; public class PNGImageWriterSpi extends ImageWriterSpi { @@ -61,7 +62,7 @@ public class PNGImageWriterSpi extends ImageWriterSpi { suffixes, MIMETypes, writerClassName, - STANDARD_OUTPUT_TYPE, + new Class[] { ImageOutputStream.class }, readerSpiNames, false, null, null, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java index 2d882ab6b2c..7e5e6e61e0e 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReaderSpi.java @@ -51,7 +51,7 @@ public class WBMPImageReaderSpi extends ImageReaderSpi { entensions, mimeType, "com.sun.imageio.plugins.wbmp.WBMPImageReader", - STANDARD_INPUT_TYPE, + new Class[] { ImageInputStream.class }, writerSpiNames, true, null, null, null, null, diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java index 1da8420dc32..82106f981f5 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageWriterSpi.java @@ -28,6 +28,7 @@ package com.sun.imageio.plugins.wbmp; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.spi.ServiceRegistry; import javax.imageio.spi.IIORegistry; +import javax.imageio.stream.ImageOutputStream; import javax.imageio.ImageWriter; import javax.imageio.ImageTypeSpecifier; import javax.imageio.IIOException; @@ -54,7 +55,7 @@ public class WBMPImageWriterSpi extends ImageWriterSpi { entensions, mimeType, "com.sun.imageio.plugins.wbmp.WBMPImageWriter", - STANDARD_OUTPUT_TYPE, + new Class[] { ImageOutputStream.class }, readerSpiNames, true, null, null, null, null, diff --git a/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java b/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java index 4f0b7fa6ac5..0de66188ba8 100644 --- a/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java +++ b/jdk/src/share/classes/javax/imageio/spi/ImageReaderSpi.java @@ -77,7 +77,10 @@ public abstract class ImageReaderSpi extends ImageReaderWriterSpi { * A single-element array, initially containing * ImageInputStream.class, to be returned from * getInputTypes. + * @deprecated Instead of using this field, directly create + * the equivalent array { ImageInputStream.class }. */ + @Deprecated public static final Class[] STANDARD_INPUT_TYPE = { ImageInputStream.class }; @@ -227,7 +230,11 @@ public abstract class ImageReaderSpi extends ImageReaderWriterSpi { throw new IllegalArgumentException ("inputTypes.length == 0!"); } - this.inputTypes = (Class[])inputTypes.clone(); + + this.inputTypes = (inputTypes == STANDARD_INPUT_TYPE) ? + new Class[] { ImageInputStream.class } : + inputTypes.clone(); + // If length == 0, leave it null if (writerSpiNames != null && writerSpiNames.length > 0) { this.writerSpiNames = (String[])writerSpiNames.clone(); diff --git a/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java b/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java index 324c5cd3d05..f3ff947a4f4 100644 --- a/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java +++ b/jdk/src/share/classes/javax/imageio/spi/ImageWriterSpi.java @@ -77,9 +77,12 @@ public abstract class ImageWriterSpi extends ImageReaderWriterSpi { /** * A single-element array, initially containing - * ImageInputStream.class, to be returned from - * getInputTypes. + * ImageOutputStream.class, to be returned from + * getOutputTypes. + * @deprecated Instead of using this field, directly create + * the equivalent array { ImageOutputStream.class }. */ + @Deprecated public static final Class[] STANDARD_OUTPUT_TYPE = { ImageOutputStream.class }; @@ -228,7 +231,11 @@ public abstract class ImageWriterSpi extends ImageReaderWriterSpi { throw new IllegalArgumentException ("outputTypes.length == 0!"); } - this.outputTypes = (Class[])outputTypes.clone(); + + this.outputTypes = (outputTypes == STANDARD_OUTPUT_TYPE) ? + new Class[] { ImageOutputStream.class } : + outputTypes.clone(); + // If length == 0, leave it null if (readerSpiNames != null && readerSpiNames.length > 0) { this.readerSpiNames = (String[])readerSpiNames.clone(); From 8fdb1d367a6988246045d77dba7ce3e9b4eab893 Mon Sep 17 00:00:00 2001 From: Andrew Brygin Date: Fri, 8 May 2009 15:57:33 +0400 Subject: [PATCH 010/215] 6657133: Mutable statics in imageio plugins (findbugs) Reviewed-by: prr --- .../com/sun/imageio/stream/StreamCloser.java | 44 +++++++++++++------ .../plugins/bmp/BMPImageWriteParam.java | 2 +- .../stream/FileCacheImageInputStream.java | 10 ++++- .../stream/FileCacheImageOutputStream.java | 10 ++++- jdk/src/share/lib/security/java.security | 2 +- .../share/lib/security/java.security-solaris | 2 +- .../share/lib/security/java.security-windows | 2 +- 7 files changed, 51 insertions(+), 21 deletions(-) diff --git a/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java b/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java index 03c6ce32364..96e5646f782 100644 --- a/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java +++ b/jdk/src/share/classes/com/sun/imageio/stream/StreamCloser.java @@ -43,35 +43,35 @@ import javax.imageio.stream.ImageInputStream; */ public class StreamCloser { - private static WeakHashMap toCloseQueue; + private static WeakHashMap toCloseQueue; private static Thread streamCloser; - public static void addToQueue(ImageInputStream iis) { + public static void addToQueue(CloseAction ca) { synchronized (StreamCloser.class) { if (toCloseQueue == null) { toCloseQueue = - new WeakHashMap(); + new WeakHashMap(); } - toCloseQueue.put(iis, null); + toCloseQueue.put(ca, null); if (streamCloser == null) { final Runnable streamCloserRunnable = new Runnable() { public void run() { if (toCloseQueue != null) { synchronized (StreamCloser.class) { - Set set = + Set set = toCloseQueue.keySet(); // Make a copy of the set in order to avoid // concurrent modification (the is.close() // will in turn call removeFromQueue()) - ImageInputStream[] streams = - new ImageInputStream[set.size()]; - streams = set.toArray(streams); - for (ImageInputStream is : streams) { - if (is != null) { + CloseAction[] actions = + new CloseAction[set.size()]; + actions = set.toArray(actions); + for (CloseAction ca : actions) { + if (ca != null) { try { - is.close(); + ca.performAction(); } catch (IOException e) { } } @@ -106,10 +106,28 @@ public class StreamCloser { } } - public static void removeFromQueue(ImageInputStream iis) { + public static void removeFromQueue(CloseAction ca) { synchronized (StreamCloser.class) { if (toCloseQueue != null) { - toCloseQueue.remove(iis); + toCloseQueue.remove(ca); + } + } + } + + public static CloseAction createCloseAction(ImageInputStream iis) { + return new CloseAction(iis); + } + + public static final class CloseAction { + private ImageInputStream iis; + + private CloseAction(ImageInputStream iis) { + this.iis = iis; + } + + public void performAction() throws IOException { + if (iis != null) { + iis.close(); } } } diff --git a/jdk/src/share/classes/javax/imageio/plugins/bmp/BMPImageWriteParam.java b/jdk/src/share/classes/javax/imageio/plugins/bmp/BMPImageWriteParam.java index ec3acf2e9db..e11057f2a48 100644 --- a/jdk/src/share/classes/javax/imageio/plugins/bmp/BMPImageWriteParam.java +++ b/jdk/src/share/classes/javax/imageio/plugins/bmp/BMPImageWriteParam.java @@ -78,7 +78,7 @@ public class BMPImageWriteParam extends ImageWriteParam { super(locale); // Set compression types ("BI_RGB" denotes uncompressed). - compressionTypes = BMPConstants.compressionTypeNames; + compressionTypes = BMPConstants.compressionTypeNames.clone(); // Set compression flag. canWriteCompressed = true; diff --git a/jdk/src/share/classes/javax/imageio/stream/FileCacheImageInputStream.java b/jdk/src/share/classes/javax/imageio/stream/FileCacheImageInputStream.java index ad03d65c04d..1bff7746344 100644 --- a/jdk/src/share/classes/javax/imageio/stream/FileCacheImageInputStream.java +++ b/jdk/src/share/classes/javax/imageio/stream/FileCacheImageInputStream.java @@ -62,6 +62,10 @@ public class FileCacheImageInputStream extends ImageInputStreamImpl { /** The DisposerRecord that closes the underlying cache. */ private final DisposerRecord disposerRecord; + /** The CloseAction that closes the stream in + * the StreamCloser's shutdown hook */ + private final StreamCloser.CloseAction closeAction; + /** * Constructs a FileCacheImageInputStream that will read * from a given InputStream. @@ -96,7 +100,9 @@ public class FileCacheImageInputStream extends ImageInputStreamImpl { this.cacheFile = File.createTempFile("imageio", ".tmp", cacheDir); this.cache = new RandomAccessFile(cacheFile, "rw"); - StreamCloser.addToQueue(this); + + this.closeAction = StreamCloser.createCloseAction(this); + StreamCloser.addToQueue(closeAction); disposerRecord = new StreamDisposerRecord(cacheFile, cache); if (getClass() == FileCacheImageInputStream.class) { @@ -242,7 +248,7 @@ public class FileCacheImageInputStream extends ImageInputStreamImpl { stream = null; cache = null; cacheFile = null; - StreamCloser.removeFromQueue(this); + StreamCloser.removeFromQueue(closeAction); } /** diff --git a/jdk/src/share/classes/javax/imageio/stream/FileCacheImageOutputStream.java b/jdk/src/share/classes/javax/imageio/stream/FileCacheImageOutputStream.java index f6387125499..f079e8e81fa 100644 --- a/jdk/src/share/classes/javax/imageio/stream/FileCacheImageOutputStream.java +++ b/jdk/src/share/classes/javax/imageio/stream/FileCacheImageOutputStream.java @@ -48,6 +48,10 @@ public class FileCacheImageOutputStream extends ImageOutputStreamImpl { // Pos after last (rightmost) byte written private long maxStreamPos = 0L; + /** The CloseAction that closes the stream in + * the StreamCloser's shutdown hook */ + private final StreamCloser.CloseAction closeAction; + /** * Constructs a FileCacheImageOutputStream that will write * to a given outputStream. @@ -82,7 +86,9 @@ public class FileCacheImageOutputStream extends ImageOutputStreamImpl { this.cacheFile = File.createTempFile("imageio", ".tmp", cacheDir); this.cache = new RandomAccessFile(cacheFile, "rw"); - StreamCloser.addToQueue(this); + + this.closeAction = StreamCloser.createCloseAction(this); + StreamCloser.addToQueue(closeAction); } public int read() throws IOException { @@ -227,7 +233,7 @@ public class FileCacheImageOutputStream extends ImageOutputStreamImpl { cacheFile = null; stream.flush(); stream = null; - StreamCloser.removeFromQueue(this); + StreamCloser.removeFromQueue(closeAction); } public void flushBefore(long pos) throws IOException { diff --git a/jdk/src/share/lib/security/java.security b/jdk/src/share/lib/security/java.security index eadfe715b51..c2a07506c15 100644 --- a/jdk/src/share/lib/security/java.security +++ b/jdk/src/share/lib/security/java.security @@ -127,7 +127,7 @@ system.scope=sun.security.provider.IdentityDatabase # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun. +package.access=sun.,com.sun.imageio. # # List of comma-separated packages that start with or equal this string diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris index 58fbc9d15cd..05dfcb17728 100644 --- a/jdk/src/share/lib/security/java.security-solaris +++ b/jdk/src/share/lib/security/java.security-solaris @@ -128,7 +128,7 @@ system.scope=sun.security.provider.IdentityDatabase # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun. +package.access=sun.,com.sun.imageio. # # List of comma-separated packages that start with or equal this string diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows index 25de17d5247..062b85b63c3 100644 --- a/jdk/src/share/lib/security/java.security-windows +++ b/jdk/src/share/lib/security/java.security-windows @@ -128,7 +128,7 @@ system.scope=sun.security.provider.IdentityDatabase # passed to checkPackageAccess unless the # corresponding RuntimePermission ("accessClassInPackage."+package) has # been granted. -package.access=sun. +package.access=sun.,com.sun.imageio. # # List of comma-separated packages that start with or equal this string From 813ad65e9a7847816c206e194c4b8d297ed3ca17 Mon Sep 17 00:00:00 2001 From: Andrew Brygin Date: Fri, 8 May 2009 16:15:15 +0400 Subject: [PATCH 011/215] 6823373: [ZDI-CAN-460] Java Web Start JPEG header parsing needs more scruity Reviewed-by: igor --- .../sun/awt/splashscreen/splashscreen_jpeg.c | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c index 09d38fcb422..5d250e9e4b3 100644 --- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c +++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c @@ -139,21 +139,45 @@ SplashDecodeJpeg(Splash * splash, struct jpeg_decompress_struct *cinfo) splash->width = cinfo->output_width; splash->height = cinfo->output_height; + + if (!SAFE_TO_ALLOC(splash->imageFormat.depthBytes, splash->width)) { + return 0; + } stride = splash->width * splash->imageFormat.depthBytes; + if (!SAFE_TO_ALLOC(stride, splash->height)) { + return 0; + } + if (!SAFE_TO_ALLOC(cinfo->output_width, cinfo->output_components)) { + return 0; + } + splash->frameCount = 1; splash->frames = (SplashImage *) malloc(sizeof(SplashImage) * splash->frameCount); + if (splash->frames == NULL) { + return 0; + } memset(splash->frames, 0, sizeof(SplashImage) * splash->frameCount); + splash->loopCount = 1; - splash->frames[0].bitmapBits = malloc(stride * splash->height); splash->frames[0].delay = 0; + splash->frames[0].bitmapBits = malloc(stride * splash->height); + if (splash->frames[0].bitmapBits == NULL) { + free(splash->frames); + return 0; + } rowStride = cinfo->output_width * cinfo->output_components; buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, rowStride, 1); + if (buffer == NULL) { + free(splash->frames[0].bitmapBits); + free(splash->frames); + return 0; + } initFormat(&srcFormat, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000); srcFormat.byteOrder = BYTE_ORDER_LSBFIRST; From ce7e28f3e6e44f6558968cb731d6fb5a90f29d9d Mon Sep 17 00:00:00 2001 From: Chris Hegarty Date: Tue, 12 May 2009 16:32:34 +0100 Subject: [PATCH 012/215] 6801071: Remote sites can compromise user privacy and possibly hijack web sessions Reviewed-by: jccollet, hawtin --- jdk/make/sun/net/FILES_java.gmk | 1 + jdk/src/share/classes/java/net/Socket.java | 2 +- .../classes/java/net/SocksSocketImpl.java | 25 ++++++++--- jdk/src/share/classes/java/net/URL.java | 2 +- .../classes/sun/net/ApplicationProxy.java | 43 +++++++++++++++++++ .../www/protocol/http/HttpURLConnection.java | 18 +++++--- 6 files changed, 78 insertions(+), 13 deletions(-) create mode 100644 jdk/src/share/classes/sun/net/ApplicationProxy.java diff --git a/jdk/make/sun/net/FILES_java.gmk b/jdk/make/sun/net/FILES_java.gmk index 1ab771a37f1..00b6223b8da 100644 --- a/jdk/make/sun/net/FILES_java.gmk +++ b/jdk/make/sun/net/FILES_java.gmk @@ -24,6 +24,7 @@ # FILES_java = \ + sun/net/ApplicationProxy.java \ sun/net/InetAddressCachePolicy.java \ sun/net/URLCanonicalizer.java \ sun/net/NetworkClient.java \ diff --git a/jdk/src/share/classes/java/net/Socket.java b/jdk/src/share/classes/java/net/Socket.java index 110a6a5f1a9..39dfebd4180 100644 --- a/jdk/src/share/classes/java/net/Socket.java +++ b/jdk/src/share/classes/java/net/Socket.java @@ -118,7 +118,7 @@ class Socket implements java.io.Closeable { if (proxy == null) { throw new IllegalArgumentException("Invalid Proxy"); } - Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : new Proxy(proxy.type(), proxy.address()); + Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy); if (p.type() == Proxy.Type.SOCKS) { SecurityManager security = System.getSecurityManager(); InetSocketAddress epoint = (InetSocketAddress) p.address(); diff --git a/jdk/src/share/classes/java/net/SocksSocketImpl.java b/jdk/src/share/classes/java/net/SocksSocketImpl.java index e73b6c9467e..4561b6e1e56 100644 --- a/jdk/src/share/classes/java/net/SocksSocketImpl.java +++ b/jdk/src/share/classes/java/net/SocksSocketImpl.java @@ -47,6 +47,9 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { private Socket cmdsock = null; private InputStream cmdIn = null; private OutputStream cmdOut = null; + /* true if the Proxy has been set programatically */ + private boolean applicationSetProxy; /* false */ + SocksSocketImpl() { // Nothing needed @@ -64,6 +67,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { // Use getHostString() to avoid reverse lookups server = ad.getHostString(); port = ad.getPort(); + applicationSetProxy = true; } } @@ -165,8 +169,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { throw (IOException) pae.getException(); } } else { - userName = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("user.name")); + userName = getUserName(); } } if (userName == null) @@ -267,8 +270,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { out.write((endpoint.getPort() >> 8) & 0xff); out.write((endpoint.getPort() >> 0) & 0xff); out.write(endpoint.getAddress().getAddress()); - String userName = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("user.name")); + String userName = getUserName(); try { out.write(userName.getBytes("ISO-8859-1")); } catch (java.io.UnsupportedEncodingException uee) { @@ -588,8 +590,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { out.write((super.getLocalPort() >> 8) & 0xff); out.write((super.getLocalPort() >> 0) & 0xff); out.write(addr1); - String userName = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("user.name")); + String userName = getUserName(); try { out.write(userName.getBytes("ISO-8859-1")); } catch (java.io.UnsupportedEncodingException uee) { @@ -1052,4 +1053,16 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { super.close(); } + private String getUserName() { + String userName = ""; + if (applicationSetProxy) { + try { + userName = System.getProperty("user.name"); + } catch (SecurityException se) { /* swallow Exception */ } + } else { + userName = java.security.AccessController.doPrivileged( + new sun.security.action.GetPropertyAction("user.name")); + } + return userName; + } } diff --git a/jdk/src/share/classes/java/net/URL.java b/jdk/src/share/classes/java/net/URL.java index 73818e960d8..33cfe039654 100644 --- a/jdk/src/share/classes/java/net/URL.java +++ b/jdk/src/share/classes/java/net/URL.java @@ -1005,7 +1005,7 @@ public final class URL implements java.io.Serializable { } // Create a copy of Proxy as a security measure - Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : new Proxy(proxy.type(), proxy.address()); + Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy); SecurityManager sm = System.getSecurityManager(); if (p.type() != Proxy.Type.DIRECT && sm != null) { InetSocketAddress epoint = (InetSocketAddress) p.address(); diff --git a/jdk/src/share/classes/sun/net/ApplicationProxy.java b/jdk/src/share/classes/sun/net/ApplicationProxy.java new file mode 100644 index 00000000000..2c84e3649e3 --- /dev/null +++ b/jdk/src/share/classes/sun/net/ApplicationProxy.java @@ -0,0 +1,43 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.net; + +import java.net.Proxy; +import java.net.SocketAddress; + +/** + * Proxy wrapper class so that we can determine application set + * proxies by type. + */ +public final class ApplicationProxy extends Proxy { + private ApplicationProxy(Proxy proxy) { + super(proxy.type(), proxy.address()); + } + + public static ApplicationProxy create(Proxy proxy) { + return new ApplicationProxy(proxy); + } +} diff --git a/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 6f3250b30eb..9f5d7303abc 100644 --- a/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -575,12 +575,20 @@ public class HttpURLConnection extends java.net.HttpURLConnection { responses = new MessageHeader(); this.handler = handler; instProxy = p; - cookieHandler = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + if (instProxy instanceof sun.net.ApplicationProxy) { + /* Application set Proxies should not have access to cookies + * in a secure environment unless explicitly allowed. */ + try { + cookieHandler = CookieHandler.getDefault(); + } catch (SecurityException se) { /* swallow exception */ } + } else { + cookieHandler = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { public CookieHandler run() { - return CookieHandler.getDefault(); - } - }); + return CookieHandler.getDefault(); + } + }); + } cacheHandler = java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public ResponseCache run() { From 28848d3300bdbb324ab81bdf4b4d9d14d349ed1a Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Wed, 13 May 2009 13:52:52 +0400 Subject: [PATCH 013/215] 6657625: RmfFileReader/StandardMidiFileWriter.types are public mutable statics (findbugs) Reviewed-by: hawtin --- .../classes/com/sun/media/sound/StandardMidiFileWriter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java b/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java index 533104fa707..fce29478ada 100644 --- a/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java +++ b/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1999-2009 Sun Microsystems, Inc. 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 @@ -82,7 +82,7 @@ public class StandardMidiFileWriter extends MidiFileWriter { /** * MIDI parser types */ - public static final int types[] = { + private static final int types[] = { MIDI_TYPE_0, MIDI_TYPE_1 }; From 00b701fedae519097ea4f8c3b1f5f95c6d2cd117 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Wed, 13 May 2009 14:32:14 +0400 Subject: [PATCH 014/215] 6738524: JDK13Services allows read access to system properties from untrusted code Reviewed-by: hawtin --- .../com/sun/media/sound/JDK13Services.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java index 2b588ceef8d..fd477285770 100644 --- a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java +++ b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1999-2009 Sun Microsystems, Inc. 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 @@ -41,6 +41,15 @@ import javax.sound.midi.spi.MidiFileWriter; import javax.sound.midi.spi.SoundbankReader; import javax.sound.midi.spi.MidiDeviceProvider; +import javax.sound.midi.Receiver; +import javax.sound.midi.Sequencer; +import javax.sound.midi.Synthesizer; +import javax.sound.midi.Transmitter; +import javax.sound.sampled.Clip; +import javax.sound.sampled.Port; +import javax.sound.sampled.SourceDataLine; +import javax.sound.sampled.TargetDataLine; + /** * JDK13Services uses the Service class in JDK 1.3 @@ -186,6 +195,16 @@ public class JDK13Services { If the property is not set, null is returned. */ private static synchronized String getDefaultProvider(Class typeClass) { + if (!SourceDataLine.class.equals(typeClass) + && !TargetDataLine.class.equals(typeClass) + && !Clip.class.equals(typeClass) + && !Port.class.equals(typeClass) + && !Receiver.class.equals(typeClass) + && !Transmitter.class.equals(typeClass) + && !Synthesizer.class.equals(typeClass) + && !Sequencer.class.equals(typeClass)) { + return null; + } String value; String propertyName = typeClass.getName(); value = JSSecurityManager.getProperty(propertyName); From 272f5e12f9e369834173681913c17b7e5c23a3c3 Mon Sep 17 00:00:00 2001 From: Alex Menkov Date: Wed, 13 May 2009 14:32:33 +0400 Subject: [PATCH 015/215] 6777448: JDK13Services.getProviders creates instances with full privileges [hawtin, alexp] Reviewed-by: hawtin, alexp --- .../sun/media/sound/JSSecurityManager.java | 55 +++++++++++-------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java b/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java index 253d22c1e93..064e5c4ba04 100644 --- a/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java +++ b/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1999-2009 Sun Microsystems, Inc. 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 @@ -283,28 +283,37 @@ class JSSecurityManager { static List getProviders(final Class providerClass) { - PrivilegedAction action = new PrivilegedAction() { - public Object run() { - List p = new ArrayList(); - Iterator ps = Service.providers(providerClass); - while (ps.hasNext()) { - try { - Object provider = ps.next(); - if (providerClass.isInstance(provider)) { - // $$mp 2003-08-22 - // Always adding at the beginning reverses the - // order of the providers. So we no longer have - // to do this in AudioSystem and MidiSystem. - p.add(0, provider); - } - } catch (Throwable t) { - //$$fb 2002-11-07: do not fail on SPI not found - if (Printer.err) t.printStackTrace(); - } } - return p; + List p = new ArrayList(); + // Service.providers(Class) just creates "lazy" iterator instance, + // so it doesn't require do be called from privileged section + final Iterator ps = Service.providers(providerClass); + + // the iterator's hasNext() method looks through classpath for + // the provider class names, so it requires read permissions + PrivilegedAction hasNextAction = new PrivilegedAction() { + public Boolean run() { + return ps.hasNext(); + } + }; + + while (AccessController.doPrivileged(hasNextAction)) { + try { + // the iterator's next() method creates instances of the + // providers and it should be called in the current security + // context + Object provider = ps.next(); + if (providerClass.isInstance(provider)) { + // $$mp 2003-08-22 + // Always adding at the beginning reverses the + // order of the providers. So we no longer have + // to do this in AudioSystem and MidiSystem. + p.add(0, provider); } - }; - List providers = (List) AccessController.doPrivileged(action); - return providers; + } catch (Throwable t) { + //$$fb 2002-11-07: do not fail on SPI not found + if (Printer.err) t.printStackTrace(); + } + } + return p; } } From 0681d1454c1758bbb76ba3073b2f4116a66109da Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 18 Jun 2009 14:08:07 +0400 Subject: [PATCH 016/215] 6660049: Synth Region.uiToRegionMap/lowerCaseNameMap are mutable statics Reviewed-by: hawtin --- .../javax/swing/plaf/synth/Region.java | 288 ++++++++++-------- .../javax/swing/plaf/synth/Test6660049.java | 123 ++++++++ 2 files changed, 287 insertions(+), 124 deletions(-) create mode 100644 jdk/test/javax/swing/plaf/synth/Test6660049.java diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/Region.java b/jdk/src/share/classes/javax/swing/plaf/synth/Region.java index c7de782ba59..1ecd999896d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/Region.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/Region.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2009 Sun Microsystems, Inc. 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 @@ -24,8 +24,13 @@ */ package javax.swing.plaf.synth; -import javax.swing.*; -import java.util.*; +import sun.awt.AppContext; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import javax.swing.JComponent; +import javax.swing.UIDefaults; /** * A distinct rendering area of a Swing component. A component may @@ -67,8 +72,8 @@ import java.util.*; * @author Scott Violet */ public class Region { - private static final Map uiToRegionMap = new HashMap(); - private static final Map lowerCaseNameMap = new HashMap(); + private static final Object UI_TO_REGION_MAP_KEY = new Object(); + private static final Object LOWER_CASE_NAME_MAP_KEY = new Object(); /** * ArrowButton's are special types of buttons that also render a @@ -77,396 +82,433 @@ public class Region { * To bind a style to this Region use the name * ArrowButton. */ - public static final Region ARROW_BUTTON = new Region("ArrowButton", - "ArrowButtonUI"); + public static final Region ARROW_BUTTON = new Region("ArrowButton", false); /** * Button region. To bind a style to this Region use the name * Button. */ - public static final Region BUTTON = new Region("Button", - "ButtonUI"); + public static final Region BUTTON = new Region("Button", false); /** * CheckBox region. To bind a style to this Region use the name * CheckBox. */ - public static final Region CHECK_BOX = new Region("CheckBox", - "CheckBoxUI"); + public static final Region CHECK_BOX = new Region("CheckBox", false); /** * CheckBoxMenuItem region. To bind a style to this Region use * the name CheckBoxMenuItem. */ - public static final Region CHECK_BOX_MENU_ITEM = new Region( - "CheckBoxMenuItem", "CheckBoxMenuItemUI"); + public static final Region CHECK_BOX_MENU_ITEM = new Region("CheckBoxMenuItem", false); /** * ColorChooser region. To bind a style to this Region use * the name ColorChooser. */ - public static final Region COLOR_CHOOSER = new Region( - "ColorChooser", "ColorChooserUI"); + public static final Region COLOR_CHOOSER = new Region("ColorChooser", false); /** * ComboBox region. To bind a style to this Region use * the name ComboBox. */ - public static final Region COMBO_BOX = new Region( - "ComboBox", "ComboBoxUI"); + public static final Region COMBO_BOX = new Region("ComboBox", false); /** * DesktopPane region. To bind a style to this Region use * the name DesktopPane. */ - public static final Region DESKTOP_PANE = new Region("DesktopPane", - "DesktopPaneUI"); + public static final Region DESKTOP_PANE = new Region("DesktopPane", false); + /** * DesktopIcon region. To bind a style to this Region use * the name DesktopIcon. */ - public static final Region DESKTOP_ICON = new Region("DesktopIcon", - "DesktopIconUI"); + public static final Region DESKTOP_ICON = new Region("DesktopIcon", false); /** * EditorPane region. To bind a style to this Region use * the name EditorPane. */ - public static final Region EDITOR_PANE = new Region("EditorPane", - "EditorPaneUI"); + public static final Region EDITOR_PANE = new Region("EditorPane", false); /** * FileChooser region. To bind a style to this Region use * the name FileChooser. */ - public static final Region FILE_CHOOSER = new Region("FileChooser", - "FileChooserUI"); + public static final Region FILE_CHOOSER = new Region("FileChooser", false); /** * FormattedTextField region. To bind a style to this Region use * the name FormattedTextField. */ - public static final Region FORMATTED_TEXT_FIELD = new Region( - "FormattedTextField", "FormattedTextFieldUI"); + public static final Region FORMATTED_TEXT_FIELD = new Region("FormattedTextField", false); /** * InternalFrame region. To bind a style to this Region use * the name InternalFrame. */ - public static final Region INTERNAL_FRAME = new Region("InternalFrame", - "InternalFrameUI"); + public static final Region INTERNAL_FRAME = new Region("InternalFrame", false); + /** * TitlePane of an InternalFrame. The TitlePane typically * shows a menu, title, widgets to manipulate the internal frame. * To bind a style to this Region use the name * InternalFrameTitlePane. */ - public static final Region INTERNAL_FRAME_TITLE_PANE = - new Region("InternalFrameTitlePane", - "InternalFrameTitlePaneUI"); + public static final Region INTERNAL_FRAME_TITLE_PANE = new Region("InternalFrameTitlePane", false); /** * Label region. To bind a style to this Region use the name * Label. */ - public static final Region LABEL = new Region("Label", "LabelUI"); + public static final Region LABEL = new Region("Label", false); /** * List region. To bind a style to this Region use the name * List. */ - public static final Region LIST = new Region("List", "ListUI"); + public static final Region LIST = new Region("List", false); /** * Menu region. To bind a style to this Region use the name * Menu. */ - public static final Region MENU = new Region("Menu", "MenuUI"); + public static final Region MENU = new Region("Menu", false); /** * MenuBar region. To bind a style to this Region use the name * MenuBar. */ - public static final Region MENU_BAR = new Region("MenuBar", "MenuBarUI"); + public static final Region MENU_BAR = new Region("MenuBar", false); /** * MenuItem region. To bind a style to this Region use the name * MenuItem. */ - public static final Region MENU_ITEM = new Region("MenuItem","MenuItemUI"); + public static final Region MENU_ITEM = new Region("MenuItem", false); /** * Accelerator region of a MenuItem. To bind a style to this * Region use the name MenuItemAccelerator. */ - public static final Region MENU_ITEM_ACCELERATOR = new Region( - "MenuItemAccelerator"); + public static final Region MENU_ITEM_ACCELERATOR = new Region("MenuItemAccelerator", true); /** * OptionPane region. To bind a style to this Region use * the name OptionPane. */ - public static final Region OPTION_PANE = new Region("OptionPane", - "OptionPaneUI"); + public static final Region OPTION_PANE = new Region("OptionPane", false); /** * Panel region. To bind a style to this Region use the name * Panel. */ - public static final Region PANEL = new Region("Panel", "PanelUI"); + public static final Region PANEL = new Region("Panel", false); /** * PasswordField region. To bind a style to this Region use * the name PasswordField. */ - public static final Region PASSWORD_FIELD = new Region("PasswordField", - "PasswordFieldUI"); + public static final Region PASSWORD_FIELD = new Region("PasswordField", false); /** * PopupMenu region. To bind a style to this Region use * the name PopupMenu. */ - public static final Region POPUP_MENU = new Region("PopupMenu", - "PopupMenuUI"); + public static final Region POPUP_MENU = new Region("PopupMenu", false); /** * PopupMenuSeparator region. To bind a style to this Region * use the name PopupMenuSeparator. */ - public static final Region POPUP_MENU_SEPARATOR = new Region( - "PopupMenuSeparator", "PopupMenuSeparatorUI"); + public static final Region POPUP_MENU_SEPARATOR = new Region("PopupMenuSeparator", false); /** * ProgressBar region. To bind a style to this Region * use the name ProgressBar. */ - public static final Region PROGRESS_BAR = new Region("ProgressBar", - "ProgressBarUI"); + public static final Region PROGRESS_BAR = new Region("ProgressBar", false); /** * RadioButton region. To bind a style to this Region * use the name RadioButton. */ - public static final Region RADIO_BUTTON = new Region( - "RadioButton", "RadioButtonUI"); + public static final Region RADIO_BUTTON = new Region("RadioButton", false); /** * RegionButtonMenuItem region. To bind a style to this Region * use the name RadioButtonMenuItem. */ - public static final Region RADIO_BUTTON_MENU_ITEM = new Region( - "RadioButtonMenuItem", "RadioButtonMenuItemUI"); + public static final Region RADIO_BUTTON_MENU_ITEM = new Region("RadioButtonMenuItem", false); /** * RootPane region. To bind a style to this Region use * the name RootPane. */ - public static final Region ROOT_PANE = new Region("RootPane", - "RootPaneUI"); + public static final Region ROOT_PANE = new Region("RootPane", false); /** * ScrollBar region. To bind a style to this Region use * the name ScrollBar. */ - public static final Region SCROLL_BAR = new Region("ScrollBar", - "ScrollBarUI"); + public static final Region SCROLL_BAR = new Region("ScrollBar", false); + /** * Track of the ScrollBar. To bind a style to this Region use * the name ScrollBarTrack. */ - public static final Region SCROLL_BAR_TRACK = new Region("ScrollBarTrack"); + public static final Region SCROLL_BAR_TRACK = new Region("ScrollBarTrack", true); + /** * Thumb of the ScrollBar. The thumb is the region of the ScrollBar * that gives a graphical depiction of what percentage of the View is * currently visible. To bind a style to this Region use * the name ScrollBarThumb. */ - public static final Region SCROLL_BAR_THUMB = new Region("ScrollBarThumb"); + public static final Region SCROLL_BAR_THUMB = new Region("ScrollBarThumb", true); /** * ScrollPane region. To bind a style to this Region use * the name ScrollPane. */ - public static final Region SCROLL_PANE = new Region("ScrollPane", - "ScrollPaneUI"); + public static final Region SCROLL_PANE = new Region("ScrollPane", false); /** * Separator region. To bind a style to this Region use * the name Separator. */ - public static final Region SEPARATOR = new Region("Separator", - "SeparatorUI"); + public static final Region SEPARATOR = new Region("Separator", false); /** * Slider region. To bind a style to this Region use * the name Slider. */ - public static final Region SLIDER = new Region("Slider", "SliderUI"); + public static final Region SLIDER = new Region("Slider", false); + /** * Track of the Slider. To bind a style to this Region use * the name SliderTrack. */ - public static final Region SLIDER_TRACK = new Region("SliderTrack"); + public static final Region SLIDER_TRACK = new Region("SliderTrack", true); + /** * Thumb of the Slider. The thumb of the Slider identifies the current * value. To bind a style to this Region use the name * SliderThumb. */ - public static final Region SLIDER_THUMB = new Region("SliderThumb"); + public static final Region SLIDER_THUMB = new Region("SliderThumb", true); /** * Spinner region. To bind a style to this Region use the name * Spinner. */ - public static final Region SPINNER = new Region("Spinner", "SpinnerUI"); + public static final Region SPINNER = new Region("Spinner", false); /** * SplitPane region. To bind a style to this Region use the name * SplitPane. */ - public static final Region SPLIT_PANE = new Region("SplitPane", - "SplitPaneUI"); + public static final Region SPLIT_PANE = new Region("SplitPane", false); /** * Divider of the SplitPane. To bind a style to this Region * use the name SplitPaneDivider. */ - public static final Region SPLIT_PANE_DIVIDER = new Region( - "SplitPaneDivider"); + public static final Region SPLIT_PANE_DIVIDER = new Region("SplitPaneDivider", true); /** * TabbedPane region. To bind a style to this Region use * the name TabbedPane. */ - public static final Region TABBED_PANE = new Region("TabbedPane", - "TabbedPaneUI"); + public static final Region TABBED_PANE = new Region("TabbedPane", false); + /** * Region of a TabbedPane for one tab. To bind a style to this * Region use the name TabbedPaneTab. */ - public static final Region TABBED_PANE_TAB = new Region("TabbedPaneTab"); + public static final Region TABBED_PANE_TAB = new Region("TabbedPaneTab", true); + /** * Region of a TabbedPane containing the tabs. To bind a style to this * Region use the name TabbedPaneTabArea. */ - public static final Region TABBED_PANE_TAB_AREA = - new Region("TabbedPaneTabArea"); + public static final Region TABBED_PANE_TAB_AREA = new Region("TabbedPaneTabArea", true); + /** * Region of a TabbedPane containing the content. To bind a style to this * Region use the name TabbedPaneContent. */ - public static final Region TABBED_PANE_CONTENT = - new Region("TabbedPaneContent"); + public static final Region TABBED_PANE_CONTENT = new Region("TabbedPaneContent", true); /** * Table region. To bind a style to this Region use * the name Table. */ - public static final Region TABLE = new Region("Table", "TableUI"); + public static final Region TABLE = new Region("Table", false); /** * TableHeader region. To bind a style to this Region use * the name TableHeader. */ - public static final Region TABLE_HEADER = new Region("TableHeader", - "TableHeaderUI"); + public static final Region TABLE_HEADER = new Region("TableHeader", false); + /** * TextArea region. To bind a style to this Region use * the name TextArea. */ - public static final Region TEXT_AREA = new Region("TextArea", - "TextAreaUI"); + public static final Region TEXT_AREA = new Region("TextArea", false); /** * TextField region. To bind a style to this Region use * the name TextField. */ - public static final Region TEXT_FIELD = new Region("TextField", - "TextFieldUI"); + public static final Region TEXT_FIELD = new Region("TextField", false); /** * TextPane region. To bind a style to this Region use * the name TextPane. */ - public static final Region TEXT_PANE = new Region("TextPane", - "TextPaneUI"); + public static final Region TEXT_PANE = new Region("TextPane", false); /** * ToggleButton region. To bind a style to this Region use * the name ToggleButton. */ - public static final Region TOGGLE_BUTTON = new Region("ToggleButton", - "ToggleButtonUI"); + public static final Region TOGGLE_BUTTON = new Region("ToggleButton", false); /** * ToolBar region. To bind a style to this Region use * the name ToolBar. */ - public static final Region TOOL_BAR = new Region("ToolBar", "ToolBarUI"); + public static final Region TOOL_BAR = new Region("ToolBar", false); + /** * Region of the ToolBar containing the content. To bind a style to this * Region use the name ToolBarContent. */ - public static final Region TOOL_BAR_CONTENT = new Region("ToolBarContent"); + public static final Region TOOL_BAR_CONTENT = new Region("ToolBarContent", true); + /** * Region for the Window containing the ToolBar. To bind a style to this * Region use the name ToolBarDragWindow. */ - public static final Region TOOL_BAR_DRAG_WINDOW = new Region( - "ToolBarDragWindow", null, false); + public static final Region TOOL_BAR_DRAG_WINDOW = new Region("ToolBarDragWindow", false); /** * ToolTip region. To bind a style to this Region use * the name ToolTip. */ - public static final Region TOOL_TIP = new Region("ToolTip", "ToolTipUI"); + public static final Region TOOL_TIP = new Region("ToolTip", false); /** * ToolBar separator region. To bind a style to this Region use * the name ToolBarSeparator. */ - public static final Region TOOL_BAR_SEPARATOR = new Region( - "ToolBarSeparator", "ToolBarSeparatorUI"); + public static final Region TOOL_BAR_SEPARATOR = new Region("ToolBarSeparator", false); /** * Tree region. To bind a style to this Region use the name * Tree. */ - public static final Region TREE = new Region("Tree", "TreeUI"); + public static final Region TREE = new Region("Tree", false); + /** * Region of the Tree for one cell. To bind a style to this * Region use the name TreeCell. */ - public static final Region TREE_CELL = new Region("TreeCell"); + public static final Region TREE_CELL = new Region("TreeCell", true); /** * Viewport region. To bind a style to this Region use * the name Viewport. */ - public static final Region VIEWPORT = new Region("Viewport", "ViewportUI"); + public static final Region VIEWPORT = new Region("Viewport", false); + private static Map getUItoRegionMap() { + AppContext context = AppContext.getAppContext(); + Map map = (Map) context.get(UI_TO_REGION_MAP_KEY); + if (map == null) { + map = new HashMap(); + map.put("ArrowButtonUI", ARROW_BUTTON); + map.put("ButtonUI", BUTTON); + map.put("CheckBoxUI", CHECK_BOX); + map.put("CheckBoxMenuItemUI", CHECK_BOX_MENU_ITEM); + map.put("ColorChooserUI", COLOR_CHOOSER); + map.put("ComboBoxUI", COMBO_BOX); + map.put("DesktopPaneUI", DESKTOP_PANE); + map.put("DesktopIconUI", DESKTOP_ICON); + map.put("EditorPaneUI", EDITOR_PANE); + map.put("FileChooserUI", FILE_CHOOSER); + map.put("FormattedTextFieldUI", FORMATTED_TEXT_FIELD); + map.put("InternalFrameUI", INTERNAL_FRAME); + map.put("InternalFrameTitlePaneUI", INTERNAL_FRAME_TITLE_PANE); + map.put("LabelUI", LABEL); + map.put("ListUI", LIST); + map.put("MenuUI", MENU); + map.put("MenuBarUI", MENU_BAR); + map.put("MenuItemUI", MENU_ITEM); + map.put("OptionPaneUI", OPTION_PANE); + map.put("PanelUI", PANEL); + map.put("PasswordFieldUI", PASSWORD_FIELD); + map.put("PopupMenuUI", POPUP_MENU); + map.put("PopupMenuSeparatorUI", POPUP_MENU_SEPARATOR); + map.put("ProgressBarUI", PROGRESS_BAR); + map.put("RadioButtonUI", RADIO_BUTTON); + map.put("RadioButtonMenuItemUI", RADIO_BUTTON_MENU_ITEM); + map.put("RootPaneUI", ROOT_PANE); + map.put("ScrollBarUI", SCROLL_BAR); + map.put("ScrollPaneUI", SCROLL_PANE); + map.put("SeparatorUI", SEPARATOR); + map.put("SliderUI", SLIDER); + map.put("SpinnerUI", SPINNER); + map.put("SplitPaneUI", SPLIT_PANE); + map.put("TabbedPaneUI", TABBED_PANE); + map.put("TableUI", TABLE); + map.put("TableHeaderUI", TABLE_HEADER); + map.put("TextAreaUI", TEXT_AREA); + map.put("TextFieldUI", TEXT_FIELD); + map.put("TextPaneUI", TEXT_PANE); + map.put("ToggleButtonUI", TOGGLE_BUTTON); + map.put("ToolBarUI", TOOL_BAR); + map.put("ToolTipUI", TOOL_TIP); + map.put("ToolBarSeparatorUI", TOOL_BAR_SEPARATOR); + map.put("TreeUI", TREE); + map.put("ViewportUI", VIEWPORT); + context.put(UI_TO_REGION_MAP_KEY, map); + } + return map; + } - private String name; - private boolean subregion; - + private static Map getLowerCaseNameMap() { + AppContext context = AppContext.getAppContext(); + Map map = (Map) context.get(LOWER_CASE_NAME_MAP_KEY); + if (map == null) { + map = new HashMap(); + context.put(LOWER_CASE_NAME_MAP_KEY, map); + } + return map; + } static Region getRegion(JComponent c) { - return uiToRegionMap.get(c.getUIClassID()); + return getUItoRegionMap().get(c.getUIClassID()); } static void registerUIs(UIDefaults table) { - for (String key : uiToRegionMap.keySet()) { + for (Object key : getUItoRegionMap().keySet()) { table.put(key, "javax.swing.plaf.synth.SynthLookAndFeel"); } } + private final String name; + private final boolean subregion; - Region(String name) { - this(name, null, true); - } - - Region(String name, String ui) { - this(name, ui, false); + private Region(String name, boolean subregion) { + if (name == null) { + throw new NullPointerException("You must specify a non-null name"); + } + this.name = name; + this.subregion = subregion; } /** @@ -481,14 +523,10 @@ public class Region { * @param subregion Whether or not this is a subregion. */ protected Region(String name, String ui, boolean subregion) { - if (name == null) { - throw new NullPointerException("You must specify a non-null name"); - } - this.name = name; + this(name, subregion); if (ui != null) { - uiToRegionMap.put(ui, this); + getUItoRegionMap().put(ui, this); } - this.subregion = subregion; } /** @@ -514,16 +552,17 @@ public class Region { /** * Returns the name, in lowercase. + * + * @return lower case representation of the name of the Region */ String getLowerCaseName() { - synchronized(lowerCaseNameMap) { - String lowerCaseName = lowerCaseNameMap.get(this); - if (lowerCaseName == null) { - lowerCaseName = getName().toLowerCase(); - lowerCaseNameMap.put(this, lowerCaseName); - } - return lowerCaseName; + Map lowerCaseNameMap = getLowerCaseNameMap(); + String lowerCaseName = lowerCaseNameMap.get(this); + if (lowerCaseName == null) { + lowerCaseName = name.toLowerCase(Locale.ENGLISH); + lowerCaseNameMap.put(this, lowerCaseName); } + return lowerCaseName; } /** @@ -531,6 +570,7 @@ public class Region { * * @return name of the Region. */ + @Override public String toString() { return name; } diff --git a/jdk/test/javax/swing/plaf/synth/Test6660049.java b/jdk/test/javax/swing/plaf/synth/Test6660049.java new file mode 100644 index 00000000000..466453a8a60 --- /dev/null +++ b/jdk/test/javax/swing/plaf/synth/Test6660049.java @@ -0,0 +1,123 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6660049 6849518 + * @summary Tests the Region initialization + * @author Sergey Malenkov + */ + +import sun.awt.SunToolkit; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import javax.swing.plaf.synth.Region; +import javax.swing.plaf.synth.SynthLookAndFeel; + +public class Test6660049 implements Runnable { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Test6660049( + javax.swing.JButton.class, + javax.swing.JCheckBox.class, + javax.swing.JCheckBoxMenuItem.class, + javax.swing.JColorChooser.class, + javax.swing.JComboBox.class, + javax.swing.JDesktopPane.class, + javax.swing.JEditorPane.class, + javax.swing.JFileChooser.class, + javax.swing.JFormattedTextField.class, + javax.swing.JInternalFrame.class, + javax.swing.JLabel.class, + javax.swing.JList.class, + javax.swing.JMenu.class, + javax.swing.JMenuBar.class, + javax.swing.JMenuItem.class, + javax.swing.JOptionPane.class, + javax.swing.JPanel.class, + javax.swing.JPasswordField.class, + javax.swing.JPopupMenu.class, + javax.swing.JProgressBar.class, + javax.swing.JRadioButton.class, + javax.swing.JRadioButtonMenuItem.class, + javax.swing.JRootPane.class, + javax.swing.JScrollBar.class, + javax.swing.JScrollPane.class, + javax.swing.JSeparator.class, + javax.swing.JSlider.class, + javax.swing.JSpinner.class, + javax.swing.JSplitPane.class, + javax.swing.JTabbedPane.class, + javax.swing.JTable.class, + javax.swing.JTextArea.class, + javax.swing.JTextField.class, + javax.swing.JTextPane.class, + javax.swing.JToggleButton.class, + javax.swing.JToolBar.class, + javax.swing.JToolTip.class, + javax.swing.JTree.class, + javax.swing.JViewport.class, + javax.swing.table.JTableHeader.class)); + } + + private final Class[] types; + private final Region region; + + private Test6660049(Class... types) { + this.types = types; + run(); + + this.region = new Region("Button", "ButtonUI", true) { + @Override + public String getName() { + throw new Error("6660049: exploit is available"); + } + }; + } + + public void run() { + if (this.region != null) { + SunToolkit.createNewAppContext(); + } + for (Class type : this.types) { + Region region = getRegion(type); + if (region == null) { + throw new Error("6849518: region is not initialized"); + } + } + getRegion(JButton.class).getName(); + } + + private static Region getRegion(Class type) { + try { + return SynthLookAndFeel.getRegion(type.newInstance()); + } + catch (IllegalAccessException exception) { + throw new Error("unexpected exception", exception); + } + catch (InstantiationException exception) { + throw new Error("unexpected exception", exception); + } + } +} From 6b90310fed55e58b749b5d4b1fbbdc67ef227eca Mon Sep 17 00:00:00 2001 From: Abhijit Saha Date: Mon, 22 Jun 2009 13:36:37 -0700 Subject: [PATCH 017/215] 6656610: AccessibleResourceBundle.getContents exposes mutable static (findbugs) Reviewed-by: hawtin --- .../accessibility/AccessibleResourceBundle.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/jdk/src/share/classes/javax/accessibility/AccessibleResourceBundle.java b/jdk/src/share/classes/javax/accessibility/AccessibleResourceBundle.java index b5f23e199fa..ec27c756bde 100644 --- a/jdk/src/share/classes/javax/accessibility/AccessibleResourceBundle.java +++ b/jdk/src/share/classes/javax/accessibility/AccessibleResourceBundle.java @@ -44,15 +44,11 @@ public class AccessibleResourceBundle extends ListResourceBundle { * localized display strings. */ public Object[][] getContents() { - return contents; - } + // The table holding the mapping between the programmatic keys + // and the display strings for the en_US locale. + return new Object[][] { - /** - * The table holding the mapping between the programmatic keys - * and the display strings for the en_US locale. - */ - static final Object[][] contents = { - // LOCALIZE THIS + // LOCALIZE THIS // Role names // { "application","application" }, // { "border","border" }, @@ -151,5 +147,6 @@ public class AccessibleResourceBundle extends ListResourceBundle { { "vertical","vertical" }, { "horizontal","horizontal" } // END OF MATERIAL TO LOCALIZE - }; + }; + } } From 68d0756ea67b3c8655a28193e6725e07d3b8554b Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Tue, 23 Jun 2009 13:54:36 -0400 Subject: [PATCH 018/215] 6824440: XML Signature HMAC issue Reviewed-by: asaha --- .../implementations/IntegrityHmac.java | 76 +++++++---- .../internal/dom/DOMHMACSignatureMethod.java | 53 ++++---- .../xml/internal/security/TruncateHMAC.java | 118 ++++++++++++++++++ ...enveloping-hmac-sha1-trunclen-0-attack.xml | 16 +++ ...enveloping-hmac-sha1-trunclen-8-attack.xml | 17 +++ .../xml/crypto/dsig/GenerationTests.java | 16 ++- .../xml/crypto/dsig/ValidationTests.java | 39 +++++- ...enveloping-hmac-sha1-trunclen-0-attack.xml | 16 +++ ...enveloping-hmac-sha1-trunclen-8-attack.xml | 17 +++ 9 files changed, 311 insertions(+), 57 deletions(-) create mode 100644 jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java create mode 100644 jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-0-attack.xml create mode 100644 jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-8-attack.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-0-attack.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-8-attack.xml diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index d3495bb567f..85cc9e38a68 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -60,8 +60,14 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { */ public abstract String engineGetURI(); + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); + /** Field _macAlgorithm */ private Mac _macAlgorithm = null; + private boolean _HMACOutputLengthSet = false; /** Field _HMACOutputLength */ int _HMACOutputLength = 0; @@ -115,14 +121,16 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { throws XMLSignatureException { try { - byte[] completeResult = this._macAlgorithm.doFinal(); - - if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) { + if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "HMACOutputLength must not be less than " + getDigestLength()); + } + throw new XMLSignatureException("errorMessages.XMLSignatureException"); + } else { + byte[] completeResult = this._macAlgorithm.doFinal(); return MessageDigestAlgorithm.isEqual(completeResult, signature); } - byte[] stripped = IntegrityHmac.reduceBitLength(completeResult, - this._HMACOutputLength); - return MessageDigestAlgorithm.isEqual(stripped, signature); } catch (IllegalStateException ex) { throw new XMLSignatureException("empty", ex); } @@ -176,14 +184,15 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { protected byte[] engineSign() throws XMLSignatureException { try { - byte[] completeResult = this._macAlgorithm.doFinal(); - - if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) { - return completeResult; + if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "HMACOutputLength must not be less than " + getDigestLength()); + } + throw new XMLSignatureException("errorMessages.XMLSignatureException"); + } else { + return this._macAlgorithm.doFinal(); } - return IntegrityHmac.reduceBitLength(completeResult, - this._HMACOutputLength); - } catch (IllegalStateException ex) { throw new XMLSignatureException("empty", ex); } @@ -361,6 +370,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { */ protected void engineSetHMACOutputLength(int HMACOutputLength) { this._HMACOutputLength = HMACOutputLength; + this._HMACOutputLengthSet = true; } /** @@ -376,12 +386,13 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { throw new IllegalArgumentException("element null"); } - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); + Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), + Constants._TAG_HMACOUTPUTLENGTH,0); - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - } + if (hmaclength != null) { + this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this._HMACOutputLengthSet = true; + } } @@ -390,14 +401,13 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { * * @param element */ - public void engineAddContextToElement(Element element) - { + public void engineAddContextToElement(Element element) { if (element == null) { throw new IllegalArgumentException("null element"); } - if (this._HMACOutputLength != 0) { + if (this._HMACOutputLengthSet) { Document doc = element.getOwnerDocument(); Element HMElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); @@ -436,6 +446,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; } + + int getDigestLength() { + return 160; + } } /** @@ -463,6 +477,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; } + + int getDigestLength() { + return 256; + } } /** @@ -490,6 +508,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; } + + int getDigestLength() { + return 384; + } } /** @@ -517,6 +539,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; } + + int getDigestLength() { + return 512; + } } /** @@ -544,6 +570,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; } + + int getDigestLength() { + return 160; + } } /** @@ -571,5 +601,9 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; } + + int getDigestLength() { + return 128; + } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java index 5a9000c898c..482283b616e 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java @@ -19,7 +19,7 @@ * */ /* - * Copyright 2005-2008 Sun Microsystems, Inc. All rights reserved. + * Copyright 2005-2009 Sun Microsystems, Inc. All rights reserved. */ /* * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ @@ -58,6 +58,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Mac hmac; private int outputLength; + private boolean outputLengthSet; /** * Creates a DOMHMACSignatureMethod with the specified params @@ -87,6 +88,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { ("params must be of type HMACParameterSpec"); } outputLength = ((HMACParameterSpec) params).getOutputLength(); + outputLengthSet = true; if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Setting outputLength from HMACParameterSpec to: " @@ -101,6 +103,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throws MarshalException { outputLength = new Integer (paramsElem.getFirstChild().getNodeValue()).intValue(); + outputLengthSet = true; if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "unmarshalled outputLength: " + outputLength); } @@ -135,23 +138,13 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException(nsae); } } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "outputLength = " + outputLength); + if (outputLengthSet && outputLength < getDigestLength()) { + throw new XMLSignatureException + ("HMACOutputLength must not be less than " + getDigestLength()); } hmac.init((SecretKey) key); si.canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "resultLength = " + result.length); - } - if (outputLength != -1) { - int byteLength = outputLength/8; - if (result.length > byteLength) { - byte[] truncated = new byte[byteLength]; - System.arraycopy(result, 0, truncated, 0, byteLength); - result = truncated; - } - } return MessageDigest.isEqual(sig, result); } @@ -171,18 +164,13 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException(nsae); } } + if (outputLengthSet && outputLength < getDigestLength()) { + throw new XMLSignatureException + ("HMACOutputLength must not be less than " + getDigestLength()); + } hmac.init((SecretKey) key); si.canonicalize(context, new MacOutputStream(hmac)); - byte[] result = hmac.doFinal(); - if (outputLength != -1) { - int byteLength = outputLength/8; - if (result.length > byteLength) { - byte[] truncated = new byte[byteLength]; - System.arraycopy(result, 0, truncated, 0, byteLength); - result = truncated; - } - } - return result; + return hmac.doFinal(); } boolean paramsEqual(AlgorithmParameterSpec spec) { @@ -197,6 +185,11 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { return (outputLength == ospec.getOutputLength()); } + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); + static final class SHA1 extends DOMHMACSignatureMethod { SHA1(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException { @@ -211,6 +204,9 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { String getSignatureAlgorithm() { return "HmacSHA1"; } + int getDigestLength() { + return 160; + } } static final class SHA256 extends DOMHMACSignatureMethod { @@ -227,6 +223,9 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { String getSignatureAlgorithm() { return "HmacSHA256"; } + int getDigestLength() { + return 256; + } } static final class SHA384 extends DOMHMACSignatureMethod { @@ -243,6 +242,9 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { String getSignatureAlgorithm() { return "HmacSHA384"; } + int getDigestLength() { + return 384; + } } static final class SHA512 extends DOMHMACSignatureMethod { @@ -259,5 +261,8 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { String getSignatureAlgorithm() { return "HmacSHA512"; } + int getDigestLength() { + return 512; + } } } diff --git a/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java b/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java new file mode 100644 index 00000000000..ebb424de328 --- /dev/null +++ b/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java @@ -0,0 +1,118 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test %I% %E% + * @bug 6824440 + * @summary Check that Apache XMLSec APIs will not accept HMAC truncation + * lengths less than minimum bound + * @compile -XDignore.symbol.file TruncateHMAC.java + * @run main TruncateHMAC + */ + +import java.io.File; +import javax.crypto.SecretKey; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import com.sun.org.apache.xml.internal.security.Init; +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import com.sun.org.apache.xml.internal.security.signature.XMLSignature; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; +import com.sun.org.apache.xml.internal.security.utils.Constants; + + +public class TruncateHMAC { + + private final static String DIR = System.getProperty("test.src", "."); + private static DocumentBuilderFactory dbf = null; + private static boolean atLeastOneFailed = false; + + public static void main(String[] args) throws Exception { + + Init.init(); + dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(false); + validate("signature-enveloping-hmac-sha1-trunclen-0-attack.xml"); + validate("signature-enveloping-hmac-sha1-trunclen-8-attack.xml"); + generate_hmac_sha1_40(); + + if (atLeastOneFailed) { + throw new Exception + ("At least one signature did not validate as expected"); + } + } + + private static void validate(String data) throws Exception { + System.out.println("Validating " + data); + File file = new File(DIR, data); + + Document doc = dbf.newDocumentBuilder().parse(file); + NodeList nl = + doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature"); + if (nl.getLength() == 0) { + throw new Exception("Couldn't find signature Element"); + } + Element sigElement = (Element) nl.item(0); + XMLSignature signature = new XMLSignature + (sigElement, file.toURI().toString()); + SecretKey sk = signature.createSecretKey("secret".getBytes("ASCII")); + try { + System.out.println + ("Validation status: " + signature.checkSignatureValue(sk)); + System.out.println("FAILED"); + atLeastOneFailed = true; + } catch (XMLSignatureException xse) { + System.out.println(xse.getMessage()); + System.out.println("PASSED"); + } + } + + private static void generate_hmac_sha1_40() throws Exception { + System.out.println("Generating "); + + Document doc = dbf.newDocumentBuilder().newDocument(); + XMLSignature sig = new XMLSignature + (doc, null, XMLSignature.ALGO_ID_MAC_HMAC_SHA1, 40, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); + try { + sig.sign(getSecretKey("secret".getBytes("ASCII"))); + System.out.println("FAILED"); + atLeastOneFailed = true; + } catch (XMLSignatureException xse) { + System.out.println(xse.getMessage()); + System.out.println("PASSED"); + } + } + + private static SecretKey getSecretKey(final byte[] secret) { + return new SecretKey() { + public String getFormat() { return "RAW"; } + public byte[] getEncoded() { return secret; } + public String getAlgorithm(){ return "SECRET"; } + }; + } +} diff --git a/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-0-attack.xml b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-0-attack.xml new file mode 100644 index 00000000000..5008dae5193 --- /dev/null +++ b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-0-attack.xml @@ -0,0 +1,16 @@ + + + + + + 0 + + + + nz4GS0NbH2SrWlD/4fX313CoTzc= + + + + + some other text + diff --git a/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-8-attack.xml b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-8-attack.xml new file mode 100644 index 00000000000..dfe0a0df9a5 --- /dev/null +++ b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1-trunclen-8-attack.xml @@ -0,0 +1,17 @@ + + + + + + 8 + + + + nz4GS0NbH2SrWlD/4fX313CoTzc= + + + + Qw== + + some other text + diff --git a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java index ea4fd610e1e..13881966d32 100644 --- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java +++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2009 Sun Microsystems, Inc. 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,9 +23,7 @@ /** * @test - * @bug 4635230 - * @bug 6283345 - * @bug 6303830 + * @bug 4635230 6283345 6303830 6824440 * @summary Basic unit tests for generating XML Signatures with JSR 105 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * X509KeySelector.java GenerationTests.java @@ -248,8 +246,14 @@ public class GenerationTests { System.out.println("* Generating signature-enveloping-hmac-sha1-40.xml"); SignatureMethod hmacSha1 = fac.newSignatureMethod (SignatureMethod.HMAC_SHA1, new HMACParameterSpec(40)); - test_create_signature_enveloping(sha1, hmacSha1, null, - getSecretKey("secret".getBytes("ASCII")), sks, false); + try { + test_create_signature_enveloping(sha1, hmacSha1, null, + getSecretKey("secret".getBytes("ASCII")), sks, false); + } catch (Exception e) { + if (!(e instanceof XMLSignatureException)) { + throw e; + } + } System.out.println(); } diff --git a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java index 0934de7e921..0604af9bbc5 100644 --- a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java +++ b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2009 Sun Microsystems, Inc. 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,9 +23,7 @@ /** * @test - * @bug 4635230 - * @bug 6365103 - * @bug 6366054 + * @bug 4635230 6365103 6366054 6824440 * @summary Basic unit tests for validating XML Signatures with JSR 105 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * X509KeySelector.java ValidationTests.java @@ -42,6 +40,7 @@ import javax.xml.crypto.URIDereferencer; import javax.xml.crypto.URIReference; import javax.xml.crypto.URIReferenceException; import javax.xml.crypto.XMLCryptoContext; +import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.XMLSignatureFactory; /** @@ -68,7 +67,6 @@ public class ValidationTests { "signature-enveloping-dsa.xml", "signature-enveloping-rsa.xml", "signature-enveloping-hmac-sha1.xml", - "signature-enveloping-hmac-sha1-40.xml", "signature-external-dsa.xml", "signature-external-b64-dsa.xml", "signature-retrievalmethod-rawx509crt.xml", @@ -106,7 +104,6 @@ public class ValidationTests { KVKS, KVKS, SKKS, - SKKS, KVKS, KVKS, CKS, @@ -146,6 +143,36 @@ public class ValidationTests { atLeastOneFailed = true; } + System.out.println("Validating signature-enveloping-hmac-sha1-40.xml"); + try { + test_signature("signature-enveloping-hmac-sha1-40.xml", SKKS, false); + System.out.println("FAILED"); + atLeastOneFailed = true; + } catch (XMLSignatureException xse) { + System.out.println(xse.getMessage()); + System.out.println("PASSED"); + } + + System.out.println("Validating signature-enveloping-hmac-sha1-trunclen-0-attack.xml"); + try { + test_signature("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", SKKS, false); + System.out.println("FAILED"); + atLeastOneFailed = true; + } catch (XMLSignatureException xse) { + System.out.println(xse.getMessage()); + System.out.println("PASSED"); + } + + System.out.println("Validating signature-enveloping-hmac-sha1-trunclen-8-attack.xml"); + try { + test_signature("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", SKKS, false); + System.out.println("FAILED"); + atLeastOneFailed = true; + } catch (XMLSignatureException xse) { + System.out.println(xse.getMessage()); + System.out.println("PASSED"); + } + if (atLeastOneFailed) { throw new Exception ("At least one signature did not validate as expected"); diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-0-attack.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-0-attack.xml new file mode 100644 index 00000000000..5008dae5193 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-0-attack.xml @@ -0,0 +1,16 @@ + + + + + + 0 + + + + nz4GS0NbH2SrWlD/4fX313CoTzc= + + + + + some other text + diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-8-attack.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-8-attack.xml new file mode 100644 index 00000000000..dfe0a0df9a5 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-hmac-sha1-trunclen-8-attack.xml @@ -0,0 +1,17 @@ + + + + + + 8 + + + + nz4GS0NbH2SrWlD/4fX313CoTzc= + + + + Qw== + + some other text + From d92c74443f73ee3c282a052d9e5027a5123621d1 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Mon, 22 Jun 2009 07:23:20 -0700 Subject: [PATCH 019/215] 6830335: Java JAR Pack200 Decompression Integer Overflow Vulnerability Fixes a potential vulnerability in the unpack200 logic, by adding extra checks, a back-port. Reviewed-by: asaha --- .../share/native/com/sun/java/util/jar/pack/unpack.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp index a6f4ca0c2c8..7ca65c5d61e 100644 --- a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp +++ b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp @@ -908,10 +908,12 @@ void cpool::init(unpacker* u_, int counts[NUM_COUNTS]) { // place a limit on future CP growth: int generous = 0; - generous += u->ic_count*3; // implicit name, outer, outer.utf8 - generous += 40; // WKUs, misc - generous += u->class_count; // implicit SourceFile strings - maxentries = nentries + generous; + generous = add_size(generous, u->ic_count); // implicit name + generous = add_size(generous, u->ic_count); // outer + generous = add_size(generous, u->ic_count); // outer.utf8 + generous = add_size(generous, 40); // WKUs, misc + generous = add_size(generous, u->class_count); // implicit SourceFile strings + maxentries = add_size(nentries, generous); // Note that this CP does not include "empty" entries // for longs and doubles. Those are introduced when From 95f53ce57bb36019087a774f46bfeadc843d4d68 Mon Sep 17 00:00:00 2001 From: Abhijit Saha Date: Mon, 22 Jun 2009 13:56:30 -0700 Subject: [PATCH 020/215] 6845701: Xerces2 Java XML library infinite loop with malformed XML input Reviewed-by: hawtin --- .../com/sun/org/apache/xerces/internal/impl/XMLScanner.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/jaxp/src/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/jaxp/src/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java index e7071fde4f1..513dec48f04 100644 --- a/jaxp/src/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java +++ b/jaxp/src/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java @@ -1027,6 +1027,9 @@ public abstract class XMLScanner int c = fEntityScanner.peekChar(); if (XMLChar.isMarkup(c) || c == ']') { fStringBuffer.append((char)fEntityScanner.scanChar()); + } else if (c != -1 && isInvalidLiteral(c)) { + reportFatalError("InvalidCharInSystemID", + new Object[] {Integer.toString(c, 16)}); } } while (fEntityScanner.scanLiteral(quote, ident) != quote); fStringBuffer.append(ident); From 7db63ef95fd14841554e4238ec151a73a2bb040d Mon Sep 17 00:00:00 2001 From: Naoto Sato Date: Tue, 30 Jun 2009 17:12:32 -0700 Subject: [PATCH 021/215] 6852429: IME should call ImmIsUIMessage() or DefWindowProc() when it receives WM_IME_SETCONTEX Reviewed-by: peytoia --- jdk/src/windows/native/sun/windows/awt_Component.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/jdk/src/windows/native/sun/windows/awt_Component.cpp b/jdk/src/windows/native/sun/windows/awt_Component.cpp index 3c20533de90..ba0fc9cdc99 100644 --- a/jdk/src/windows/native/sun/windows/awt_Component.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp @@ -3739,11 +3739,12 @@ void AwtComponent::SetCandidateWindow(int iCandType, int x, int y) MsgRouting AwtComponent::WmImeSetContext(BOOL fSet, LPARAM *lplParam) { - // This message causes native status window shown even it is disabled. So don't - // let DefWindowProc process this message if this IMC is disabled. + // If the Windows input context is disabled, do not let Windows + // display any UIs. HIMC hIMC = ImmGetContext(); if (hIMC == NULL) { - return mrConsume; + *lplParam = 0; + return mrDoDefault; } if (fSet) { From e4502f3b6fa5fc7bb678e0f02736bd2407883bca Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Wed, 8 Jul 2009 16:57:40 -0400 Subject: [PATCH 022/215] 6858484: If an invalid HMAC XML Signature is validated, all subsequent valid HMAC signatures are invalid Reviewed-by: asaha --- .../implementations/IntegrityHmac.java | 4 +++- .../xml/internal/security/TruncateHMAC.java | 24 +++++++++++++------ .../signature-enveloping-hmac-sha1.xml | 15 ++++++++++++ 3 files changed, 35 insertions(+), 8 deletions(-) create mode 100644 jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1.xml diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 85cc9e38a68..7231b069a18 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -106,7 +106,9 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { } public void reset() { - _HMACOutputLength=0; + _HMACOutputLength=0; + _HMACOutputLengthSet = false; + _macAlgorithm.reset(); } /** diff --git a/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java b/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java index ebb424de328..a77d02b84f9 100644 --- a/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java +++ b/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java @@ -23,7 +23,7 @@ /** * @test %I% %E% - * @bug 6824440 + * @bug 6824440 6858484 * @summary Check that Apache XMLSec APIs will not accept HMAC truncation * lengths less than minimum bound * @compile -XDignore.symbol.file TruncateHMAC.java @@ -56,8 +56,10 @@ public class TruncateHMAC { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); - validate("signature-enveloping-hmac-sha1-trunclen-0-attack.xml"); - validate("signature-enveloping-hmac-sha1-trunclen-8-attack.xml"); + validate("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", false); + validate("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", false); + // this one should pass + validate("signature-enveloping-hmac-sha1.xml", true); generate_hmac_sha1_40(); if (atLeastOneFailed) { @@ -66,7 +68,7 @@ public class TruncateHMAC { } } - private static void validate(String data) throws Exception { + private static void validate(String data, boolean pass) throws Exception { System.out.println("Validating " + data); File file = new File(DIR, data); @@ -83,11 +85,19 @@ public class TruncateHMAC { try { System.out.println ("Validation status: " + signature.checkSignatureValue(sk)); - System.out.println("FAILED"); - atLeastOneFailed = true; + if (!pass) { + System.out.println("FAILED"); + atLeastOneFailed = true; + } else { + System.out.println("PASSED"); + } } catch (XMLSignatureException xse) { System.out.println(xse.getMessage()); - System.out.println("PASSED"); + if (!pass) { + System.out.println("PASSED"); + } else { + System.out.println("FAILED"); + } } } diff --git a/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1.xml b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1.xml new file mode 100644 index 00000000000..c0c8343a895 --- /dev/null +++ b/jdk/test/com/sun/org/apache/xml/internal/security/signature-enveloping-hmac-sha1.xml @@ -0,0 +1,15 @@ + + + + + + + + 7/XTsHaBSOnJ/jXD5v0zL6VKYsk= + + + + JElPttIT4Am7Q+MNoMyv+WDfAZw= + + some text + From dd76763423f427a552407f4a106fa4388bcaf130 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 15 Jul 2009 10:25:01 +0100 Subject: [PATCH 023/215] 6846972: cannot access member of raw type when erasure change overriding into overloading Fix of 6400189 caused a nasty problem in method resolution Reviewed-by: jjg --- .../com/sun/tools/javac/comp/Resolve.java | 3 +- .../javac/generics/rawOverride/T6846972.java | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 langtools/test/tools/javac/generics/rawOverride/T6846972.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java index bb62298119c..808fd9959ef 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java @@ -251,7 +251,8 @@ public class Resolve { return true; else { Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true); - return (s2 == null || s2 == sym); + return (s2 == null || s2 == sym || + !types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym))); } } //where diff --git a/langtools/test/tools/javac/generics/rawOverride/T6846972.java b/langtools/test/tools/javac/generics/rawOverride/T6846972.java new file mode 100644 index 00000000000..af39a2d7cd6 --- /dev/null +++ b/langtools/test/tools/javac/generics/rawOverride/T6846972.java @@ -0,0 +1,49 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6846972 + * @summary cannot access member of raw type when erasure change overriding into overloading + * @author mcimadamore + * @compile T6846972.java + */ + +import java.util.EnumMap; + +public class T6846972 { + + enum Suit { + CLUBS, DIAMONDS; + } + + static Object [] array = { + Suit.CLUBS, "value1", + Suit.DIAMONDS, "value2" + }; + + static void test() { + EnumMap map = new EnumMap(Suit.class); + map.put(array[0], array[1]); + } +} From c854c85621aa9bfa03f290835a7369d4108b3305 Mon Sep 17 00:00:00 2001 From: Sergey Groznyh Date: Wed, 15 Jul 2009 19:05:18 +0400 Subject: [PATCH 024/215] 6612541: api/javax_swing/text/LabelView/index.html#getXXX[LabelView0004] fails since JDK 7 b20 Reviewed-by: peterz --- jdk/src/share/classes/javax/swing/text/GlyphView.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/GlyphView.java b/jdk/src/share/classes/javax/swing/text/GlyphView.java index 364fd69e8ee..087e9201545 100644 --- a/jdk/src/share/classes/javax/swing/text/GlyphView.java +++ b/jdk/src/share/classes/javax/swing/text/GlyphView.java @@ -719,8 +719,9 @@ public class GlyphView extends View implements TabableView, Cloneable { checkPainter(); int p0 = getStartOffset(); int p1 = painter.getBoundedPosition(this, p0, pos, len); - return ((p1 > p0) && (getBreakSpot(p0, p1) != BreakIterator.DONE)) ? - View.ExcellentBreakWeight : View.BadBreakWeight; + return p1 == p0 ? View.BadBreakWeight : + getBreakSpot(p0, p1) != BreakIterator.DONE ? + View.ExcellentBreakWeight : View.GoodBreakWeight; } return super.getBreakWeight(axis, pos, len); } From ae2586d2c3656378e28e8e372836fd270f439bf3 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 15 Jul 2009 17:01:47 +0100 Subject: [PATCH 025/215] 6860795: NullPointerException when compiling a negative java source Rich formatter shouldn't propagate visits on method symbols that have a null type Reviewed-by: jjg --- .../javac/util/RichDiagnosticFormatter.java | 3 +- .../javac/Diagnostics/6860795/T6860795.java | 34 +++++++++++++++++++ .../javac/Diagnostics/6860795/T6860795.out | 2 ++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 langtools/test/tools/javac/Diagnostics/6860795/T6860795.java create mode 100644 langtools/test/tools/javac/Diagnostics/6860795/T6860795.out diff --git a/langtools/src/share/classes/com/sun/tools/javac/util/RichDiagnosticFormatter.java b/langtools/src/share/classes/com/sun/tools/javac/util/RichDiagnosticFormatter.java index 6d8538bf654..60e323f7bda 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/util/RichDiagnosticFormatter.java +++ b/langtools/src/share/classes/com/sun/tools/javac/util/RichDiagnosticFormatter.java @@ -569,7 +569,8 @@ public class RichDiagnosticFormatter extends @Override public Void visitMethodSymbol(MethodSymbol s, Void ignored) { visit(s.owner, null); - typePreprocessor.visit(s.type); + if (s.type != null) + typePreprocessor.visit(s.type); return null; } }; diff --git a/langtools/test/tools/javac/Diagnostics/6860795/T6860795.java b/langtools/test/tools/javac/Diagnostics/6860795/T6860795.java new file mode 100644 index 00000000000..6480e0ff2b7 --- /dev/null +++ b/langtools/test/tools/javac/Diagnostics/6860795/T6860795.java @@ -0,0 +1,34 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 6860795 + * @summary NullPointerException when compiling a negative java source + * @author mcimadamore + * @compile/fail/ref=T6860795.out -XDrawDiagnostics T6860795.java + */ + +class Test { + void foo(float x, int x) {} +} diff --git a/langtools/test/tools/javac/Diagnostics/6860795/T6860795.out b/langtools/test/tools/javac/Diagnostics/6860795/T6860795.out new file mode 100644 index 00000000000..f7ec1120afd --- /dev/null +++ b/langtools/test/tools/javac/Diagnostics/6860795/T6860795.out @@ -0,0 +1,2 @@ +T6860795.java:33:27: compiler.err.already.defined: x, foo +1 error From 8c000e858b40b9b2b4b1b6297b22a5f3a6ee7b17 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 15 Jul 2009 12:08:55 -0700 Subject: [PATCH 026/215] 6857789: (reflect) Create common superclass of reflective exceptions Reviewed-by: martin --- .../java/lang/ClassNotFoundException.java | 2 +- .../java/lang/IllegalAccessException.java | 2 +- .../java/lang/InstantiationException.java | 2 +- .../java/lang/NoSuchFieldException.java | 2 +- .../java/lang/NoSuchMethodException.java | 2 +- .../lang/ReflectiveOperationException.java | 91 +++++++++++++++++++ .../reflect/InvocationTargetException.java | 2 +- 7 files changed, 97 insertions(+), 6 deletions(-) create mode 100644 jdk/src/share/classes/java/lang/ReflectiveOperationException.java diff --git a/jdk/src/share/classes/java/lang/ClassNotFoundException.java b/jdk/src/share/classes/java/lang/ClassNotFoundException.java index 8da84456726..af3af4246a5 100644 --- a/jdk/src/share/classes/java/lang/ClassNotFoundException.java +++ b/jdk/src/share/classes/java/lang/ClassNotFoundException.java @@ -50,7 +50,7 @@ package java.lang; * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) * @since JDK1.0 */ -public class ClassNotFoundException extends Exception { +public class ClassNotFoundException extends ReflectiveOperationException { /** * use serialVersionUID from JDK 1.1.X for interoperability */ diff --git a/jdk/src/share/classes/java/lang/IllegalAccessException.java b/jdk/src/share/classes/java/lang/IllegalAccessException.java index 19b51b90fef..2dc609978fc 100644 --- a/jdk/src/share/classes/java/lang/IllegalAccessException.java +++ b/jdk/src/share/classes/java/lang/IllegalAccessException.java @@ -56,7 +56,7 @@ package java.lang; * @see java.lang.reflect.Constructor#newInstance(Object[]) * @since JDK1.0 */ -public class IllegalAccessException extends Exception { +public class IllegalAccessException extends ReflectiveOperationException { private static final long serialVersionUID = 6616958222490762034L; /** diff --git a/jdk/src/share/classes/java/lang/InstantiationException.java b/jdk/src/share/classes/java/lang/InstantiationException.java index ace382ae437..fac48397cc8 100644 --- a/jdk/src/share/classes/java/lang/InstantiationException.java +++ b/jdk/src/share/classes/java/lang/InstantiationException.java @@ -43,7 +43,7 @@ package java.lang; * @since JDK1.0 */ public -class InstantiationException extends Exception { +class InstantiationException extends ReflectiveOperationException { private static final long serialVersionUID = -8441929162975509110L; /** diff --git a/jdk/src/share/classes/java/lang/NoSuchFieldException.java b/jdk/src/share/classes/java/lang/NoSuchFieldException.java index b44fb173ebb..ce3adf2d289 100644 --- a/jdk/src/share/classes/java/lang/NoSuchFieldException.java +++ b/jdk/src/share/classes/java/lang/NoSuchFieldException.java @@ -31,7 +31,7 @@ package java.lang; * @author unascribed * @since JDK1.1 */ -public class NoSuchFieldException extends Exception { +public class NoSuchFieldException extends ReflectiveOperationException { private static final long serialVersionUID = -6143714805279938260L; /** diff --git a/jdk/src/share/classes/java/lang/NoSuchMethodException.java b/jdk/src/share/classes/java/lang/NoSuchMethodException.java index 720fbfcbbc6..dc8954b6cd0 100644 --- a/jdk/src/share/classes/java/lang/NoSuchMethodException.java +++ b/jdk/src/share/classes/java/lang/NoSuchMethodException.java @@ -32,7 +32,7 @@ package java.lang; * @since JDK1.0 */ public -class NoSuchMethodException extends Exception { +class NoSuchMethodException extends ReflectiveOperationException { private static final long serialVersionUID = 5034388446362600923L; /** diff --git a/jdk/src/share/classes/java/lang/ReflectiveOperationException.java b/jdk/src/share/classes/java/lang/ReflectiveOperationException.java new file mode 100644 index 00000000000..d06613c6d2b --- /dev/null +++ b/jdk/src/share/classes/java/lang/ReflectiveOperationException.java @@ -0,0 +1,91 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package java.lang; + +/** + * Common superclass of exceptions thrown by reflective operations in + * core reflection. + * + * @see LinkageError + * @since 1.7 + */ +public class ReflectiveOperationException extends Exception { + static final long serialVersionUID = 123456789L; + + /** + * Constructs a new exception with {@code null} as its detail + * message. The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + */ + public ReflectiveOperationException() { + super(); + } + + /** + * Constructs a new exception with the specified detail message. + * The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public ReflectiveOperationException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified detail message + * and cause. + * + *

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public ReflectiveOperationException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of {@code (cause==null ? null : cause.toString())} (which + * typically contains the class and detail message of {@code cause}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public ReflectiveOperationException(Throwable cause) { + super(cause); + } +} diff --git a/jdk/src/share/classes/java/lang/reflect/InvocationTargetException.java b/jdk/src/share/classes/java/lang/reflect/InvocationTargetException.java index 28f3b206297..048d04cacbf 100644 --- a/jdk/src/share/classes/java/lang/reflect/InvocationTargetException.java +++ b/jdk/src/share/classes/java/lang/reflect/InvocationTargetException.java @@ -39,7 +39,7 @@ package java.lang.reflect; * @see Method * @see Constructor */ -public class InvocationTargetException extends Exception { +public class InvocationTargetException extends ReflectiveOperationException { /** * Use serialVersionUID from JDK 1.1.X for interoperability */ From b8fae2d33cfffdf41f134b530fd3790da65ed2a5 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 15 Jul 2009 14:43:13 -0700 Subject: [PATCH 027/215] 6463998: Undocumented NullPointerExeption from Float.parseFloat and Double.parseDouble Reviewed-by: lancea, iris --- jdk/src/share/classes/java/lang/Double.java | 1 + jdk/src/share/classes/java/lang/Float.java | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/classes/java/lang/Double.java b/jdk/src/share/classes/java/lang/Double.java index 9866d5d4aee..8efb241b808 100644 --- a/jdk/src/share/classes/java/lang/Double.java +++ b/jdk/src/share/classes/java/lang/Double.java @@ -529,6 +529,7 @@ public final class Double extends Number implements Comparable { * @param s the string to be parsed. * @return the {@code double} value represented by the string * argument. + * @throws NullPointerException if the string is null * @throws NumberFormatException if the string does not contain * a parsable {@code double}. * @see java.lang.Double#valueOf(String) diff --git a/jdk/src/share/classes/java/lang/Float.java b/jdk/src/share/classes/java/lang/Float.java index 1c89a458fa7..eb133016f6b 100644 --- a/jdk/src/share/classes/java/lang/Float.java +++ b/jdk/src/share/classes/java/lang/Float.java @@ -438,12 +438,13 @@ public final class Float extends Number implements Comparable { * represented by the specified {@code String}, as performed * by the {@code valueOf} method of class {@code Float}. * - * @param s the string to be parsed. + * @param s the string to be parsed. * @return the {@code float} value represented by the string * argument. - * @throws NumberFormatException if the string does not contain a + * @throws NullPointerException if the string is null + * @throws NumberFormatException if the string does not contain a * parsable {@code float}. - * @see java.lang.Float#valueOf(String) + * @see java.lang.Float#valueOf(String) * @since 1.2 */ public static float parseFloat(String s) throws NumberFormatException { From da30267d99edd4ab695bce12fd92e67f1241965a Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Thu, 16 Jul 2009 20:12:14 +0400 Subject: [PATCH 028/215] 6505027: terminateEditOnFocusLost making problems for table in JDesktopPane Reviewed-by: alexp --- .../classes/javax/swing/JInternalFrame.java | 31 ++-- .../swing/JInternalFrame/Test6505027.java | 136 ++++++++++++++++++ 2 files changed, 151 insertions(+), 16 deletions(-) create mode 100644 jdk/test/javax/swing/JInternalFrame/Test6505027.java diff --git a/jdk/src/share/classes/javax/swing/JInternalFrame.java b/jdk/src/share/classes/javax/swing/JInternalFrame.java index 837ffe49e4f..3079a26ebdc 100644 --- a/jdk/src/share/classes/javax/swing/JInternalFrame.java +++ b/jdk/src/share/classes/javax/swing/JInternalFrame.java @@ -26,13 +26,10 @@ package javax.swing; import java.awt.*; -import java.awt.event.*; import java.beans.PropertyVetoException; import java.beans.PropertyChangeEvent; -import java.util.EventListener; -import javax.swing.border.Border; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import javax.swing.plaf.*; @@ -40,7 +37,6 @@ import javax.swing.plaf.*; import javax.accessibility.*; import java.io.ObjectOutputStream; -import java.io.ObjectInputStream; import java.io.IOException; import java.lang.StringBuilder; import java.beans.PropertyChangeListener; @@ -1459,19 +1455,22 @@ public class JInternalFrame extends JComponent implements SwingUtilities2.compositeRequestFocus(getDesktopIcon()); } else { - // FocusPropertyChangeListener will eventually update - // lastFocusOwner. As focus requests are asynchronous - // lastFocusOwner may be accessed before it has been correctly - // updated. To avoid any problems, lastFocusOwner is immediately - // set, assuming the request will succeed. - lastFocusOwner = getMostRecentFocusOwner(); - if (lastFocusOwner == null) { - // Make sure focus is restored somewhere, so that - // we don't leave a focused component in another frame while - // this frame is selected. - lastFocusOwner = getContentPane(); + Component component = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); + if ((component == null) || !SwingUtilities.isDescendingFrom(component, this)) { + // FocusPropertyChangeListener will eventually update + // lastFocusOwner. As focus requests are asynchronous + // lastFocusOwner may be accessed before it has been correctly + // updated. To avoid any problems, lastFocusOwner is immediately + // set, assuming the request will succeed. + setLastFocusOwner(getMostRecentFocusOwner()); + if (lastFocusOwner == null) { + // Make sure focus is restored somewhere, so that + // we don't leave a focused component in another frame while + // this frame is selected. + setLastFocusOwner(getContentPane()); + } + lastFocusOwner.requestFocus(); } - lastFocusOwner.requestFocus(); } } diff --git a/jdk/test/javax/swing/JInternalFrame/Test6505027.java b/jdk/test/javax/swing/JInternalFrame/Test6505027.java new file mode 100644 index 00000000000..218769003cb --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/Test6505027.java @@ -0,0 +1,136 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6505027 + * @summary Tests focus problem inside internal frame + * @author Sergey Malenkov + */ + +import java.awt.AWTException; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.KeyboardFocusManager; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import javax.swing.DefaultCellEditor; +import javax.swing.JComboBox; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumn; + +public class Test6505027 implements Runnable { + + private static final boolean INTERNAL = true; + private static final boolean TERMINATE = true; + + private static final int WIDTH = 450; + private static final int HEIGHT = 200; + private static final int OFFSET = 10; + private static final long PAUSE = 2048L; + + private static final String[] COLUMNS = { "Size", "Shape" }; // NON-NLS + private static final String[] ITEMS = { "a", "b", "c", "d" }; // NON-NLS + private static final String KEY = "terminateEditOnFocusLost"; // NON-NLS + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Test6505027()); + + Component component = null; + while (component == null) { + try { + Thread.sleep(PAUSE); + } + catch (InterruptedException exception) { + // ignore interrupted exception + } + component = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); + } + if (!component.getClass().equals(JComboBox.class)) { + throw new Error("unexpected focus owner: " + component); + } + SwingUtilities.getWindowAncestor(component).dispose(); + } + + private JTable table; + private Point point; + + public void run() { + if (this.table == null) { + JFrame main = new JFrame(); + main.setSize(WIDTH + OFFSET * 3, HEIGHT + OFFSET * 5); + main.setLocationRelativeTo(null); + main.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + main.setVisible(true); + + Container container = main; + if (INTERNAL) { + JInternalFrame frame = new JInternalFrame(); + frame.setBounds(OFFSET, OFFSET, WIDTH, HEIGHT); + frame.setVisible(true); + + JDesktopPane desktop = new JDesktopPane(); + desktop.add(frame, new Integer(1)); + + container.add(desktop); + container = frame; + } + this.table = new JTable(new DefaultTableModel(COLUMNS, 2)); + if (TERMINATE) { + this.table.putClientProperty(KEY, Boolean.TRUE); + } + TableColumn column = this.table.getColumn(COLUMNS[1]); + column.setCellEditor(new DefaultCellEditor(new JComboBox(ITEMS))); + + container.add(BorderLayout.NORTH, new JTextField()); + container.add(BorderLayout.CENTER, new JScrollPane(this.table)); + + SwingUtilities.invokeLater(this); + } + else if (this.point == null) { + this.point = this.table.getCellRect(1, 1, false).getLocation(); + SwingUtilities.convertPointToScreen(this.point, this.table); + SwingUtilities.invokeLater(this); + } + else { + try { + Robot robot = new Robot(); + robot.mouseMove(this.point.x + 1, this.point.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + } + catch (AWTException exception) { + throw new Error("unexpected exception", exception); + } + } + } +} From 44904765cac436e041e31a1bb32b2e63a2641603 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Fri, 17 Jul 2009 15:25:51 +0400 Subject: [PATCH 029/215] 6387360: Usage of package-private class as a parameter of a method (javax.swing.text.ParagraphView) Reviewed-by: malenkov --- .../classes/javax/swing/text/ParagraphView.java | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/text/ParagraphView.java b/jdk/src/share/classes/javax/swing/text/ParagraphView.java index c7f6bb09c3e..2b5f7826a08 100644 --- a/jdk/src/share/classes/javax/swing/text/ParagraphView.java +++ b/jdk/src/share/classes/javax/swing/text/ParagraphView.java @@ -174,23 +174,6 @@ public class ParagraphView extends FlowView implements TabExpander { return layoutPool.getView(index); } - /** - * Adjusts the given row if possible to fit within the - * layout span. By default this will try to find the - * highest break weight possible nearest the end of - * the row. If a forced break is encountered, the - * break will be positioned there. - *

- * This is meant for internal usage, and should not be used directly. - * - * @param r the row to adjust to the current layout - * span - * @param desiredSpan the current layout span >= 0 - * @param x the location r starts at - */ - protected void adjustRow(Row r, int desiredSpan, int x) { - } - /** * Returns the next visual position for the cursor, in * either the east or west direction. From e5047864cd1b701e2afdcfe2f87907dc7eedd650 Mon Sep 17 00:00:00 2001 From: Artem Ananiev Date: Fri, 17 Jul 2009 15:40:19 +0400 Subject: [PATCH 030/215] 6844297: java/awt/EventQueue/6638195/bug6638195.java test failed in jdk7 on Windows just on b59,passed on b57 Reviewed-by: bchristi, dcherepanov --- .../awt/EventQueue/6638195/bug6638195.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/jdk/test/java/awt/EventQueue/6638195/bug6638195.java b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java index 9dc3b50b973..c4612391547 100644 --- a/jdk/test/java/awt/EventQueue/6638195/bug6638195.java +++ b/jdk/test/java/awt/EventQueue/6638195/bug6638195.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2008-2009 Sun Microsystems, Inc. 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 6638195 + * @bug 6638195 6844297 * @author Igor Kushnirskiy * @summary tests if EventQueueDelegate.Delegate is invoked. */ @@ -47,11 +47,22 @@ public class bug6638195 { } private static void runTest(MyEventQueueDelegate delegate) throws Exception { + // We need an empty runnable here, so the next event is + // processed with a new EventQueueDelegate. See 6844297 + // for details EventQueue.invokeLater( new Runnable() { public void run() { } }); + // The following event is expected to be processed by + // the EventQueueDelegate instance + EventQueue.invokeLater( + new Runnable() { + public void run() { + } + }); + // Finally, proceed on the main thread final CountDownLatch latch = new CountDownLatch(1); EventQueue.invokeLater( new Runnable() { @@ -60,7 +71,7 @@ public class bug6638195 { } }); latch.await(); - if (! delegate.allInvoked()) { + if (!delegate.allInvoked()) { throw new RuntimeException("failed"); } } @@ -125,6 +136,7 @@ public class bug6638195 { return objectMap; } + static class MyEventQueueDelegate implements EventQueueDelegate.Delegate { private volatile boolean getNextEventInvoked = false; private volatile boolean beforeDispatchInvoked = false; From 97bb9bff6fec0de4d29248cdea3d535c57666157 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Fri, 17 Jul 2009 20:29:41 +0100 Subject: [PATCH 031/215] 6657619: DnsContext.debug is public static mutable (findbugs) Reviewed-by: alanb --- .../classes/com/sun/jndi/dns/DnsContext.java | 4 +- jdk/test/com/sun/jndi/dns/CheckAccess.java | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 jdk/test/com/sun/jndi/dns/CheckAccess.java diff --git a/jdk/src/share/classes/com/sun/jndi/dns/DnsContext.java b/jdk/src/share/classes/com/sun/jndi/dns/DnsContext.java index a5c8f01f3c1..3b30bb96a6e 100644 --- a/jdk/src/share/classes/com/sun/jndi/dns/DnsContext.java +++ b/jdk/src/share/classes/com/sun/jndi/dns/DnsContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -922,7 +922,7 @@ public class DnsContext extends ComponentDirContext { //---------- Debugging - public static boolean debug = false; + private static final boolean debug = false; private static final void dprint(String msg) { if (debug) { diff --git a/jdk/test/com/sun/jndi/dns/CheckAccess.java b/jdk/test/com/sun/jndi/dns/CheckAccess.java new file mode 100644 index 00000000000..478575167a5 --- /dev/null +++ b/jdk/test/com/sun/jndi/dns/CheckAccess.java @@ -0,0 +1,49 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6657619 + * @summary DnsContext.debug is public static mutable (findbugs) + * @author Vincent Ryan + */ + +import java.lang.reflect.*; + +/* + * Check that the 'debug' class member is no longer publicly accessible. + */ +public class CheckAccess { + public static final void main(String[] args) throws Exception { + try { + Class clazz = Class.forName("com.sun.jndi.dns.DnsContext"); + Field field = clazz.getField("debug"); + if (Modifier.isPublic(field.getModifiers())) { + throw new Exception( + "class member 'debug' must not be publicly accessible"); + } + } catch (NoSuchFieldException e) { + // 'debug' is not publicly accessible, ignore exception + } + } +} From d12079f670e26bd0c26e80ace4f63b3308622396 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Fri, 17 Jul 2009 20:43:53 +0100 Subject: [PATCH 032/215] 6657695: AbstractSaslImpl.logger is a static mutable (findbugs) Reviewed-by: alanb --- .../security/sasl/util/AbstractSaslImpl.java | 21 +++------ .../sun/security/sasl/util/CheckAccess.java | 46 +++++++++++++++++++ 2 files changed, 52 insertions(+), 15 deletions(-) create mode 100644 jdk/test/com/sun/security/sasl/util/CheckAccess.java diff --git a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java index 9c24b55ecf6..ac6fa258632 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java +++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -48,10 +48,6 @@ import sun.misc.HexDumpEncoder; * @author Rosanna Lee */ public abstract class AbstractSaslImpl { - /** - * Logger for debug messages - */ - protected static Logger logger; // set in initLogger(); lazily loads logger protected boolean completed = false; protected boolean privacy = false; @@ -68,7 +64,6 @@ public abstract class AbstractSaslImpl { protected String myClassName; protected AbstractSaslImpl(Map props, String className) throws SaslException { - initLogger(); myClassName = className; // Parse properties to set desired context options @@ -325,19 +320,15 @@ public abstract class AbstractSaslImpl { } } - /** - * Sets logger field. - */ - private static synchronized void initLogger() { - if (logger == null) { - logger = Logger.getLogger(SASL_LOGGER_NAME); - } - } - // ---------------- Constants ----------------- private static final String SASL_LOGGER_NAME = "javax.security.sasl"; protected static final String MAX_SEND_BUF = "javax.security.sasl.sendmaxbuffer"; + /** + * Logger for debug messages + */ + protected static final Logger logger = Logger.getLogger(SASL_LOGGER_NAME); + // default 0 (no protection); 1 (integrity only) protected static final byte NO_PROTECTION = (byte)1; protected static final byte INTEGRITY_ONLY_PROTECTION = (byte)2; diff --git a/jdk/test/com/sun/security/sasl/util/CheckAccess.java b/jdk/test/com/sun/security/sasl/util/CheckAccess.java new file mode 100644 index 00000000000..9ac0674b15c --- /dev/null +++ b/jdk/test/com/sun/security/sasl/util/CheckAccess.java @@ -0,0 +1,46 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 6657695 + * @summary AbstractSaslImpl.logger is a static mutable (findbugs) + * @author Vincent Ryan + */ + +import java.lang.reflect.*; + +/* + * Check that the 'logger' class member is immutable. + */ +public class CheckAccess { + public static final void main(String[] args) throws Exception { + Class clazz = + Class.forName("com.sun.security.sasl.util.AbstractSaslImpl"); + Field field = clazz.getDeclaredField("logger"); + if (! Modifier.isFinal(field.getModifiers())) { + throw new Exception( + "class member 'logger' must be immutable"); + } + } +} From b838a003268c302ddf5ae15cd78bef658c591375 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Mon, 20 Jul 2009 13:33:09 +0400 Subject: [PATCH 033/215] 6857360: NimbusLAF: Menu indicator looks ugly with RTL orientation Reviewed-by: rupashka --- jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java | 2 ++ jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java index 921ca0ea74c..f96a03c9045 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusIcon.java @@ -84,6 +84,8 @@ class NimbusIcon extends SynthIcon { translatex = 1; } } + } else if (c instanceof JMenu) { + flip = ! c.getComponentOrientation().isLeftToRight(); } if (g instanceof Graphics2D){ Graphics2D gfx = (Graphics2D)g; diff --git a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java index 109d0c4022c..1f0281e9be3 100644 --- a/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java +++ b/jdk/src/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -718,10 +718,10 @@ public class MenuItemLayoutHelper { } private void alignRect(Rectangle rect, int alignment, int origWidth) { - if (alignment != SwingUtilities.LEFT) { + if (alignment == SwingConstants.RIGHT) { rect.x = rect.x + rect.width - origWidth; - rect.width = origWidth; } + rect.width = origWidth; } protected void layoutIconAndTextInLabelRect(LayoutResult lr) { From 4ba0a90189212113e138bd6723442cf640cbc8db Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Mon, 20 Jul 2009 13:34:54 +0400 Subject: [PATCH 034/215] 6849331: Nimbus L&F: AbstractRegionPainter's paint context is not initialized Reviewed-by: rupashka --- .../plaf/nimbus/AbstractRegionPainter.java | 50 +++++++++++++------ 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java index bf29e15221d..f5762f0f0ef 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java @@ -227,10 +227,10 @@ public abstract class AbstractRegionPainter implements Painter { * * @param x an encoded x value (0...1, or 1...2, or 2...3) * @return the decoded x value + * @throws IllegalArgumentException + * if {@code x < 0} or {@code x > 3} */ protected final float decodeX(float x) { - if (ctx.canvasSize == null) return x; - if (x >= 0 && x <= 1) { return x * leftWidth; } else if (x > 1 && x < 2) { @@ -238,7 +238,7 @@ public abstract class AbstractRegionPainter implements Painter { } else if (x >= 2 && x <= 3) { return ((x-2) * rightWidth) + leftWidth + centerWidth; } else { - throw new AssertionError("Invalid x"); + throw new IllegalArgumentException("Invalid x"); } } @@ -248,10 +248,10 @@ public abstract class AbstractRegionPainter implements Painter { * * @param y an encoded y value (0...1, or 1...2, or 2...3) * @return the decoded y value + * @throws IllegalArgumentException + * if {@code y < 0} or {@code y > 3} */ protected final float decodeY(float y) { - if (ctx.canvasSize == null) return y; - if (y >= 0 && y <= 1) { return y * topHeight; } else if (y > 1 && y < 2) { @@ -259,7 +259,7 @@ public abstract class AbstractRegionPainter implements Painter { } else if (y >= 2 && y <= 3) { return ((y-2) * bottomHeight) + topHeight + centerHeight; } else { - throw new AssertionError("Invalid y"); + throw new IllegalArgumentException("Invalid y"); } } @@ -271,10 +271,10 @@ public abstract class AbstractRegionPainter implements Painter { * @param x an encoded x value of the bezier control point (0...1, or 1...2, or 2...3) * @param dx the offset distance to the anchor from the control point x * @return the decoded x location of the control point + * @throws IllegalArgumentException + * if {@code x < 0} or {@code x > 3} */ protected final float decodeAnchorX(float x, float dx) { - if (ctx.canvasSize == null) return x + dx; - if (x >= 0 && x <= 1) { return decodeX(x) + (dx * leftScale); } else if (x > 1 && x < 2) { @@ -282,7 +282,7 @@ public abstract class AbstractRegionPainter implements Painter { } else if (x >= 2 && x <= 3) { return decodeX(x) + (dx * rightScale); } else { - throw new AssertionError("Invalid x"); + throw new IllegalArgumentException("Invalid x"); } } @@ -294,10 +294,10 @@ public abstract class AbstractRegionPainter implements Painter { * @param y an encoded y value of the bezier control point (0...1, or 1...2, or 2...3) * @param dy the offset distance to the anchor from the control point y * @return the decoded y position of the control point + * @throws IllegalArgumentException + * if {@code y < 0} or {@code y > 3} */ protected final float decodeAnchorY(float y, float dy) { - if (ctx.canvasSize == null) return y + dy; - if (y >= 0 && y <= 1) { return decodeY(y) + (dy * topScale); } else if (y > 1 && y < 2) { @@ -305,7 +305,7 @@ public abstract class AbstractRegionPainter implements Painter { } else if (y >= 2 && y <= 3) { return decodeY(y) + (dy * bottomScale); } else { - throw new AssertionError("Invalid y"); + throw new IllegalArgumentException("Invalid y"); } } @@ -363,6 +363,15 @@ public abstract class AbstractRegionPainter implements Painter { * @param midpoints * @param colors * @return a valid LinearGradientPaint. This method never returns null. + * @throws NullPointerException + * if {@code midpoints} array is null, + * or {@code colors} array is null, + * @throws IllegalArgumentException + * if start and end points are the same points, + * or {@code midpoints.length != colors.length}, + * or {@code colors} is less than 2 in size, + * or a {@code midpoints} value is less than 0.0 or greater than 1.0, + * or the {@code midpoints} are not provided in strictly increasing order */ protected final LinearGradientPaint decodeGradient(float x1, float y1, float x2, float y2, float[] midpoints, Color[] colors) { if (x1 == x2 && y1 == y2) { @@ -384,6 +393,15 @@ public abstract class AbstractRegionPainter implements Painter { * @param midpoints * @param colors * @return a valid RadialGradientPaint. This method never returns null. + * @throws NullPointerException + * if {@code midpoints} array is null, + * or {@code colors} array is null + * @throws IllegalArgumentException + * if {@code r} is non-positive, + * or {@code midpoints.length != colors.length}, + * or {@code colors} is less than 2 in size, + * or a {@code midpoints} value is less than 0.0 or greater than 1.0, + * or the {@code midpoints} are not provided in strictly increasing order */ protected final RadialGradientPaint decodeRadialGradient(float x, float y, float r, float[] midpoints, Color[] colors) { if (r == 0f) { @@ -537,10 +555,10 @@ public abstract class AbstractRegionPainter implements Painter { this.maxVerticalScaleFactor = maxV; if (canvasSize != null) { - a = insets.left; - b = canvasSize.width - insets.right; - c = insets.top; - d = canvasSize.height - insets.bottom; + a = stretchingInsets.left; + b = canvasSize.width - stretchingInsets.right; + c = stretchingInsets.top; + d = canvasSize.height - stretchingInsets.bottom; this.canvasSize = canvasSize; this.inverted = inverted; if (inverted) { From 31eb8dfb51a90c8ab8f0b01a1c307c4e00acbbfc Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Mon, 20 Jul 2009 17:16:34 -0400 Subject: [PATCH 035/215] 6787645: CRL validation code should permit some clock skew when checking validity of CRLs Reviewed-by: vinnie --- .../security/cert/CertPathHelperImpl.java | 8 +++-- .../java/security/cert/X509CRLSelector.java | 30 ++++++++++++++++--- .../provider/certpath/CertPathHelper.java | 10 ++++++- .../certpath/CrlRevocationChecker.java | 8 +++-- .../provider/certpath/OCSPResponse.java | 4 +-- 5 files changed, 49 insertions(+), 11 deletions(-) diff --git a/jdk/src/share/classes/java/security/cert/CertPathHelperImpl.java b/jdk/src/share/classes/java/security/cert/CertPathHelperImpl.java index a9998282a25..b279392d442 100644 --- a/jdk/src/share/classes/java/security/cert/CertPathHelperImpl.java +++ b/jdk/src/share/classes/java/security/cert/CertPathHelperImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2009 Sun Microsystems, Inc. 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 @@ -46,7 +46,7 @@ class CertPathHelperImpl extends CertPathHelper { /** * Initialize the helper framework. This method must be called from * the static initializer of each class that is the target of one of - * the methods in this class. This ensures that the helper if initialized + * the methods in this class. This ensures that the helper is initialized * prior to a tunneled call from the Sun provider. */ synchronized static void initialize() { @@ -59,4 +59,8 @@ class CertPathHelperImpl extends CertPathHelper { Set names) { sel.setPathToNamesInternal(names); } + + protected void implSetDateAndTime(X509CRLSelector sel, Date date, long skew) { + sel.setDateAndTime(date, skew); + } } diff --git a/jdk/src/share/classes/java/security/cert/X509CRLSelector.java b/jdk/src/share/classes/java/security/cert/X509CRLSelector.java index b602aee12c5..1fc750db4d0 100644 --- a/jdk/src/share/classes/java/security/cert/X509CRLSelector.java +++ b/jdk/src/share/classes/java/security/cert/X509CRLSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -72,6 +72,10 @@ import sun.security.x509.X500Name; */ public class X509CRLSelector implements CRLSelector { + static { + CertPathHelperImpl.initialize(); + } + private static final Debug debug = Debug.getInstance("certpath"); private HashSet issuerNames; private HashSet issuerX500Principals; @@ -79,6 +83,7 @@ public class X509CRLSelector implements CRLSelector { private BigInteger maxCRL; private Date dateAndTime; private X509Certificate certChecking; + private long skew = 0; /** * Creates an X509CRLSelector. Initially, no criteria are set @@ -417,7 +422,18 @@ public class X509CRLSelector implements CRLSelector { if (dateAndTime == null) this.dateAndTime = null; else - this.dateAndTime = (Date) dateAndTime.clone(); + this.dateAndTime = new Date(dateAndTime.getTime()); + this.skew = 0; + } + + /** + * Sets the dateAndTime criterion and allows for the specified clock skew + * (in milliseconds) when checking against the validity period of the CRL. + */ + void setDateAndTime(Date dateAndTime, long skew) { + this.dateAndTime = + (dateAndTime == null ? null : new Date(dateAndTime.getTime())); + this.skew = skew; } /** @@ -657,8 +673,14 @@ public class X509CRLSelector implements CRLSelector { } return false; } - if (crlThisUpdate.after(dateAndTime) - || nextUpdate.before(dateAndTime)) { + Date nowPlusSkew = dateAndTime; + Date nowMinusSkew = dateAndTime; + if (skew > 0) { + nowPlusSkew = new Date(dateAndTime.getTime() + skew); + nowMinusSkew = new Date(dateAndTime.getTime() - skew); + } + if (nowMinusSkew.after(nextUpdate) + || nowPlusSkew.before(crlThisUpdate)) { if (debug != null) { debug.println("X509CRLSelector.match: update out of range"); } diff --git a/jdk/src/share/classes/sun/security/provider/certpath/CertPathHelper.java b/jdk/src/share/classes/sun/security/provider/certpath/CertPathHelper.java index 38c5130d6d9..b45b20737fa 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/CertPathHelper.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/CertPathHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,11 @@ package sun.security.provider.certpath; +import java.util.Date; import java.util.Set; import java.security.cert.X509CertSelector; +import java.security.cert.X509CRLSelector; import sun.security.x509.GeneralNameInterface; @@ -55,8 +57,14 @@ public abstract class CertPathHelper { protected abstract void implSetPathToNames(X509CertSelector sel, Set names); + protected abstract void implSetDateAndTime(X509CRLSelector sel, Date date, long skew); + static void setPathToNames(X509CertSelector sel, Set names) { instance.implSetPathToNames(sel, names); } + + static void setDateAndTime(X509CRLSelector sel, Date date, long skew) { + instance.implSetDateAndTime(sel, date, skew); + } } diff --git a/jdk/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java b/jdk/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java index 63ee343175d..b462dd5ba08 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -81,6 +81,10 @@ class CrlRevocationChecker extends PKIXCertPathChecker { private static final boolean[] ALL_REASONS = {true, true, true, true, true, true, true, true, true}; + // Maximum clock skew in milliseconds (15 minutes) allowed when checking + // validity of CRLs + private static final long MAX_CLOCK_SKEW = 900000; + /** * Creates a CrlRevocationChecker. * @@ -281,7 +285,7 @@ class CrlRevocationChecker extends PKIXCertPathChecker { try { X509CRLSelector sel = new X509CRLSelector(); sel.setCertificateChecking(currCert); - sel.setDateAndTime(mCurrentTime); + CertPathHelper.setDateAndTime(sel, mCurrentTime, MAX_CLOCK_SKEW); for (CertStore mStore : mStores) { for (java.security.cert.CRL crl : mStore.getCRLs(sel)) { diff --git a/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java b/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java index 62cd4288ed0..cdadc45f66c 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/OCSPResponse.java @@ -149,9 +149,9 @@ class OCSPResponse { private SingleResponse singleResponse; - // Maximum clock skew in milliseconds (10 minutes) allowed when checking + // Maximum clock skew in milliseconds (15 minutes) allowed when checking // validity of OCSP responses - private static final long MAX_CLOCK_SKEW = 600000; + private static final long MAX_CLOCK_SKEW = 900000; // an array of all of the CRLReasons (used in SingleResponse) private static CRLReason[] values = CRLReason.values(); From da10005c86ffc6ea59c644d3473ea89fb196d25a Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 22 Jul 2009 12:21:31 +0400 Subject: [PATCH 036/215] 6802868: JInternalFrame is not maximized when maximized parent frame Reviewed-by: rupashka --- .../swing/plaf/basic/BasicDesktopIconUI.java | 15 +- .../plaf/basic/BasicInternalFrameUI.java | 42 +++-- .../swing/plaf/basic/DesktopIconMover.java | 168 ------------------ .../swing/JInternalFrame/Test6802868.java | 108 +++++++++++ 4 files changed, 136 insertions(+), 197 deletions(-) delete mode 100644 jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java create mode 100644 jdk/test/javax/swing/JInternalFrame/Test6802868.java diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java index 5ebb6289440..888b95aa021 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,9 +32,6 @@ import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.*; import java.beans.*; -import java.util.EventListener; -import java.io.Serializable; - /** * Basic L&F for a minimized window on a desktop. @@ -47,7 +44,6 @@ public class BasicDesktopIconUI extends DesktopIconUI { protected JInternalFrame.JDesktopIcon desktopIcon; protected JInternalFrame frame; - private DesktopIconMover desktopIconMover; /** * The title pane component used in the desktop icon. @@ -128,21 +124,12 @@ public class BasicDesktopIconUI extends DesktopIconUI { mouseInputListener = createMouseInputListener(); desktopIcon.addMouseMotionListener(mouseInputListener); desktopIcon.addMouseListener(mouseInputListener); - getDesktopIconMover().installListeners(); } protected void uninstallListeners() { desktopIcon.removeMouseMotionListener(mouseInputListener); desktopIcon.removeMouseListener(mouseInputListener); mouseInputListener = null; - getDesktopIconMover().uninstallListeners(); - } - - private DesktopIconMover getDesktopIconMover() { - if (desktopIconMover == null) { - desktopIconMover = new DesktopIconMover(desktopIcon); - } - return desktopIconMover; } protected void installDefaults() { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java index 383930533a2..551ab00d602 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java @@ -27,16 +27,10 @@ package javax.swing.plaf.basic; import java.awt.*; import java.awt.event.*; -import java.awt.peer.LightweightPeer; - import javax.swing.*; -import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.event.*; - import java.beans.*; -import java.io.Serializable; - import sun.swing.DefaultLookup; import sun.swing.UIAction; @@ -55,6 +49,7 @@ public class BasicInternalFrameUI extends InternalFrameUI protected MouseInputAdapter borderListener; protected PropertyChangeListener propertyChangeListener; protected LayoutManager internalFrameLayout; + protected ComponentListener componentListener; protected MouseInputListener glassPaneDispatcher; private InternalFrameListener internalFrameListener; @@ -66,9 +61,9 @@ public class BasicInternalFrameUI extends InternalFrameUI protected BasicInternalFrameTitlePane titlePane; // access needs this private static DesktopManager sharedDesktopManager; + private boolean componentListenerAdded = false; private Rectangle parentBounds; - private DesktopIconMover desktopIconMover; private boolean dragging = false; private boolean resizing = false; @@ -209,17 +204,14 @@ public class BasicInternalFrameUI extends InternalFrameUI frame.getGlassPane().addMouseListener(glassPaneDispatcher); frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher); } + componentListener = createComponentListener(); if (frame.getParent() != null) { parentBounds = frame.getParent().getBounds(); } - getDesktopIconMover().installListeners(); - } - - private DesktopIconMover getDesktopIconMover() { - if (desktopIconMover == null) { - desktopIconMover = new DesktopIconMover(frame); + if ((frame.getParent() != null) && !componentListenerAdded) { + frame.getParent().addComponentListener(componentListener); + componentListenerAdded = true; } - return desktopIconMover; } // Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event, @@ -290,7 +282,11 @@ public class BasicInternalFrameUI extends InternalFrameUI * @since 1.3 */ protected void uninstallListeners() { - getDesktopIconMover().uninstallListeners(); + if ((frame.getParent() != null) && componentListenerAdded) { + frame.getParent().removeComponentListener(componentListener); + componentListenerAdded = false; + } + componentListener = null; if (glassPaneDispatcher != null) { frame.getGlassPane().removeMouseListener(glassPaneDispatcher); frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher); @@ -1228,6 +1224,15 @@ public class BasicInternalFrameUI extends InternalFrameUI } } + // Relocate the icon base on the new parent bounds. + if (icon != null) { + Rectangle iconBounds = icon.getBounds(); + int y = iconBounds.y + + (parentNewBounds.height - parentBounds.height); + icon.setBounds(iconBounds.x, y, + iconBounds.width, iconBounds.height); + } + // Update the new parent bounds for next resize. if (!parentBounds.equals(parentNewBounds)) { parentBounds = parentNewBounds; @@ -1399,6 +1404,9 @@ public class BasicInternalFrameUI extends InternalFrameUI // Cancel a resize in progress if the internal frame // gets a setClosed(true) or dispose(). cancelResize(); + if ((frame.getParent() != null) && componentListenerAdded) { + frame.getParent().removeComponentListener(componentListener); + } closeFrame(f); } } else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) { @@ -1431,6 +1439,10 @@ public class BasicInternalFrameUI extends InternalFrameUI } else { parentBounds = null; } + if ((frame.getParent() != null) && !componentListenerAdded) { + f.getParent().addComponentListener(componentListener); + componentListenerAdded = true; + } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || prop == "maximizable") { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java deleted file mode 100644 index deff4f27a5f..00000000000 --- a/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 1997-2008 Sun Microsystems, Inc. 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. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.plaf.basic; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.beans.*; - -/** - * DesktopIconMover is intended to move desktop icon - * when parent window is resized. - */ -class DesktopIconMover implements ComponentListener, PropertyChangeListener { - private Component parent; - private JInternalFrame frame; // if not null, DesktopIconMover(frame) - // constructor was used - private JInternalFrame.JDesktopIcon icon; - private Rectangle parentBounds; - private boolean componentListenerAdded = false; - - public DesktopIconMover(JInternalFrame frame) { - if (frame == null) { - throw new NullPointerException("Frame cannot be null"); - } - this.frame = frame; - this.icon = frame.getDesktopIcon(); - if (icon == null) { - throw new NullPointerException( - "frame.getDesktopIcon() cannot be null"); - } - this.parent = frame.getParent(); - if (this.parent != null) { - parentBounds = this.parent.getBounds(); - } - } - - public DesktopIconMover(JInternalFrame.JDesktopIcon icon) { - if (icon == null) { - throw new NullPointerException("Icon cannot be null"); - } - this.icon = icon; - this.parent = icon.getParent(); - if (this.parent != null) { - parentBounds = this.parent.getBounds(); - } - } - - public void installListeners() { - if (frame != null) { - frame.addPropertyChangeListener(this); - } else { - icon.addPropertyChangeListener(this); - } - addComponentListener(); - } - - public void uninstallListeners() { - if (frame != null) { - frame.removePropertyChangeListener(this); - } else { - icon.removePropertyChangeListener(this); - } - removeComponentListener(); - } - - public void propertyChange(PropertyChangeEvent evt) { - String propName = evt.getPropertyName(); - if ("ancestor".equals(propName)) { - Component newAncestor = (Component) evt.getNewValue(); - - // Remove component listener if parent is changing - Component probablyNewParent = getCurrentParent(); - if ((probablyNewParent != null) && - (!probablyNewParent.equals(parent))) { - removeComponentListener(); - parent = probablyNewParent; - } - - if (newAncestor == null) { - removeComponentListener(); - } else { - addComponentListener(); - } - - // Update parentBounds - if (parent != null) { - parentBounds = parent.getBounds(); - } else { - parentBounds = null; - } - } else if (JInternalFrame.IS_CLOSED_PROPERTY.equals(propName)) { - removeComponentListener(); - } - } - - private void addComponentListener() { - if (!componentListenerAdded && (parent != null)) { - parent.addComponentListener(this); - componentListenerAdded = true; - } - } - - private void removeComponentListener() { - if ((parent != null) && componentListenerAdded) { - parent.removeComponentListener(this); - componentListenerAdded = false; - } - } - - private Component getCurrentParent() { - if (frame != null) { - return frame.getParent(); - } else { - return icon.getParent(); - } - } - - public void componentResized(ComponentEvent e) { - if ((parent == null) || (parentBounds == null)) { - return; - } - - Rectangle parentNewBounds = parent.getBounds(); - if ((parentNewBounds == null) || parentNewBounds.equals(parentBounds)) { - return; - } - - // Move desktop icon only in up-down direction - int newIconY = icon.getLocation().y + - (parentNewBounds.height - parentBounds.height); - icon.setLocation(icon.getLocation().x, newIconY); - - parentBounds = parentNewBounds; - } - - public void componentMoved(ComponentEvent e) { - } - - public void componentShown(ComponentEvent e) { - } - - public void componentHidden(ComponentEvent e) { - } -} diff --git a/jdk/test/javax/swing/JInternalFrame/Test6802868.java b/jdk/test/javax/swing/JInternalFrame/Test6802868.java new file mode 100644 index 00000000000..74410df81fd --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/Test6802868.java @@ -0,0 +1,108 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6802868 + * @summary JInternalFrame is not maximized when maximized parent frame + * @author Alexander Potochkin + */ + +import sun.awt.SunToolkit; + +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Toolkit; +import java.beans.PropertyVetoException; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.SwingUtilities; + +public class Test6802868 { + static JInternalFrame jif; + static JFrame frame; + static Dimension size; + static Point location; + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(20); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JDesktopPane jdp = new JDesktopPane(); + frame.getContentPane().add(jdp); + + jif = new JInternalFrame("Title", true, true, true, true); + jdp.add(jif); + jif.setVisible(true); + + frame.setSize(200, 200); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + try { + jif.setMaximum(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + toolkit.realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + size = jif.getSize(); + frame.setSize(300, 300); + } + }); + toolkit.realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if (jif.getSize().equals(size)) { + throw new RuntimeException("InternalFrame hasn't changed its size"); + } + try { + jif.setIcon(true); + } catch (PropertyVetoException e) { + e.printStackTrace(); + } + location = jif.getDesktopIcon().getLocation(); + frame.setSize(400, 400); + } + }); + toolkit.realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if (jif.getDesktopIcon().getLocation().equals(location)) { + throw new RuntimeException("JDesktopIcon hasn't moved"); + } + } + }); + } +} From f1b3e33db7277a668ccb1e25de308daf7829b1e6 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 22 Jul 2009 16:39:34 +0800 Subject: [PATCH 037/215] 6858589: more changes to Config on system properties Reviewed-by: valeriep --- .../classes/sun/security/krb5/Config.java | 88 +++++------- .../classes/sun/security/krb5/KrbApReq.java | 2 - jdk/test/sun/security/krb5/ConfPlusProp.java | 127 +++++++++++++----- 3 files changed, 124 insertions(+), 93 deletions(-) diff --git a/jdk/src/share/classes/sun/security/krb5/Config.java b/jdk/src/share/classes/sun/security/krb5/Config.java index 8adcba81f53..283e0d28cbf 100644 --- a/jdk/src/share/classes/sun/security/krb5/Config.java +++ b/jdk/src/share/classes/sun/security/krb5/Config.java @@ -70,7 +70,12 @@ public class Config { private static final int BASE16_1 = 16; private static final int BASE16_2 = 16 * 16; private static final int BASE16_3 = 16 * 16 * 16; - private String defaultRealm; // default kdc realm. + + /** + * Specified by system properties. Must be both null or non-null. + */ + private final String defaultRealm; + private final String defaultKDC; // used for native interface private static native String getWindowsDirectory(boolean isSystem); @@ -81,9 +86,8 @@ public class Config { * singleton) is returned. * * @exception KrbException if error occurs when constructing a Config - * instance. Possible causes would be configuration file not - * found, either of java.security.krb5.realm or java.security.krb5.kdc - * not specified, error reading configuration file. + * instance. Possible causes would be either of java.security.krb5.realm or + * java.security.krb5.kdc not specified, error reading configuration file. */ public static synchronized Config getInstance() throws KrbException { if (singleton == null) { @@ -98,9 +102,8 @@ public class Config { * the java.security.krb5.* system properties again. * * @exception KrbException if error occurs when constructing a Config - * instance. Possible causes would be configuration file not - * found, either of java.security.krb5.realm or java.security.krb5.kdc - * not specified, error reading configuration file. + * instance. Possible causes would be either of java.security.krb5.realm or + * java.security.krb5.kdc not specified, error reading configuration file. */ public static synchronized void refresh() throws KrbException { @@ -114,56 +117,37 @@ public class Config { */ private Config() throws KrbException { /* - * If these two system properties are being specified by the user, - * we ignore configuration file. If either one system property is - * specified, we throw exception. If neither of them are specified, - * we load the information from configuration file. + * If either one system property is specified, we throw exception. */ - String kdchost = + String tmp = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction ("java.security.krb5.kdc")); + if (tmp != null) { + // The user can specify a list of kdc hosts separated by ":" + defaultKDC = tmp.replace(':', ' '); + } else { + defaultKDC = null; + } defaultRealm = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction ("java.security.krb5.realm")); - if ((kdchost == null && defaultRealm != null) || - (defaultRealm == null && kdchost != null)) { + if ((defaultKDC == null && defaultRealm != null) || + (defaultRealm == null && defaultKDC != null)) { throw new KrbException ("System property java.security.krb5.kdc and " + "java.security.krb5.realm both must be set or " + "neither must be set."); } - // Read the Kerberos configuration file + // Always read the Kerberos configuration file try { Vector configFile; configFile = loadConfigFile(); stanzaTable = parseStanzaTable(configFile); } catch (IOException ioe) { - // No krb5.conf, no problem. We'll use DNS etc. - } - - if (kdchost != null) { - /* - * If configuration information is only specified by - * properties java.security.krb5.kdc and - * java.security.krb5.realm, we put both in the hashtable - * under [libdefaults]. - */ - if (stanzaTable == null) { - stanzaTable = new Hashtable (); - } - Hashtable kdcs = - (Hashtable)stanzaTable.get("libdefaults"); - if (kdcs == null) { - kdcs = new Hashtable (); - stanzaTable.put("libdefaults", kdcs); - } - kdcs.put("default_realm", defaultRealm); - // The user can specify a list of kdc hosts separated by ":" - kdchost = kdchost.replace(':', ' '); - kdcs.put("kdc", kdchost); + // No krb5.conf, no problem. We'll use DNS or system property etc. } } @@ -295,19 +279,6 @@ public class Config { String result = null; Hashtable subTable; - /* - * In the situation when kdc is specified by - * java.security.krb5.kdc, we get the kdc from [libdefaults] in - * hashtable. - */ - if (name.equalsIgnoreCase("kdc") && - (section.equalsIgnoreCase(getDefault("default_realm", "libdefaults"))) && - (java.security.AccessController.doPrivileged( - new sun.security.action. - GetPropertyAction("java.security.krb5.kdc")) != null)) { - result = getDefault("kdc", "libdefaults"); - return result; - } if (stanzaTable != null) { for (Enumeration e = stanzaTable.keys(); e.hasMoreElements(); ) { stanzaName = (String)e.nextElement(); @@ -1035,13 +1006,13 @@ public class Config { /** * Resets the default kdc realm. * We do not need to synchronize these methods since assignments are atomic + * + * This method was useless. Kept here in case some class still calls it. */ public void resetDefaultRealm(String realm) { - defaultRealm = realm; if (DEBUG) { - System.out.println(">>> Config reset default kdc " + defaultRealm); + System.out.println(">>> Config try resetting default kdc " + realm); } - } /** @@ -1098,6 +1069,9 @@ public class Config { * @return the default realm, always non null */ public String getDefaultRealm() throws KrbException { + if (defaultRealm != null) { + return defaultRealm; + } Exception cause = null; String realm = getDefault("default_realm", "libdefaults"); if ((realm == null) && useDNS_Realm()) { @@ -1142,6 +1116,9 @@ public class Config { if (realm == null) { realm = getDefaultRealm(); } + if (realm.equalsIgnoreCase(defaultRealm)) { + return defaultKDC; + } Exception cause = null; String kdcs = getDefault("kdc", realm); if ((kdcs == null) && useDNS_KDC()) { @@ -1171,6 +1148,9 @@ public class Config { }); } if (kdcs == null) { + if (defaultKDC != null) { + return defaultKDC; + } KrbException ke = new KrbException("Cannot locate KDC"); if (cause != null) { ke.initCause(cause); diff --git a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java index d274b1efbb0..4ed98c5f0cd 100644 --- a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java +++ b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java @@ -294,8 +294,6 @@ public class KrbApReq { apReqMessg.ticket.sname.setRealm(apReqMessg.ticket.realm); enc_ticketPart.cname.setRealm(enc_ticketPart.crealm); - Config.getInstance().resetDefaultRealm(apReqMessg.ticket.realm.toString()); - if (!authenticator.cname.equals(enc_ticketPart.cname)) throw new KrbApErrException(Krb5.KRB_AP_ERR_BADMATCH); diff --git a/jdk/test/sun/security/krb5/ConfPlusProp.java b/jdk/test/sun/security/krb5/ConfPlusProp.java index b1ea2ca5e75..e2c49a237a9 100644 --- a/jdk/test/sun/security/krb5/ConfPlusProp.java +++ b/jdk/test/sun/security/krb5/ConfPlusProp.java @@ -23,31 +23,56 @@ /* * @test * @bug 6857795 + * @buf 6858589 * @summary krb5.conf ignored if system properties on realm and kdc are provided */ import sun.security.krb5.Config; -import sun.security.krb5.KrbException; public class ConfPlusProp { + Config config; public static void main(String[] args) throws Exception { - System.setProperty("java.security.krb5.realm", "R2"); - System.setProperty("java.security.krb5.kdc", "k2"); + new ConfPlusProp().run(); + } + + void refresh() throws Exception { + Config.refresh(); + config = Config.getInstance(); + } + + void checkDefaultRealm(String r) throws Exception { + try { + if (!config.getDefaultRealm().equals(r)) { + throw new AssertionError("Default realm error"); + } + } catch (Exception e) { + if (r != null) throw e; + } + } + + void check(String r, String k) throws Exception { + try { + if (!config.getKDCList(r).equals(k)) { + throw new AssertionError(r + " kdc not " + k); + } + } catch (Exception e) { + if (k != null) throw e; + } + } + + void run() throws Exception { + + // No prop, only conf // Point to a file with existing default_realm System.setProperty("java.security.krb5.conf", System.getProperty("test.src", ".") +"/confplusprop.conf"); - Config config = Config.getInstance(); + refresh(); - if (!config.getDefaultRealm().equals("R2")) { - throw new Exception("Default realm error"); - } - if (!config.getKDCList("R1").equals("k1")) { - throw new Exception("R1 kdc error"); - } - if (!config.getKDCList("R2").equals("k2")) { - throw new Exception("R2 kdc error"); - } + checkDefaultRealm("R1"); + check("R1", "k1"); + check("R2", "old"); + check("R3", null); if (!config.getDefault("forwardable", "libdefaults").equals("well")) { throw new Exception("Extra config error"); } @@ -55,38 +80,66 @@ public class ConfPlusProp { // Point to a file with no libdefaults System.setProperty("java.security.krb5.conf", System.getProperty("test.src", ".") +"/confplusprop2.conf"); - Config.refresh(); + refresh(); - config = Config.getInstance(); + checkDefaultRealm(null); + check("R1", "k12"); + check("R2", "old"); + check("R3", null); - if (!config.getDefaultRealm().equals("R2")) { - throw new Exception("Default realm error again"); + int version = System.getProperty("java.version").charAt(2) - '0'; + System.out.println("JDK version is " + version); + + // Zero-config is supported since 1.7 + if (version >= 7) { + // Point to a non-existing file + System.setProperty("java.security.krb5.conf", "i-am-not-a file"); + refresh(); + + checkDefaultRealm(null); + check("R1", null); + check("R2", null); + check("R3", null); + if (config.getDefault("forwardable", "libdefaults") != null) { + throw new Exception("Extra config error"); + } } - if (!config.getKDCList("R1").equals("k12")) { - throw new Exception("R1 kdc error"); - } - if (!config.getKDCList("R2").equals("k2")) { - throw new Exception("R2 kdc error"); + + // Add prop + System.setProperty("java.security.krb5.realm", "R2"); + System.setProperty("java.security.krb5.kdc", "k2"); + + // Point to a file with existing default_realm + System.setProperty("java.security.krb5.conf", + System.getProperty("test.src", ".") +"/confplusprop.conf"); + refresh(); + + checkDefaultRealm("R2"); + check("R1", "k1"); + check("R2", "k2"); + check("R3", "k2"); + if (!config.getDefault("forwardable", "libdefaults").equals("well")) { + throw new Exception("Extra config error"); } + // Point to a file with no libdefaults + System.setProperty("java.security.krb5.conf", + System.getProperty("test.src", ".") +"/confplusprop2.conf"); + refresh(); + + checkDefaultRealm("R2"); + check("R1", "k12"); + check("R2", "k2"); + check("R3", "k2"); + // Point to a non-existing file System.setProperty("java.security.krb5.conf", "i-am-not-a file"); - Config.refresh(); + refresh(); - config = Config.getInstance(); - - if (!config.getDefaultRealm().equals("R2")) { - throw new Exception("Default realm error"); - } - try { - config.getKDCList("R1"); - throw new Exception("R1 is nowhere"); - } catch (KrbException ke) { - // OK - } - if (!config.getKDCList("R2").equals("k2")) { - throw new Exception("R2 kdc error"); - } + checkDefaultRealm("R2"); + check("R1", "k2"); + check("R2", "k2"); + check("R3", "k2"); if (config.getDefault("forwardable", "libdefaults") != null) { throw new Exception("Extra config error"); } From 20ee77e0d006d665446d3987e56717aadd68335a Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 22 Jul 2009 16:40:04 +0800 Subject: [PATCH 038/215] 6847026: keytool should be able to generate certreq and cert without subject name Reviewed-by: xuelei --- .../classes/sun/security/tools/KeyTool.java | 18 +++-- .../classes/sun/security/util/Resources.java | 1 + .../security/tools/keytool/emptysubject.sh | 68 +++++++++++++++++++ 3 files changed, 81 insertions(+), 6 deletions(-) create mode 100644 jdk/test/sun/security/tools/keytool/emptysubject.sh diff --git a/jdk/src/share/classes/sun/security/tools/KeyTool.java b/jdk/src/share/classes/sun/security/tools/KeyTool.java index 9b4b16fa11d..62d7b3fa464 100644 --- a/jdk/src/share/classes/sun/security/tools/KeyTool.java +++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java @@ -1052,7 +1052,7 @@ public final class KeyTool { X509CertImpl signerCertImpl = new X509CertImpl(encoded); X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get( X509CertImpl.NAME + "." + X509CertImpl.INFO); - X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." + + X500Name issuer = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateSubjectName.DN_NAME); Date firstDate = getStartDate(startDate); @@ -1068,7 +1068,7 @@ public final class KeyTool { Signature signature = Signature.getInstance(sigAlgName); signature.initSign(privateKey); - X500Signer signer = new X500Signer(signature, owner); + X500Signer signer = new X500Signer(signature, issuer); X509CertInfo info = new X509CertInfo(); info.set(X509CertInfo.VALIDITY, interval); @@ -1102,7 +1102,8 @@ public final class KeyTool { PKCS10 req = new PKCS10(rawReq); info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo())); - info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(req.getSubjectName())); + info.set(X509CertInfo.SUBJECT, new CertificateSubjectName( + dname==null?req.getSubjectName():new X500Name(dname))); CertificateExtensions reqex = null; Iterator attrs = req.getAttributes().getAttributes().iterator(); while (attrs.hasNext()) { @@ -1160,8 +1161,9 @@ public final class KeyTool { Signature signature = Signature.getInstance(sigAlgName); signature.initSign(privKey); - X500Name subject = - new X500Name(((X509Certificate)cert).getSubjectDN().toString()); + X500Name subject = dname == null? + new X500Name(((X509Certificate)cert).getSubjectDN().toString()): + new X500Name(dname); X500Signer signer = new X500Signer(signature, subject); // Sign the request and base-64 encode it @@ -3428,7 +3430,7 @@ public final class KeyTool { int colonpos = name.indexOf(':'); if (colonpos >= 0) { - if (name.substring(colonpos+1).equalsIgnoreCase("critical")) { + if (oneOf(name.substring(colonpos+1), "critical") == 0) { isCritical = true; } name = name.substring(0, colonpos); @@ -3688,6 +3690,8 @@ public final class KeyTool { ("-certreq [-v] [-protected]")); System.err.println(rb.getString ("\t [-alias ] [-sigalg ]")); + System.err.println(rb.getString + ("\t [-dname ]")); System.err.println(rb.getString ("\t [-file ] [-keypass ]")); System.err.println(rb.getString @@ -3770,6 +3774,8 @@ public final class KeyTool { ("\t [-infile ] [-outfile ]")); System.err.println(rb.getString ("\t [-alias ]")); + System.err.println(rb.getString + ("\t [-dname ]")); System.err.println(rb.getString ("\t [-sigalg ]")); System.err.println(rb.getString diff --git a/jdk/src/share/classes/sun/security/util/Resources.java b/jdk/src/share/classes/sun/security/util/Resources.java index c8c5e386de1..d837ae9b0c9 100644 --- a/jdk/src/share/classes/sun/security/util/Resources.java +++ b/jdk/src/share/classes/sun/security/util/Resources.java @@ -301,6 +301,7 @@ public class Resources extends java.util.ListResourceBundle { "-certreq [-v] [-protected]"}, {"\t [-alias ] [-sigalg ]", "\t [-alias ] [-sigalg ]"}, + {"\t [-dname ]", "\t [-dname ]"}, {"\t [-file ] [-keypass ]", "\t [-file ] [-keypass ]"}, {"\t [-keystore ] [-storepass ]", diff --git a/jdk/test/sun/security/tools/keytool/emptysubject.sh b/jdk/test/sun/security/tools/keytool/emptysubject.sh new file mode 100644 index 00000000000..ffe681c42aa --- /dev/null +++ b/jdk/test/sun/security/tools/keytool/emptysubject.sh @@ -0,0 +1,68 @@ +# +# Copyright 2009 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# @test +# @bug 6847026 +# @summary keytool should be able to generate certreq and cert without subject name +# +# @run shell emptysubject.sh +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + ;; +esac + +KS=emptysubject.jks +KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore $KS" + +rm $KS + +$KT -alias ca -dname CN=CA -genkeypair +$KT -alias me -dname CN=Me -genkeypair + +# When -dname is recognized, SAN must be specfied, otherwise, -printcert fails. +$KT -alias me -certreq -dname "" | \ + $KT -alias ca -gencert | $KT -printcert && exit 1 +$KT -alias me -certreq | \ + $KT -alias ca -gencert -dname "" | $KT -printcert && exit 2 +$KT -alias me -certreq -dname "" | \ + $KT -alias ca -gencert -ext san:c=email:me@me.com | \ + $KT -printcert || exit 3 +$KT -alias me -certreq | \ + $KT -alias ca -gencert -dname "" -ext san:c=email:me@me.com | \ + $KT -printcert || exit 4 + +exit 0 + From ee5188c4c3dadc3adecfa173f4c18e40daf962c6 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 22 Jul 2009 16:40:39 +0800 Subject: [PATCH 039/215] 6854308: more ktab options Reviewed-by: mullan --- .../security/krb5/internal/ktab/KeyTab.java | 27 +++- .../security/krb5/internal/tools/Klist.java | 1 + .../security/krb5/internal/tools/Ktab.java | 126 +++++++++++++----- 3 files changed, 112 insertions(+), 42 deletions(-) diff --git a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java index 4fd7b3bf4e6..d7c5484ec0c 100644 --- a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java +++ b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2000-2009 Sun Microsystems, Inc. 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 @@ -403,11 +403,11 @@ public class KeyTab implements KeyTabConstants { /** * Retrieves the key table entry with the specified service name. * @param service the service which may have an entry in the key table. + * @param keyType the etype to match, returns the 1st one if -1 provided * @return -1 if the entry is not found, else return the entry index * in the list. */ private int retrieveEntry(PrincipalName service, int keyType) { - int found = -1; KeyTabEntry e; if (entries != null) { for (int i = 0; i < entries.size(); i++) { @@ -418,7 +418,7 @@ public class KeyTab implements KeyTabConstants { } } } - return found; + return -1; } /** @@ -476,12 +476,29 @@ public class KeyTab implements KeyTabConstants { /** * Removes an entry from the key table. * @param service the service PrincipalName. + * @param etype the etype to match, first one if -1 provided + * @return 1 if removed successfully, 0 otherwise */ - public void deleteEntry(PrincipalName service) { - int result = retrieveEntry(service, -1); + public int deleteEntry(PrincipalName service, int etype) { + int result = retrieveEntry(service, etype); if (result != -1) { entries.removeElementAt(result); + return 1; } + return 0; + } + + /** + * Removes an entry from the key table. + * @param service the service PrincipalName. + * @return number of entries removed + */ + public int deleteEntry(PrincipalName service) { + int count = 0; + while (deleteEntry(service, -1) > 0) { + count++; + } + return count; } /** diff --git a/jdk/src/windows/classes/sun/security/krb5/internal/tools/Klist.java b/jdk/src/windows/classes/sun/security/krb5/internal/tools/Klist.java index c4724fbd382..5cb919b9d52 100644 --- a/jdk/src/windows/classes/sun/security/krb5/internal/tools/Klist.java +++ b/jdk/src/windows/classes/sun/security/krb5/internal/tools/Klist.java @@ -1,4 +1,5 @@ /* + * Portions Copyright 2003-2009 Sun Microsystems, Inc. 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 diff --git a/jdk/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java b/jdk/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java index b773189c113..30be1b51405 100644 --- a/jdk/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java +++ b/jdk/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java @@ -1,4 +1,5 @@ /* + * Portions Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,16 +31,15 @@ package sun.security.krb5.internal.tools; import sun.security.krb5.*; -import sun.security.krb5.internal.*; import sun.security.krb5.internal.ktab.*; -import sun.security.krb5.KrbCryptoException; -import java.lang.RuntimeException; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; -import java.io.FileOutputStream; import java.io.File; +import java.text.DateFormat; import java.util.Arrays; +import java.util.Date; +import sun.security.krb5.internal.crypto.EType; /** * This class can execute as a command-line tool to help the user manage * entires in the key table. @@ -55,6 +55,9 @@ public class Ktab { char action; String name; // name and directory of key table String principal; + boolean showEType; + boolean showTime; + int etype = -1; char[] password = null; /** @@ -62,13 +65,14 @@ public class Ktab { *
Usage: ktab *
available options to Ktab: *