From 65e203be59bea3231eec65fe94cc45902d72f9ae Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Tue, 20 Oct 2009 10:59:13 -0700 Subject: [PATCH 01/56] 6893062: remove support for obsolete attributes Reviewed-by: ksrini --- .../com/sun/tools/classfile/Attribute.java | 20 ------ .../com/sun/tools/classfile/ClassWriter.java | 19 ----- .../ModuleExportTable_attribute.java | 70 ------------------- .../ModuleMemberTable_attribute.java | 69 ------------------ .../sun/tools/classfile/Module_attribute.java | 64 ----------------- .../com/sun/tools/javap/AttributeWriter.java | 60 ---------------- .../com/sun/tools/javap/JavapTask.java | 7 -- .../classes/com/sun/tools/javap/Options.java | 1 - 8 files changed, 310 deletions(-) delete mode 100644 langtools/src/share/classes/com/sun/tools/classfile/ModuleExportTable_attribute.java delete mode 100644 langtools/src/share/classes/com/sun/tools/classfile/ModuleMemberTable_attribute.java delete mode 100644 langtools/src/share/classes/com/sun/tools/classfile/Module_attribute.java diff --git a/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java b/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java index 326de77a7c9..997e5ebe1fb 100644 --- a/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java +++ b/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java @@ -64,11 +64,6 @@ public abstract class Attribute { public static final String StackMapTable = "StackMapTable"; public static final String Synthetic = "Synthetic"; - // JSR 277/294 - public static final String Module = "Module"; - public static final String ModuleExportTable = "ModuleExportTable"; - public static final String ModuleMemberTable = "ModuleMemberTable"; - public static class Factory { public Factory() { // defer init of standardAttributeClasses until after options set up @@ -78,10 +73,6 @@ public abstract class Attribute { this.compat = compat; } - public void setJSR277(boolean jsr277) { - this.jsr277 = jsr277; - } - public Attribute createAttribute(ClassReader cr, int name_index, byte[] data) throws IOException { if (standardAttributes == null) @@ -121,12 +112,6 @@ public abstract class Attribute { standardAttributes.put(LocalVariableTable, LocalVariableTable_attribute.class); standardAttributes.put(LocalVariableTypeTable, LocalVariableTypeTable_attribute.class); - if (jsr277) { - standardAttributes.put(Module, Module_attribute.class); - standardAttributes.put(ModuleExportTable, ModuleExportTable_attribute.class); - standardAttributes.put(ModuleMemberTable, ModuleMemberTable_attribute.class); - } - if (!compat) { // old javap does not recognize recent attributes standardAttributes.put(CompilationID, CompilationID_attribute.class); standardAttributes.put(RuntimeInvisibleAnnotations, RuntimeInvisibleAnnotations_attribute.class); @@ -148,7 +133,6 @@ public abstract class Attribute { private Map> standardAttributes; private boolean compat; // don't support recent attrs in compatibility mode - private boolean jsr277; // support new jsr277 attrs } public static Attribute read(ClassReader cr) throws IOException { @@ -201,9 +185,5 @@ public abstract class Attribute { R visitStackMap(StackMap_attribute attr, P p); R visitStackMapTable(StackMapTable_attribute attr, P p); R visitSynthetic(Synthetic_attribute attr, P p); - - R visitModule(Module_attribute attr, P p); - R visitModuleExportTable(ModuleExportTable_attribute attr, P p); - R visitModuleMemberTable(ModuleMemberTable_attribute attr, P p); } } diff --git a/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java b/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java index 8f8a6edab5e..6b2bad47c37 100644 --- a/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java +++ b/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java @@ -449,25 +449,6 @@ public class ClassWriter { out.writeShort(entry.index); } - public Void visitModule(Module_attribute attr, ClassOutputStream out) { - out.writeShort(attr.module_name); - return null; - } - - public Void visitModuleExportTable(ModuleExportTable_attribute attr, ClassOutputStream out) { - out.writeShort(attr.export_type_table.length); - for (int i: attr.export_type_table) - out.writeShort(i); - return null; - } - - public Void visitModuleMemberTable(ModuleMemberTable_attribute attr, ClassOutputStream out) { - out.writeShort(attr.package_member_table.length); - for (int i: attr.package_member_table) - out.writeShort(i); - return null; - } - public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, ClassOutputStream out) { annotationWriter.write(attr.annotations, out); return null; diff --git a/langtools/src/share/classes/com/sun/tools/classfile/ModuleExportTable_attribute.java b/langtools/src/share/classes/com/sun/tools/classfile/ModuleExportTable_attribute.java deleted file mode 100644 index 74cc3b395c6..00000000000 --- a/langtools/src/share/classes/com/sun/tools/classfile/ModuleExportTable_attribute.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2007-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 com.sun.tools.classfile; - -import java.io.IOException; - -/** - * See JSR 277. - * - *

This is NOT part of any API supported by Sun Microsystems. If - * you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. - */ -public class ModuleExportTable_attribute extends Attribute { - ModuleExportTable_attribute(ClassReader cr, int name_index, int length) throws IOException { - super(name_index, length); - int export_type_length = cr.readUnsignedShort(); - export_type_table = new int[export_type_length]; - for (int i = 0; i < export_type_table.length; i++) - export_type_table[i] = cr.readUnsignedShort(); - } - - public ModuleExportTable_attribute(ConstantPool cp, int[] export_type_table) - throws ConstantPoolException { - this(cp.getUTF8Index(Attribute.ModuleExportTable), export_type_table); - } - - public ModuleExportTable_attribute(int name_index, int[] export_type_table) { - super(name_index, 2 + 2 * export_type_table.length); - this.export_type_table = export_type_table; - } - - public int getExportTypeCount() { - return export_type_table.length; - } - - public String getExportTypeName(int index, ConstantPool constant_pool) throws ConstantPoolException { - return constant_pool.getUTF8Value(export_type_table[index]); - } - - public R accept(Visitor visitor, P p) { - return visitor.visitModuleExportTable(this, p); - } - - public final int[] export_type_table; -} diff --git a/langtools/src/share/classes/com/sun/tools/classfile/ModuleMemberTable_attribute.java b/langtools/src/share/classes/com/sun/tools/classfile/ModuleMemberTable_attribute.java deleted file mode 100644 index c5eaf78eff5..00000000000 --- a/langtools/src/share/classes/com/sun/tools/classfile/ModuleMemberTable_attribute.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2007-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 com.sun.tools.classfile; - -import java.io.IOException; - -/** - * See JSR 277. - * - *

This is NOT part of any API supported by Sun Microsystems. If - * you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. - */ -public class ModuleMemberTable_attribute extends Attribute { - ModuleMemberTable_attribute(ClassReader cr, int name_index, int length) throws IOException { - super(name_index, length); - int package_member_length = cr.readUnsignedShort(); - package_member_table = new int[package_member_length]; - for (int i = 0; i < package_member_table.length; i++) - package_member_table[i] = cr.readUnsignedShort(); - } - - public ModuleMemberTable_attribute(ConstantPool cp, int[] package_member_table) - throws ConstantPoolException { - this(cp.getUTF8Index(Attribute.ModuleMemberTable), package_member_table); - } - - public ModuleMemberTable_attribute(int name_index, int[] package_member_table) { - super(name_index, 2 + 2 * package_member_table.length); - this.package_member_table = package_member_table; - } - - public int getPackageMemberCount() { - return package_member_table.length; - } - - public String getPackageMemberName(int index, ConstantPool constant_pool) throws ConstantPoolException { - return constant_pool.getUTF8Value(package_member_table[index]); - } - - public R accept(Visitor visitor, P p) { - return visitor.visitModuleMemberTable(this, p); - } - - public final int[] package_member_table; -} diff --git a/langtools/src/share/classes/com/sun/tools/classfile/Module_attribute.java b/langtools/src/share/classes/com/sun/tools/classfile/Module_attribute.java deleted file mode 100644 index 8a1ba1fef87..00000000000 --- a/langtools/src/share/classes/com/sun/tools/classfile/Module_attribute.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2007-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 com.sun.tools.classfile; - -import java.io.IOException; - -/** - * See JSR 277. - * - *

This is NOT part of any API supported by Sun Microsystems. If - * you write code that depends on this, you do so at your own risk. - * This code and its internal interfaces are subject to change or - * deletion without notice. - */ -public class Module_attribute extends Attribute { - Module_attribute(ClassReader cr, int name_index, int length) throws IOException { - super(name_index, length); - module_name = cr.readUnsignedShort(); - } - - public Module_attribute(ConstantPool constant_pool, int module_name) - throws ConstantPoolException { - this(constant_pool.getUTF8Index(Attribute.Module), module_name); - } - - public Module_attribute(int name_index, int module_name) { - super(name_index, 2); - this.module_name = module_name; - } - - public String getModuleName(ConstantPool constant_pool) throws ConstantPoolException { - return constant_pool.getUTF8Value(module_name); - } - - public R accept(Visitor visitor, D data) { - return visitor.visitModule(this, data); - } - - public final int module_name; - -} diff --git a/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java b/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java index 42567342b31..46c8530340a 100644 --- a/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java +++ b/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java @@ -45,9 +45,6 @@ import com.sun.tools.classfile.InnerClasses_attribute; import com.sun.tools.classfile.LineNumberTable_attribute; import com.sun.tools.classfile.LocalVariableTable_attribute; import com.sun.tools.classfile.LocalVariableTypeTable_attribute; -import com.sun.tools.classfile.ModuleExportTable_attribute; -import com.sun.tools.classfile.ModuleMemberTable_attribute; -import com.sun.tools.classfile.Module_attribute; import com.sun.tools.classfile.RuntimeInvisibleAnnotations_attribute; import com.sun.tools.classfile.RuntimeInvisibleParameterAnnotations_attribute; import com.sun.tools.classfile.RuntimeInvisibleTypeAnnotations_attribute; @@ -372,63 +369,6 @@ public class AttributeWriter extends BasicWriter return null; } - public Void visitModule(Module_attribute attr, Void ignore) { - print("Module: #" + attr.module_name); - tab(); - println("// " + getModuleName(attr)); - return null; - } - - String getModuleName(Module_attribute attr) { - try { - return attr.getModuleName(constant_pool); - } catch (ConstantPoolException e) { - return report(e); - } - } - - public Void visitModuleExportTable(ModuleExportTable_attribute attr, Void ignore) { - println("ModuleExportTable:"); - indent(+1); - println("Types: (" + attr.export_type_table.length + ")"); - for (int i = 0; i < attr.export_type_table.length; i++) { - print("#" + attr.export_type_table[i]); - tab(); - println("// " + getExportTypeName(attr, i)); - } - indent(-1); - return null; - } - - String getExportTypeName(ModuleExportTable_attribute attr, int index) { - try { - return attr.getExportTypeName(index, constant_pool); - } catch (ConstantPoolException e) { - return report(e); - } - } - - public Void visitModuleMemberTable(ModuleMemberTable_attribute attr, Void ignore) { - println("ModuleMemberTable:"); - indent(+1); - println("Packages: (" + attr.package_member_table.length + ")"); - for (int i = 0; i < attr.package_member_table.length; i++) { - print("#" + attr.package_member_table[i]); - tab(); - println("// " + getPackageMemberName(attr, i)); - } - indent(-1); - return null; - } - - String getPackageMemberName(ModuleMemberTable_attribute attr, int index) { - try { - return attr.getPackageMemberName(index, constant_pool); - } catch (ConstantPoolException e) { - return report(e); - } - } - public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, Void ignore) { println("RuntimeVisibleAnnotations:"); indent(+1); diff --git a/langtools/src/share/classes/com/sun/tools/javap/JavapTask.java b/langtools/src/share/classes/com/sun/tools/javap/JavapTask.java index c68cff26b6b..cb1fd4df5c2 100644 --- a/langtools/src/share/classes/com/sun/tools/javap/JavapTask.java +++ b/langtools/src/share/classes/com/sun/tools/javap/JavapTask.java @@ -236,12 +236,6 @@ public class JavapTask implements DisassemblerTool.DisassemblerTask, Messages { } }, - new Option(false, "-XDjsr277") { - void process(JavapTask task, String opt, String arg) { - task.options.jsr277 = true; - } - }, - new Option(false, "-XDdetails") { void process(JavapTask task, String opt, String arg) { task.options.details = EnumSet.allOf(InstructionDetailWriter.Kind.class); @@ -586,7 +580,6 @@ public class JavapTask implements DisassemblerTool.DisassemblerTask, Messages { sourceWriter.setFileManager(fileManager); attributeFactory.setCompat(options.compat); - attributeFactory.setJSR277(options.jsr277); boolean ok = true; diff --git a/langtools/src/share/classes/com/sun/tools/javap/Options.java b/langtools/src/share/classes/com/sun/tools/javap/Options.java index 0ff78a7edd2..c0f5d00eb6e 100644 --- a/langtools/src/share/classes/com/sun/tools/javap/Options.java +++ b/langtools/src/share/classes/com/sun/tools/javap/Options.java @@ -90,5 +90,4 @@ public class Options { public int tabColumn = 40; // column number for comments public boolean compat; // bug-for-bug compatibility mode with old javap - public boolean jsr277; } From 59ea6ab4d53e1247496c73b48d51a8118daeb2bb Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Wed, 11 Nov 2009 11:17:51 -0800 Subject: [PATCH 02/56] 6900341: jaxp/jaxws ant scripts using ant runtime in classpath, needs to be explicit Reviewed-by: tbell --- jaxp/build.properties | 4 ++++ jaxp/build.xml | 5 ++++- jaxp/make/Makefile | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/jaxp/build.properties b/jaxp/build.properties index 9e5f63306c9..f31b4057a9e 100644 --- a/jaxp/build.properties +++ b/jaxp/build.properties @@ -34,6 +34,10 @@ drops.dir=${slashjava}/devtools/share/jdk7-drops # one of the standard user build.properties files (see build.xml) javac.jar=${bootstrap.dir}/lib/javac.jar +# The tools.jar is needed in the classpath to compile these sources +jdk.home=${java.home}/.. +tools.jar=${jdk.home}/lib/tools.jar + # options for the tasks used to compile the tools javac.source = 7 javac.target = 7 diff --git a/jaxp/build.xml b/jaxp/build.xml index 28831d69a0b..2f263826d21 100644 --- a/jaxp/build.xml +++ b/jaxp/build.xml @@ -113,7 +113,10 @@ - Date: Wed, 11 Nov 2009 11:19:10 -0800 Subject: [PATCH 03/56] 6900341: jaxp/jaxws ant scripts using ant runtime in classpath, needs to be explicit Reviewed-by: tbell --- jaxws/build.properties | 4 ++++ jaxws/build.xml | 5 ++++- jaxws/make/Makefile | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/jaxws/build.properties b/jaxws/build.properties index 9e5f63306c9..f31b4057a9e 100644 --- a/jaxws/build.properties +++ b/jaxws/build.properties @@ -34,6 +34,10 @@ drops.dir=${slashjava}/devtools/share/jdk7-drops # one of the standard user build.properties files (see build.xml) javac.jar=${bootstrap.dir}/lib/javac.jar +# The tools.jar is needed in the classpath to compile these sources +jdk.home=${java.home}/.. +tools.jar=${jdk.home}/lib/tools.jar + # options for the tasks used to compile the tools javac.source = 7 javac.target = 7 diff --git a/jaxws/build.xml b/jaxws/build.xml index b14eb6b8bd8..5ee8f190b25 100644 --- a/jaxws/build.xml +++ b/jaxws/build.xml @@ -113,7 +113,10 @@ - Date: Thu, 12 Nov 2009 15:35:34 -0800 Subject: [PATCH 04/56] Added tag jdk7-b76 for changeset ef0a6062eaec --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index a3ac772f914..a82460bf48f 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -50,3 +50,4 @@ e1b972ff53cd58f825791f8ed9b2deffd16e768c jdk7-b68 3ac6dcf7823205546fbbc3d4ea59f37358d0b0d4 jdk7-b73 2c88089b6e1c053597418099a14232182c387edc jdk7-b74 d1516b9f23954b29b8e76e6f4efc467c08c78133 jdk7-b75 +c8b63075403d53a208104a8a6ea5072c1cb66aab jdk7-b76 From 24dd77625158ac4657b61ea7b88ce4d5d1e550ca Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 12 Nov 2009 15:35:35 -0800 Subject: [PATCH 05/56] Added tag jdk7-b76 for changeset 2180f3e03264 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index 98a13b65b6a..9e8067101da 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -50,3 +50,4 @@ c793a31209263fbb867c23c752599d85c21abb73 jdk7-b72 b751c528c55560cf2adeaeef24b39ca1f4d1cbf7 jdk7-b73 5d0cf59a3203b9f57aceebc33ae656b884987955 jdk7-b74 0fb137085952c8e47878e240d1cb40f14de463c4 jdk7-b75 +937144222e2219939101b0129d26a872a7956b13 jdk7-b76 From 39adc1c2b245cc2ae34cb716e84d1774bc608ecc Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 12 Nov 2009 15:35:38 -0800 Subject: [PATCH 06/56] Added tag jdk7-b76 for changeset 02d36709a16f --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index b8ce5272692..d91cec8c3fe 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -50,3 +50,4 @@ a94714c550658fd6741793ef036cb9625dc2ab1a jdk7-b72 faf94d94786b621f8e13cbcc941ca69c6d967c3f jdk7-b73 f4b900403d6e4b0af51447bd13bbe23fe3a1dac7 jdk7-b74 d8dd291a362acb656026a9c0a9da48501505a1e7 jdk7-b75 +9174bb32e934965288121f75394874eeb1fcb649 jdk7-b76 From 1511ef1bd90fe2538eb93f31a3d99bf6e9c32717 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 12 Nov 2009 15:35:43 -0800 Subject: [PATCH 07/56] Added tag jdk7-b76 for changeset 430015834eb3 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index e3f8d778afd..9f0017be4e7 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -50,3 +50,4 @@ ff94d8ce0daded647bb326630e643d010357afce jdk7-b71 feb05980f9f2964e6bc2b3a8532f9b3054c2289b jdk7-b73 ea7b88c676dd8b269bc858a4a17c14dc96c8aed1 jdk7-b74 555fb78ee4cebed082ca7ddabff46d2e5b4c9026 jdk7-b75 +233a4871d3364ec305efd4a58cfd676620a03a90 jdk7-b76 From 4a8601fc81929b32310409d377d34b01b9f2a46b Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 12 Nov 2009 15:35:47 -0800 Subject: [PATCH 08/56] Added tag jdk7-b76 for changeset bd5ae0a4bc94 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index f5bb90ab7a2..80b5e997f98 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -50,3 +50,4 @@ dd3c5f3ec28d5d5e5c0dc3229fdd52d85d04274d jdk7-b70 558985e26fe16f5a6ebb2edb9180a42e1c8e8202 jdk7-b73 f4466e1b608088c90e11beaa4b600f102608c6a1 jdk7-b74 fcf2b8b5d606641659419f247fcee4b284c45e6e jdk7-b75 +765d2077d1e652e234d27fe85ba58a986b488503 jdk7-b76 From 4d0aedf53a82af97ef863e9a8bc3516cef350f2c Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 12 Nov 2009 15:36:01 -0800 Subject: [PATCH 09/56] Added tag jdk7-b76 for changeset bd950c8f4fb3 --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index 7fb6b91c680..ed1d1b15d59 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -50,3 +50,4 @@ ce9bcdcb7859bb7ef10afd078ad59ba7847f208d jdk7-b69 9596dff460935f09684c11d156ce591f92584f0d jdk7-b73 1a66b08deed0459054b5b1bea3dfbead30d258fa jdk7-b74 2485f5641ed0829205aaaeb31ad711c2c2ef0de3 jdk7-b75 +8fb9b4be3cb1574302acde90549a4d333ef51e93 jdk7-b76 From 1b92857246b26e94fe547002ffc7c2e9ed3d233e Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Wed, 18 Nov 2009 12:34:26 -0500 Subject: [PATCH 10/56] 6894461: OCSP Checker should not wrap all Exception as "Unable to send OCSP request."(introduced by #6885667) Reviewed-by: vinnie, xuelei --- .../sun/security/provider/certpath/OCSPChecker.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/jdk/src/share/classes/sun/security/provider/certpath/OCSPChecker.java b/jdk/src/share/classes/sun/security/provider/certpath/OCSPChecker.java index 499a5912aca..3d17803f765 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/OCSPChecker.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/OCSPChecker.java @@ -335,10 +335,13 @@ class OCSPChecker extends PKIXCertPathChecker { response = OCSP.check(Collections.singletonList(certId), uri, responderCert, pkixParams.getDate()); } catch (Exception e) { - // Wrap all exceptions in CertPathValidatorException so that - // we can fallback to CRLs, if enabled. - throw new CertPathValidatorException - ("Unable to send OCSP request", e); + if (e instanceof CertPathValidatorException) { + throw (CertPathValidatorException) e; + } else { + // Wrap exceptions in CertPathValidatorException so that + // we can fallback to CRLs, if enabled. + throw new CertPathValidatorException(e); + } } RevocationStatus rs = (RevocationStatus) response.getSingleResponse(certId); From 5ef31ba1520a78cfe849efd0cc602a0ec38a3c2d Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Wed, 18 Nov 2009 11:10:18 -0800 Subject: [PATCH 11/56] 6902323: Fix testcase sun/tools/native2ascii/NativeErrors.java 6902325: Fix testcase sun/tools/jhat/HatHeapDump1Test.java Reviewed-by: tbell, dcubed --- jdk/test/ProblemList.txt | 6 ------ jdk/test/sun/tools/jhat/HatRun.java | 4 +++- .../sun/tools/native2ascii/NativeErrors.java | 20 +++++++++++++++++-- jdk/test/sun/tools/native2ascii/test2 | 1 - 4 files changed, 21 insertions(+), 10 deletions(-) delete mode 100644 jdk/test/sun/tools/native2ascii/test2 diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 9a366c1ba8f..4bced4d851b 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -1117,9 +1117,6 @@ sun/jvmstat/monitor/MonitoredVm/CR6672135.java generic-all # Unexpected Monitor Exception, solaris sparc -client sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.sh generic-all -# Probably should be samevm, but seem to cause errors even in othervm at times -sun/tools/jhat/HatHeapDump1Test.java generic-all - # Problems on windows, jmap.exe hangs? (these run jmap) sun/tools/jmap/Basic.sh windows-all @@ -1129,9 +1126,6 @@ sun/tools/jstatd/jstatdDefaults.sh solaris-all # Solaris sparcv9, jps output does not match, x64 different sun/tools/jstatd/jstatdExternalRegistry.sh solaris-all -# Probably should be samevm, but seem to cause errors even in othervm at times -sun/tools/native2ascii/NativeErrors.java generic-all - # Solaris 10 sparc 32bit -client, java.lang.AssertionError: Some tests failed tools/jar/JarEntryTime.java generic-all diff --git a/jdk/test/sun/tools/jhat/HatRun.java b/jdk/test/sun/tools/jhat/HatRun.java index cac66e57d8c..cb1e41b248e 100644 --- a/jdk/test/sun/tools/jhat/HatRun.java +++ b/jdk/test/sun/tools/jhat/HatRun.java @@ -186,11 +186,13 @@ public class HatRun { */ int nvm_options = 0; if ( vm_options != null ) nvm_options = vm_options.length; - String cmd[] = new String[1 + (d64?1:0) + 5 + nvm_options]; + String cmd[] = new String[1 + (d64?1:0) + 7 + nvm_options]; int i,j; i = 0; cmd[i++] = java; + cmd[i++] = "-cp"; + cmd[i++] = cdir; cmd[i++] = "-Dtest.classes=" + cdir; if ( d64 ) { cmd[i++] = "-d64"; diff --git a/jdk/test/sun/tools/native2ascii/NativeErrors.java b/jdk/test/sun/tools/native2ascii/NativeErrors.java index 460a9f158cf..c0fbad160e0 100644 --- a/jdk/test/sun/tools/native2ascii/NativeErrors.java +++ b/jdk/test/sun/tools/native2ascii/NativeErrors.java @@ -59,15 +59,28 @@ public class NativeErrors { in = new BufferedReader(new InputStreamReader(p.getInputStream())); checkResult(in, "err.bad.arg"); - command = getComString("test123"); + File f0 = new File(System.getProperty("test.src", "."), "test123"); + String path0 = f0.getPath(); + if ( f0.exists() ) { + throw new Error("Input file should not exist: " + path0); + } + + command = getComString(path0); p = Runtime.getRuntime().exec(command); in = new BufferedReader(new InputStreamReader(p.getInputStream())); checkResult(in, "err.cannot.read"); File f1 = new File(System.getProperty("test.src", "."), "test1"); - File f2 = new File(System.getProperty("test.src", "."), "test2"); + File f2 = File.createTempFile("test2", ".tmp"); String path1 = f1.getPath(); String path2 = f2.getPath(); + if ( !f1.exists() ) { + throw new Error("Missing input file: " + path1); + } + if ( !f2.setWritable(false) ) { + throw new Error("Output file cannot be made read only: " + path2); + } + f2.deleteOnExit(); command = getComString(path1, path2); p = Runtime.getRuntime().exec(command); @@ -80,7 +93,9 @@ public class NativeErrors { throws Exception { String errorReceived; errorReceived = in.readLine(); + assert errorReceived != null : "First readline cannot be null"; errorExpected = rsrc.getString(errorExpected); + assert errorExpected != null : "Expected message cannot be null"; StringBuffer error = new StringBuffer(errorExpected); int start = errorExpected.indexOf("{0}"); if (start >= 0) { @@ -128,6 +143,7 @@ public class NativeErrors { f = new File(path); if (!f.exists()) throw new RuntimeException("Cannot find native2ascii at "+path); + System.out.println("Using native2ascii at "+path); } return path; } diff --git a/jdk/test/sun/tools/native2ascii/test2 b/jdk/test/sun/tools/native2ascii/test2 deleted file mode 100644 index 9a669e9ced5..00000000000 --- a/jdk/test/sun/tools/native2ascii/test2 +++ /dev/null @@ -1 +0,0 @@ -This file exists as a non-writable placeholder for NativeErrors.java From f1fd7e28fe627b3b88bcca01737b71bd60f0aed9 Mon Sep 17 00:00:00 2001 From: Keith Randall Date: Wed, 18 Nov 2009 11:12:28 -0800 Subject: [PATCH 12/56] 6892742: Improve root set used by jhat Reviewed-by: tbell, dcubed --- .../classes/com/sun/tools/hat/internal/model/JavaStatic.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaStatic.java b/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaStatic.java index 36f4e0e228d..86064914ea6 100644 --- a/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaStatic.java +++ b/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaStatic.java @@ -57,7 +57,10 @@ public class JavaStatic { id = ((JavaObjectRef)value).getId(); } value = value.dereference(snapshot, field); - if (value.isHeapAllocated()) { + if (value.isHeapAllocated() && + clazz.getLoader() == snapshot.getNullThing()) { + // static fields are only roots if they are in classes + // loaded by the root classloader. JavaHeapObject ho = (JavaHeapObject) value; String s = "Static reference from " + clazz.getName() + "." + field.getName(); From 8d62fe076c12c0ee824cf4cfb5ab3cdbd1d1d8bd Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Wed, 18 Nov 2009 22:29:16 -0800 Subject: [PATCH 13/56] 6902678: com.sun.tracing.ProviderFactory.createProvider doesn't throw IllegalArgumentException DoPrivileged for calls that have permission check instead of catching all exceptions Reviewed-by: kamg, dcubed --- .../com/sun/tracing/ProviderFactory.java | 46 +++--- .../sun/tracing/MultiplexProviderFactory.java | 9 +- .../sun/tracing/NullProviderFactory.java | 9 +- .../tracing/PrintStreamProviderFactory.java | 9 +- .../classes/sun/tracing/ProviderSkeleton.java | 10 +- .../tracing/dtrace/DTraceProviderFactory.java | 12 +- .../com/sun/tracing/BasicWithSecurityMgr.java | 149 ++++++++++++++++++ 7 files changed, 188 insertions(+), 56 deletions(-) create mode 100644 jdk/test/com/sun/tracing/BasicWithSecurityMgr.java diff --git a/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java b/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java index 768a6bebb8d..1a4f064ff51 100644 --- a/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java +++ b/jdk/src/share/classes/com/sun/tracing/ProviderFactory.java @@ -4,7 +4,10 @@ package com.sun.tracing; import java.util.HashSet; import java.io.PrintStream; import java.lang.reflect.Field; -import java.util.logging.Logger; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import sun.security.action.GetPropertyAction; import sun.tracing.NullProviderFactory; import sun.tracing.PrintStreamProviderFactory; @@ -52,23 +55,17 @@ public abstract class ProviderFactory { HashSet factories = new HashSet(); // Try to instantiate a DTraceProviderFactory - String prop = null; - try { prop = System.getProperty("com.sun.tracing.dtrace"); } - catch (java.security.AccessControlException e) { - Logger.getAnonymousLogger().fine( - "Cannot access property com.sun.tracing.dtrace"); - } + String prop = AccessController.doPrivileged( + new GetPropertyAction("com.sun.tracing.dtrace")); + if ( (prop == null || !prop.equals("disable")) && DTraceProviderFactory.isSupported() ) { factories.add(new DTraceProviderFactory()); } // Try to instantiate an output stream factory - try { prop = System.getProperty("sun.tracing.stream"); } - catch (java.security.AccessControlException e) { - Logger.getAnonymousLogger().fine( - "Cannot access property sun.tracing.stream"); - } + prop = AccessController.doPrivileged( + new GetPropertyAction("sun.tracing.stream")); if (prop != null) { for (String spec : prop.split(",")) { PrintStream ps = getPrintStreamFromSpec(spec); @@ -89,22 +86,29 @@ public abstract class ProviderFactory { } } - private static PrintStream getPrintStreamFromSpec(String spec) { + private static PrintStream getPrintStreamFromSpec(final String spec) { try { // spec is in the form of ., where is // a fully specified class name, and is a static member // in that class. The must be a 'PrintStream' or subtype // in order to be used. - int fieldpos = spec.lastIndexOf('.'); - Class cls = Class.forName(spec.substring(0, fieldpos)); - Field f = cls.getField(spec.substring(fieldpos + 1)); - Class fieldType = f.getType(); + final int fieldpos = spec.lastIndexOf('.'); + final Class cls = Class.forName(spec.substring(0, fieldpos)); + + Field f = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Field run() throws NoSuchFieldException { + return cls.getField(spec.substring(fieldpos + 1)); + } + }); + return (PrintStream)f.get(null); - } catch (Exception e) { - Logger.getAnonymousLogger().warning( - "Could not parse sun.tracing.stream property: " + e); + } catch (ClassNotFoundException e) { + throw new AssertionError(e); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } catch (PrivilegedActionException e) { + throw new AssertionError(e); } - return null; } } diff --git a/jdk/src/share/classes/sun/tracing/MultiplexProviderFactory.java b/jdk/src/share/classes/sun/tracing/MultiplexProviderFactory.java index 6ede31ec158..14c27c76d86 100644 --- a/jdk/src/share/classes/sun/tracing/MultiplexProviderFactory.java +++ b/jdk/src/share/classes/sun/tracing/MultiplexProviderFactory.java @@ -30,7 +30,6 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; -import java.util.logging.Logger; import com.sun.tracing.ProviderFactory; import com.sun.tracing.Provider; @@ -65,13 +64,7 @@ public class MultiplexProviderFactory extends ProviderFactory { providers.add(factory.createProvider(cls)); } MultiplexProvider provider = new MultiplexProvider(cls, providers); - try { - provider.init(); - } catch (Exception e) { - // Probably a permission problem (can't get declared members) - Logger.getAnonymousLogger().warning( - "Could not initialize tracing provider: " + e.getMessage()); - } + provider.init(); return provider.newProxyInstance(); } } diff --git a/jdk/src/share/classes/sun/tracing/NullProviderFactory.java b/jdk/src/share/classes/sun/tracing/NullProviderFactory.java index f567acabb32..5416fe35e53 100644 --- a/jdk/src/share/classes/sun/tracing/NullProviderFactory.java +++ b/jdk/src/share/classes/sun/tracing/NullProviderFactory.java @@ -26,7 +26,6 @@ package sun.tracing; import java.lang.reflect.Method; -import java.util.logging.Logger; import com.sun.tracing.ProviderFactory; import com.sun.tracing.Provider; @@ -53,13 +52,7 @@ public class NullProviderFactory extends ProviderFactory { */ public T createProvider(Class cls) { NullProvider provider = new NullProvider(cls); - try { - provider.init(); - } catch (Exception e) { - // Probably a permission problem (can't get declared members) - Logger.getAnonymousLogger().warning( - "Could not initialize tracing provider: " + e.getMessage()); - } + provider.init(); return provider.newProxyInstance(); } } diff --git a/jdk/src/share/classes/sun/tracing/PrintStreamProviderFactory.java b/jdk/src/share/classes/sun/tracing/PrintStreamProviderFactory.java index 53013041653..cca6bb58df5 100644 --- a/jdk/src/share/classes/sun/tracing/PrintStreamProviderFactory.java +++ b/jdk/src/share/classes/sun/tracing/PrintStreamProviderFactory.java @@ -28,7 +28,6 @@ package sun.tracing; import java.lang.reflect.Method; import java.io.PrintStream; import java.util.HashMap; -import java.util.logging.Logger; import com.sun.tracing.ProviderFactory; import com.sun.tracing.Provider; @@ -54,13 +53,7 @@ public class PrintStreamProviderFactory extends ProviderFactory { public T createProvider(Class cls) { PrintStreamProvider provider = new PrintStreamProvider(cls, stream); - try { - provider.init(); - } catch (Exception e) { - // Probably a permission problem (can't get declared members) - Logger.getAnonymousLogger().warning( - "Could not initialize tracing provider: " + e.getMessage()); - } + provider.init(); return provider.newProxyInstance(); } } diff --git a/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java b/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java index 0178fe46ed8..dd7cbb1976a 100644 --- a/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java +++ b/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java @@ -32,6 +32,8 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.AnnotatedElement; import java.lang.annotation.Annotation; import java.util.HashMap; +import java.security.AccessController; +import java.security.PrivilegedAction; import com.sun.tracing.Provider; import com.sun.tracing.Probe; @@ -99,7 +101,13 @@ public abstract class ProviderSkeleton implements InvocationHandler, Provider { * It is up to the factory implementations to call this after construction. */ public void init() { - for (Method m : providerType.getDeclaredMethods()) { + Method[] methods = AccessController.doPrivileged(new PrivilegedAction() { + public Method[] run() { + return providerType.getDeclaredMethods(); + } + }); + + for (Method m : methods) { if ( m.getReturnType() != Void.TYPE ) { throw new IllegalArgumentException( "Return value of method is not void"); diff --git a/jdk/src/share/classes/sun/tracing/dtrace/DTraceProviderFactory.java b/jdk/src/share/classes/sun/tracing/dtrace/DTraceProviderFactory.java index 3148f6f6db4..ce921d88eeb 100644 --- a/jdk/src/share/classes/sun/tracing/dtrace/DTraceProviderFactory.java +++ b/jdk/src/share/classes/sun/tracing/dtrace/DTraceProviderFactory.java @@ -29,7 +29,6 @@ import java.util.Map; import java.util.Set; import java.util.HashMap; import java.util.HashSet; -import java.util.logging.Logger; import java.security.Permission; import com.sun.tracing.ProviderFactory; @@ -80,15 +79,8 @@ public final class DTraceProviderFactory extends ProviderFactory { DTraceProvider jsdt = new DTraceProvider(cls); T proxy = jsdt.newProxyInstance(); jsdt.setProxy(proxy); - try { - jsdt.init(); - new Activation(jsdt.getModuleName(), new DTraceProvider[] { jsdt }); - } catch (Exception e) { - // Probably a permission problem (can't get declared members) - Logger.getAnonymousLogger().warning( - "Could not initialize tracing provider: " + e.getMessage()); - jsdt.dispose(); - } + jsdt.init(); + new Activation(jsdt.getModuleName(), new DTraceProvider[] { jsdt }); return proxy; } diff --git a/jdk/test/com/sun/tracing/BasicWithSecurityMgr.java b/jdk/test/com/sun/tracing/BasicWithSecurityMgr.java new file mode 100644 index 00000000000..547eb09445b --- /dev/null +++ b/jdk/test/com/sun/tracing/BasicWithSecurityMgr.java @@ -0,0 +1,149 @@ +/* + * Copyright 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. + * + * 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 6899605 + * @summary Basic unit test for tracing framework with security manager + * enabled + */ + +import com.sun.tracing.*; +import java.lang.reflect.Method; + +@ProviderName("NamedProvider") +interface BasicProvider extends Provider { + void plainProbe(); + void probeWithArgs(int a, float f, String s, Long l); + @ProbeName("namedProbe") void probeWithName(); + void overloadedProbe(); + void overloadedProbe(int i); +} + +interface InvalidProvider extends Provider { + int nonVoidProbe(); +} + +public class BasicWithSecurityMgr { + + public static ProviderFactory factory; + public static BasicProvider bp; + + public static void main(String[] args) throws Exception { + // enable security manager + System.setSecurityManager(new SecurityManager()); + + factory = ProviderFactory.getDefaultFactory(); + if (factory != null) { + bp = factory.createProvider(BasicProvider.class); + } + + testProviderFactory(); + testProbe(); + testProvider(); + } + + static void fail(String s) throws Exception { + throw new Exception(s); + } + + static void testProviderFactory() throws Exception { + if (factory == null) { + fail("ProviderFactory.getDefaultFactory: Did not create factory"); + } + if (bp == null) { + fail("ProviderFactory.createProvider: Did not create provider"); + } + try { + factory.createProvider(null); + fail("ProviderFactory.createProvider: Did not throw NPE for null"); + } catch (NullPointerException e) {} + + try { + factory.createProvider(InvalidProvider.class); + fail("Factory.createProvider: Should error with non-void probes"); + } catch (IllegalArgumentException e) {} + } + + public static void testProvider() throws Exception { + + // These just shouldn't throw any exeptions: + bp.plainProbe(); + bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L)); + bp.probeWithArgs(42, (float)3.14, null, null); + bp.probeWithName(); + bp.overloadedProbe(); + bp.overloadedProbe(42); + + Method m = BasicProvider.class.getMethod("plainProbe"); + Probe p = bp.getProbe(m); + if (p == null) { + fail("Provider.getProbe: Did not return probe"); + } + + Method m2 = BasicWithSecurityMgr.class.getMethod("testProvider"); + p = bp.getProbe(m2); + if (p != null) { + fail("Provider.getProbe: Got probe with invalid spec"); + } + + bp.dispose(); + // These just shouldn't throw any exeptions: + bp.plainProbe(); + bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L)); + bp.probeWithArgs(42, (float)3.14, null, null); + bp.probeWithName(); + bp.overloadedProbe(); + bp.overloadedProbe(42); + + if (bp.getProbe(m) != null) { + fail("Provider.getProbe: Should return null after dispose()"); + } + + bp.dispose(); // just to make sure nothing bad happens + } + + static void testProbe() throws Exception { + Method m = BasicProvider.class.getMethod("plainProbe"); + Probe p = bp.getProbe(m); + p.isEnabled(); // just make sure it doesn't do anything bad + p.trigger(); + + try { + p.trigger(0); + fail("Probe.trigger: too many arguments not caught"); + } catch (IllegalArgumentException e) {} + + p = bp.getProbe(BasicProvider.class.getMethod( + "probeWithArgs", int.class, float.class, String.class, Long.class)); + try { + p.trigger(); + fail("Probe.trigger: too few arguments not caught"); + } catch (IllegalArgumentException e) {} + + try { + p.trigger((float)3.14, (float)3.14, "", new Long(0L)); + fail("Probe.trigger: wrong type primitive arguments not caught"); + } catch (IllegalArgumentException e) {} + } +} From 4da1e67db39bcd15d729b116d6615827d527bbb6 Mon Sep 17 00:00:00 2001 From: Jean-Christophe Collet Date: Fri, 20 Nov 2009 14:50:55 +0100 Subject: [PATCH 14/56] 6901170: HttpCookie parsing of version and max-age mis-handled Accept single quotes in cookies and better exception handling in CookieManager Reviewed-by: chegar --- jdk/src/share/classes/java/net/CookieManager.java | 13 ++++++++++++- jdk/src/share/classes/java/net/HttpCookie.java | 11 +++++++---- jdk/test/java/net/CookieHandler/TestHttpCookie.java | 5 ++++- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/jdk/src/share/classes/java/net/CookieManager.java b/jdk/src/share/classes/java/net/CookieManager.java index 57038fcdbf2..986daeff337 100644 --- a/jdk/src/share/classes/java/net/CookieManager.java +++ b/jdk/src/share/classes/java/net/CookieManager.java @@ -30,6 +30,7 @@ import java.util.List; import java.util.Collections; import java.util.Comparator; import java.io.IOException; +import sun.util.logging.PlatformLogger; /** * CookieManager provides a concrete implementation of {@link CookieHandler}, @@ -263,6 +264,7 @@ public class CookieManager extends CookieHandler if (cookieJar == null) return; + PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager"); for (String headerKey : responseHeaders.keySet()) { // RFC 2965 3.2.2, key must be 'Set-Cookie2' // we also accept 'Set-Cookie' here for backward compatibility @@ -277,7 +279,16 @@ public class CookieManager extends CookieHandler for (String headerValue : responseHeaders.get(headerKey)) { try { - List cookies = HttpCookie.parse(headerValue); + List cookies; + try { + cookies = HttpCookie.parse(headerValue); + } catch (IllegalArgumentException e) { + // Bogus header, make an empty list and log the error + cookies = java.util.Collections.EMPTY_LIST; + if (logger.isLoggable(PlatformLogger.SEVERE)) { + logger.severe("Invalid cookie for " + uri + ": " + headerValue); + } + } for (HttpCookie cookie : cookies) { if (cookie.getPath() == null) { // If no path is specified, then by default diff --git a/jdk/src/share/classes/java/net/HttpCookie.java b/jdk/src/share/classes/java/net/HttpCookie.java index bd16d4f2723..be82cc3efbd 100644 --- a/jdk/src/share/classes/java/net/HttpCookie.java +++ b/jdk/src/share/classes/java/net/HttpCookie.java @@ -1036,7 +1036,7 @@ public final class HttpCookie implements Cloneable { int version = Integer.parseInt(attrValue); cookie.setVersion(version); } catch (NumberFormatException ignored) { - throw new IllegalArgumentException("Illegal cookie version attribute"); + // Just ignore bogus version, it will default to 0 or 1 } } }); @@ -1147,12 +1147,15 @@ public final class HttpCookie implements Cloneable { } private static String stripOffSurroundingQuote(String str) { - if (str != null && str.length() > 0 && + if (str != null && str.length() > 2 && str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') { return str.substring(1, str.length() - 1); - } else { - return str; } + if (str != null && str.length() > 2 && + str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'') { + return str.substring(1, str.length() - 1); + } + return str; } private static boolean equalsIgnoreCase(String s, String t) { diff --git a/jdk/test/java/net/CookieHandler/TestHttpCookie.java b/jdk/test/java/net/CookieHandler/TestHttpCookie.java index f1f89f8daab..df0dd74cdb7 100644 --- a/jdk/test/java/net/CookieHandler/TestHttpCookie.java +++ b/jdk/test/java/net/CookieHandler/TestHttpCookie.java @@ -24,7 +24,7 @@ /** * @test * @summary Unit test for java.net.HttpCookie - * @bug 6244040 6277796 6277801 6277808 6294071 6692802 6790677 + * @bug 6244040 6277796 6277801 6277808 6294071 6692802 6790677 6901170 * @author Edward Wang */ @@ -335,6 +335,9 @@ public class TestHttpCookie { // bug 6277801 test("set-cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT; path=\"/acme\"") .n("CUSTOMER").v("WILE_E_COYOTE").p("/").ver(0); + + // bug 6901170 + test("set-cookie: CUSTOMER=WILE_E_COYOTE; version='1'").ver(1); } static void misc() { From 117f4401d05e8debc4e68a41a2bebe22232abff8 Mon Sep 17 00:00:00 2001 From: Damjan Jovanovic Date: Fri, 20 Nov 2009 19:11:47 +0300 Subject: [PATCH 15/56] 6863566: Java should support the freedesktop.org startup notification specification The startup notification gets removed as soon as a Java top-level window is shown Reviewed-by: anthony, art, dcherepanov --- .../classes/sun/awt/X11/XWindowPeer.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java index 52e7a531188..b580bda3c8a 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java @@ -35,12 +35,19 @@ import java.awt.image.BufferedImage; import java.awt.peer.ComponentPeer; import java.awt.peer.WindowPeer; +import java.io.UnsupportedEncodingException; + +import java.security.AccessController; +import java.security.PrivilegedAction; + import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; +import java.util.concurrent.atomic.AtomicBoolean; + import sun.util.logging.PlatformLogger; import sun.awt.AWTAccessor; @@ -90,6 +97,8 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, private boolean mustControlStackPosition = false; // Am override-redirect not on top private XEventDispatcher rootPropertyEventDispatcher = null; + private static final AtomicBoolean isStartupNotificationRemoved = new AtomicBoolean(); + /* * Focus related flags */ @@ -1183,7 +1192,77 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, } } + private void removeStartupNotification() { + if (isStartupNotificationRemoved.getAndSet(true)) { + return; + } + + final String desktopStartupId = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return XToolkit.getEnv("DESKTOP_STARTUP_ID"); + } + }); + if (desktopStartupId == null) { + return; + } + + final StringBuilder messageBuilder = new StringBuilder("remove: ID="); + messageBuilder.append('"'); + for (int i = 0; i < desktopStartupId.length(); i++) { + if (desktopStartupId.charAt(i) == '"' || desktopStartupId.charAt(i) == '\\') { + messageBuilder.append('\\'); + } + messageBuilder.append(desktopStartupId.charAt(i)); + } + messageBuilder.append('"'); + messageBuilder.append('\0'); + final byte[] message; + try { + message = messageBuilder.toString().getBytes("UTF-8"); + } catch (UnsupportedEncodingException cannotHappen) { + return; + } + + XClientMessageEvent req = null; + + XToolkit.awtLock(); + try { + final XAtom netStartupInfoBeginAtom = XAtom.get("_NET_STARTUP_INFO_BEGIN"); + final XAtom netStartupInfoAtom = XAtom.get("_NET_STARTUP_INFO"); + + req = new XClientMessageEvent(); + req.set_type(XConstants.ClientMessage); + req.set_window(getWindow()); + req.set_message_type(netStartupInfoBeginAtom.getAtom()); + req.set_format(8); + + for (int pos = 0; pos < message.length; pos += 20) { + final int msglen = Math.min(message.length - pos, 20); + int i = 0; + for (; i < msglen; i++) { + XlibWrapper.unsafe.putByte(req.get_data() + i, message[pos + i]); + } + for (; i < 20; i++) { + XlibWrapper.unsafe.putByte(req.get_data() + i, (byte)0); + } + XlibWrapper.XSendEvent(XToolkit.getDisplay(), + XlibWrapper.RootWindow(XToolkit.getDisplay(), getScreenNumber()), + false, + XConstants.PropertyChangeMask, + req.pData); + req.set_message_type(netStartupInfoAtom.getAtom()); + } + } finally { + XToolkit.awtUnlock(); + if (req != null) { + req.dispose(); + } + } + } + public void handleMapNotifyEvent(XEvent xev) { + removeStartupNotification(); + // See 6480534. isUnhiding |= isWMStateNetHidden(); From 6a6d0a3c7ae65039a3b64f5cbdb6a0e762e3c518 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Fri, 27 Nov 2009 08:51:28 +0800 Subject: [PATCH 16/56] 6853328: Support OK-AS-DELEGATE flag Reviewed-by: valeriep --- .../sun/security/jgss/ExtendedGSSContext.java | 54 ++++++ .../classes/org/ietf/jgss/GSSContext.java | 12 +- .../protocol/http/spnego/NegotiatorImpl.java | 14 +- .../sun/security/jgss/GSSContextImpl.java | 39 +++-- .../sun/security/jgss/krb5/InitialToken.java | 56 ++++--- .../sun/security/jgss/krb5/Krb5Context.java | 20 +++ .../sun/security/jgss/spi/GSSContextSpi.java | 4 + .../security/jgss/spnego/SpNegoContext.java | 73 ++++---- .../jgss/wrapper/NativeGSSContext.java | 6 + .../sun/security/krb5/Credentials.java | 14 +- .../krb5/internal/CredentialsUtil.java | 15 +- jdk/test/sun/security/krb5/auto/Context.java | 15 +- jdk/test/sun/security/krb5/auto/KDC.java | 86 ++++++++-- .../sun/security/krb5/auto/OkAsDelegate.java | 104 ++++++++++++ .../krb5/auto/OkAsDelegateXRealm.java | 156 ++++++++++++++++++ .../krb5/auto/ok-as-delegate-xrealm.sh | 79 +++++++++ .../sun/security/krb5/auto/ok-as-delegate.sh | 118 +++++++++++++ 17 files changed, 766 insertions(+), 99 deletions(-) create mode 100644 jdk/test/sun/security/krb5/auto/OkAsDelegate.java create mode 100644 jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java create mode 100644 jdk/test/sun/security/krb5/auto/ok-as-delegate-xrealm.sh create mode 100644 jdk/test/sun/security/krb5/auto/ok-as-delegate.sh diff --git a/jdk/src/share/classes/com/sun/security/jgss/ExtendedGSSContext.java b/jdk/src/share/classes/com/sun/security/jgss/ExtendedGSSContext.java index dc7a3556d7d..1ac610d8880 100644 --- a/jdk/src/share/classes/com/sun/security/jgss/ExtendedGSSContext.java +++ b/jdk/src/share/classes/com/sun/security/jgss/ExtendedGSSContext.java @@ -99,4 +99,58 @@ public interface ExtendedGSSContext extends GSSContext { */ public Object inquireSecContext(InquireType type) throws GSSException; + + /** + * Requests that the delegation policy be respected. When a true value is + * requested, the underlying context would use the delegation policy + * defined by the environment as a hint to determine whether credentials + * delegation should be performed. This request can only be made on the + * context initiator's side and it has to be done prior to the first + * call to initSecContext. + *

+ * When this flag is false, delegation will only be tried when the + * {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag} + * is true. + *

+ * When this flag is true but the + * {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag} + * is false, delegation will be only tried if the delegation policy permits + * delegation. + *

+ * When both this flag and the + * {@link GSSContext#requestCredDeleg(boolean) credentials delegation flag} + * are true, delegation will be always tried. However, if the delegation + * policy does not permit delegation, the value of + * {@link #getDelegPolicyState} will be false, even + * if delegation is performed successfully. + *

+ * In any case, if the delegation is not successful, the value returned + * by {@link GSSContext#getCredDelegState()} is false, and the value + * returned by {@link #getDelegPolicyState()} is also false. + *

+ * Not all mechanisms support delegation policy. Therefore, the + * application should check to see if the request was honored with the + * {@link #getDelegPolicyState() getDelegPolicyState} method. When + * delegation policy is not supported, requestDelegPolicy + * should return silently without throwing an exception. + *

+ * Note: for the Kerberos 5 mechanism, the delegation policy is expressed + * through the OK-AS-DELEGATE flag in the service ticket. When it's true, + * the KDC permits delegation to the target server. In a cross-realm + * environment, in order for delegation be permitted, all cross-realm TGTs + * on the authentication path must also have the OK-AS-DELAGATE flags set. + * @param state true if the policy should be respected + * @throws GSSException containing the following + * major error codes: + * {@link GSSException#FAILURE GSSException.FAILURE} + */ + public void requestDelegPolicy(boolean state) throws GSSException; + + /** + * Returns the delegation policy response. Called after a security context + * is established. This method can be only called on the initiator's side. + * See {@link ExtendedGSSContext#requestDelegPolicy}. + * @return the delegation policy response + */ + public boolean getDelegPolicyState(); } diff --git a/jdk/src/share/classes/org/ietf/jgss/GSSContext.java b/jdk/src/share/classes/org/ietf/jgss/GSSContext.java index 5fb769dc523..e8eb7027580 100644 --- a/jdk/src/share/classes/org/ietf/jgss/GSSContext.java +++ b/jdk/src/share/classes/org/ietf/jgss/GSSContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2001 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 @@ -678,7 +678,7 @@ public interface GSSContext { * are not definitive then the method will attempt to treat all * available bytes as part of the token.

* - * Other than the possible blocking behaviour described above, this + * Other than the possible blocking behavior described above, this * method is equivalent to the byte array based {@link #unwrap(byte[], * int, int, MessageProp) unwrap} method.

* @@ -826,7 +826,7 @@ public interface GSSContext { * are not definitive then the method will attempt to treat all * available bytes as part of the token.

* - * Other than the possible blocking behaviour described above, this + * Other than the possible blocking behavior described above, this * method is equivalent to the byte array based {@link #verifyMIC(byte[], * int, int, byte[], int, int, MessageProp) verifyMIC} method.

* @@ -917,7 +917,7 @@ public interface GSSContext { * getMutualAuthState} method.

* * @param state a boolean value indicating whether mutual - * authentication shouls be used or not. + * authentication should be used or not. * @see #getMutualAuthState() * * @throws GSSException containing the following @@ -928,7 +928,7 @@ public interface GSSContext { /** * Requests that replay detection be enabled for the - * per-message security services after context establishemnt. This + * per-message security services after context establishment. This * request can only be made on the context initiator's side and it has * to be done prior to the first call to * initSecContext. During context establishment replay @@ -958,7 +958,7 @@ public interface GSSContext { /** * Requests that sequence checking be enabled for the - * per-message security services after context establishemnt. This + * per-message security services after context establishment. This * request can only be made on the context initiator's side and it has * to be done prior to the first call to * initSecContext. During context establishment sequence diff --git a/jdk/src/share/classes/sun/net/www/protocol/http/spnego/NegotiatorImpl.java b/jdk/src/share/classes/sun/net/www/protocol/http/spnego/NegotiatorImpl.java index dd4a39bd875..af0c9726ad9 100644 --- a/jdk/src/share/classes/sun/net/www/protocol/http/spnego/NegotiatorImpl.java +++ b/jdk/src/share/classes/sun/net/www/protocol/http/spnego/NegotiatorImpl.java @@ -25,6 +25,7 @@ package sun.net.www.protocol.http.spnego; +import com.sun.security.jgss.ExtendedGSSContext; import java.io.IOException; import org.ietf.jgss.GSSContext; @@ -100,15 +101,10 @@ public class NegotiatorImpl extends Negotiator { null, GSSContext.DEFAULT_LIFETIME); - // In order to support credential delegation in HTTP/SPNEGO, - // we always request it before initSecContext. The current - // implementation will check the OK-AS-DELEGATE flag inside - // the service ticket of the web server, and only enable - // delegation when this flag is set. This check is only - // performed when the GSS caller is CALLER_HTTP_NEGOTIATE, - // so all other normal GSS-API calls are not affected. - - context.requestCredDeleg(true); + // Always respect delegation policy in HTTP/SPNEGO. + if (context instanceof ExtendedGSSContext) { + ((ExtendedGSSContext)context).requestDelegPolicy(true); + } oneToken = context.initSecContext(new byte[0], 0, 0); } diff --git a/jdk/src/share/classes/sun/security/jgss/GSSContextImpl.java b/jdk/src/share/classes/sun/security/jgss/GSSContextImpl.java index de703ef4ded..210ba5b869a 100644 --- a/jdk/src/share/classes/sun/security/jgss/GSSContextImpl.java +++ b/jdk/src/share/classes/sun/security/jgss/GSSContextImpl.java @@ -89,7 +89,8 @@ import com.sun.security.jgss.*; */ class GSSContextImpl implements ExtendedGSSContext { - private GSSManagerImpl gssManager = null; + private final GSSManagerImpl gssManager; + private final boolean initiator; // private flags for the context state private static final int PRE_INIT = 1; @@ -99,14 +100,12 @@ class GSSContextImpl implements ExtendedGSSContext { // instance variables private int currentState = PRE_INIT; - private boolean initiator; private GSSContextSpi mechCtxt = null; private Oid mechOid = null; private ObjectIdentifier objId = null; private GSSCredentialImpl myCred = null; - private GSSCredentialImpl delegCred = null; private GSSNameImpl srcName = null; private GSSNameImpl targName = null; @@ -121,6 +120,7 @@ class GSSContextImpl implements ExtendedGSSContext { private boolean reqSequenceDetState = true; private boolean reqCredDelegState = false; private boolean reqAnonState = false; + private boolean reqDelegPolicyState = false; /** * Creates a GSSContextImp on the context initiator's side. @@ -221,6 +221,7 @@ class GSSContextImpl implements ExtendedGSSContext { mechCtxt.requestSequenceDet(reqSequenceDetState); mechCtxt.requestAnonymity(reqAnonState); mechCtxt.setChannelBinding(channelBindings); + mechCtxt.requestDelegPolicy(reqDelegPolicyState); objId = new ObjectIdentifier(mechOid.toString()); @@ -465,42 +466,42 @@ class GSSContextImpl implements ExtendedGSSContext { } public void requestMutualAuth(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqMutualAuthState = state; } public void requestReplayDet(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqReplayDetState = state; } public void requestSequenceDet(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqSequenceDetState = state; } public void requestCredDeleg(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqCredDelegState = state; } public void requestAnonymity(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqAnonState = state; } public void requestConf(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqConfState = state; } public void requestInteg(boolean state) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqIntegState = state; } public void requestLifetime(int lifetime) throws GSSException { - if (mechCtxt == null) + if (mechCtxt == null && initiator) reqLifetime = lifetime; } @@ -630,6 +631,8 @@ class GSSContextImpl implements ExtendedGSSContext { targName = null; } + // ExtendedGSSContext methods: + @Override public Object inquireSecContext(InquireType type) throws GSSException { SecurityManager security = System.getSecurityManager(); @@ -641,4 +644,18 @@ class GSSContextImpl implements ExtendedGSSContext { } return mechCtxt.inquireSecContext(type); } + + @Override + public void requestDelegPolicy(boolean state) throws GSSException { + if (mechCtxt == null && initiator) + reqDelegPolicyState = state; + } + + @Override + public boolean getDelegPolicyState() { + if (mechCtxt != null) + return mechCtxt.getDelegPolicyState(); + else + return reqDelegPolicyState; + } } diff --git a/jdk/src/share/classes/sun/security/jgss/krb5/InitialToken.java b/jdk/src/share/classes/sun/security/jgss/krb5/InitialToken.java index 2f0b834c1b9..ed7eb8c6e18 100644 --- a/jdk/src/share/classes/sun/security/jgss/krb5/InitialToken.java +++ b/jdk/src/share/classes/sun/security/jgss/krb5/InitialToken.java @@ -85,32 +85,39 @@ abstract class InitialToken extends Krb5Token { int size = CHECKSUM_LENGTH_SIZE + CHECKSUM_BINDINGS_SIZE + CHECKSUM_FLAGS_SIZE; - if (context.getCredDelegState()) { - if (context.getCaller() instanceof HttpCaller && - !serviceTicket.getFlags()[Krb5.TKT_OPTS_DELEGATE]) { - // When the caller is HTTP/SPNEGO and OK-AS-DELEGATE - // is not present in the service ticket, delegation - // is disabled. - context.setCredDelegState(false); - } else if (!tgt.isForwardable()) { - // XXX log this resetting of delegation state - context.setCredDelegState(false); - } else { - KrbCred krbCred = null; - CipherHelper cipherHelper = - context.getCipherHelper(serviceTicket.getSessionKey()); - if (useNullKey(cipherHelper)) { - krbCred = new KrbCred(tgt, serviceTicket, - EncryptionKey.NULL_KEY); - } else { - krbCred = new KrbCred(tgt, serviceTicket, - serviceTicket.getSessionKey()); + if (!tgt.isForwardable()) { + context.setCredDelegState(false); + context.setDelegPolicyState(false); + } else if (context.getCredDelegState()) { + if (context.getDelegPolicyState()) { + if (!serviceTicket.checkDelegate()) { + // delegation not permitted by server policy, mark it + context.setDelegPolicyState(false); } - krbCredMessage = krbCred.getMessage(); - size += CHECKSUM_DELEG_OPT_SIZE + - CHECKSUM_DELEG_LGTH_SIZE + - krbCredMessage.length; } + } else if (context.getDelegPolicyState()) { + if (serviceTicket.checkDelegate()) { + context.setCredDelegState(true); + } else { + context.setDelegPolicyState(false); + } + } + + if (context.getCredDelegState()) { + KrbCred krbCred = null; + CipherHelper cipherHelper = + context.getCipherHelper(serviceTicket.getSessionKey()); + if (useNullKey(cipherHelper)) { + krbCred = new KrbCred(tgt, serviceTicket, + EncryptionKey.NULL_KEY); + } else { + krbCred = new KrbCred(tgt, serviceTicket, + serviceTicket.getSessionKey()); + } + krbCredMessage = krbCred.getMessage(); + size += CHECKSUM_DELEG_OPT_SIZE + + CHECKSUM_DELEG_LGTH_SIZE + + krbCredMessage.length; } checksumBytes = new byte[size]; @@ -296,6 +303,7 @@ abstract class InitialToken extends Krb5Token { return delegCreds; } + // Only called by acceptor public void setContextFlags(Krb5Context context) { // default for cred delegation is false if ((flags & CHECKSUM_DELEG_FLAG) > 0) diff --git a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java index 4fe1e80f5f9..8810ed606f9 100644 --- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java +++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java @@ -78,6 +78,7 @@ class Krb5Context implements GSSContextSpi { private boolean sequenceDetState = true; private boolean confState = true; private boolean integState = true; + private boolean delegPolicyState = false; private int mySeqNumber; private int peerSeqNumber; @@ -299,6 +300,21 @@ class Krb5Context implements GSSContextSpi { return sequenceDetState || replayDetState; } + /** + * Requests that the deleg policy be respected. + */ + public final void requestDelegPolicy(boolean value) { + if (state == STATE_NEW && isInitiator()) + delegPolicyState = value; + } + + /** + * Is deleg policy respected? + */ + public final boolean getDelegPolicyState() { + return delegPolicyState; + } + /* * Anonymity is a little different in that after an application * requests anonymity it will want to know whether the mechanism @@ -422,6 +438,10 @@ class Krb5Context implements GSSContextSpi { integState = state; } + final void setDelegPolicyState(boolean state) { + delegPolicyState = state; + } + /** * Sets the channel bindings to be used during context * establishment. diff --git a/jdk/src/share/classes/sun/security/jgss/spi/GSSContextSpi.java b/jdk/src/share/classes/sun/security/jgss/spi/GSSContextSpi.java index 5bf359a1f8c..aaf4eebc29f 100644 --- a/jdk/src/share/classes/sun/security/jgss/spi/GSSContextSpi.java +++ b/jdk/src/share/classes/sun/security/jgss/spi/GSSContextSpi.java @@ -124,6 +124,8 @@ public interface GSSContextSpi { public void requestInteg(boolean state) throws GSSException; + public void requestDelegPolicy(boolean state) throws GSSException; + public void setChannelBinding(ChannelBinding cb) throws GSSException; public boolean getCredDelegState(); @@ -136,6 +138,8 @@ public interface GSSContextSpi { public boolean getAnonymityState(); + public boolean getDelegPolicyState(); + public boolean isTransferable() throws GSSException; public boolean isProtReady(); diff --git a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java index a436092f1bb..7fbff5ef475 100644 --- a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java +++ b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java @@ -63,6 +63,7 @@ public class SpNegoContext implements GSSContextSpi { private boolean sequenceDetState = true; private boolean confState = true; private boolean integState = true; + private boolean delegPolicyState = false; private GSSNameSpi peerName = null; private GSSNameSpi myName = null; @@ -153,6 +154,14 @@ public class SpNegoContext implements GSSContextSpi { integState = value; } + /** + * Requests that deleg policy be respected. + */ + public final void requestDelegPolicy(boolean value) throws GSSException { + if (state == STATE_NEW && isInitiator()) + delegPolicyState = value; + } + /** * Is integrity available? */ @@ -160,6 +169,19 @@ public class SpNegoContext implements GSSContextSpi { return integState; } + /** + * Is deleg policy respected? + */ + public final boolean getDelegPolicyState() { + if (isInitiator() && mechContext != null && + mechContext instanceof ExtendedGSSContext && + (state == STATE_IN_PROCESS || state == STATE_DONE)) { + return ((ExtendedGSSContext)mechContext).getDelegPolicyState(); + } else { + return delegPolicyState; + } + } + /** * Requests that credential delegation be done during context * establishment. @@ -173,7 +195,7 @@ public class SpNegoContext implements GSSContextSpi { * Is credential delegation enabled? */ public final boolean getCredDelegState() { - if (mechContext != null && + if (isInitiator() && mechContext != null && (state == STATE_IN_PROCESS || state == STATE_DONE)) { return mechContext.getCredDelegState(); } else { @@ -201,30 +223,6 @@ public class SpNegoContext implements GSSContextSpi { return mutualAuthState; } - final void setCredDelegState(boolean state) { - credDelegState = state; - } - - final void setMutualAuthState(boolean state) { - mutualAuthState = state; - } - - final void setReplayDetState(boolean state) { - replayDetState = state; - } - - final void setSequenceDetState(boolean state) { - sequenceDetState = state; - } - - final void setConfState(boolean state) { - confState = state; - } - - final void setIntegState(boolean state) { - integState = state; - } - /** * Returns the mechanism oid. * @@ -653,6 +651,10 @@ public class SpNegoContext implements GSSContextSpi { throw gssException; } + if (state == STATE_DONE) { + // now set the context flags for acceptor + setContextFlags(); + } return retVal; } @@ -703,28 +705,31 @@ public class SpNegoContext implements GSSContextSpi { return out; } + // Only called on acceptor side. On the initiator side, most flags + // are already set at request. For those that might get chanegd, + // state from mech below is used. private void setContextFlags() { if (mechContext != null) { // default for cred delegation is false if (mechContext.getCredDelegState()) { - setCredDelegState(true); + credDelegState = true; } // default for the following are true if (!mechContext.getMutualAuthState()) { - setMutualAuthState(false); + mutualAuthState = false; } if (!mechContext.getReplayDetState()) { - setReplayDetState(false); + replayDetState = false; } if (!mechContext.getSequenceDetState()) { - setSequenceDetState(false); + sequenceDetState = false; } if (!mechContext.getIntegState()) { - setIntegState(false); + integState = false; } if (!mechContext.getConfState()) { - setConfState(false); + confState = false; } } } @@ -837,6 +842,10 @@ public class SpNegoContext implements GSSContextSpi { mechContext.requestMutualAuth(mutualAuthState); mechContext.requestReplayDet(replayDetState); mechContext.requestSequenceDet(sequenceDetState); + if (mechContext instanceof ExtendedGSSContext) { + ((ExtendedGSSContext)mechContext).requestDelegPolicy( + delegPolicyState); + } } // pass token @@ -1202,5 +1211,5 @@ public class SpNegoContext implements GSSContextSpi { "inquireSecContext not supported by underlying mech."); } } - } + diff --git a/jdk/src/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java b/jdk/src/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java index 5b2a670b054..dc8c2bfafa9 100644 --- a/jdk/src/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java +++ b/jdk/src/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java @@ -549,6 +549,9 @@ class NativeGSSContext implements GSSContextSpi { public void requestInteg(boolean state) throws GSSException { changeFlags(GSS_C_INTEG_FLAG, state); } + public void requestDelegPolicy(boolean state) throws GSSException { + // Not supported, ignore + } public void requestLifetime(int lifetime) throws GSSException { if (isInitiator && pContext == 0) { this.lifetime = lifetime; @@ -590,6 +593,9 @@ class NativeGSSContext implements GSSContextSpi { public boolean getIntegState() { return checkFlags(GSS_C_INTEG_FLAG); } + public boolean getDelegPolicyState() { + return false; + } public int getLifetime() { return cStub.getContextTime(pContext); } diff --git a/jdk/src/share/classes/sun/security/krb5/Credentials.java b/jdk/src/share/classes/sun/security/krb5/Credentials.java index c003a29fa64..e2f2f901097 100644 --- a/jdk/src/share/classes/sun/security/krb5/Credentials.java +++ b/jdk/src/share/classes/sun/security/krb5/Credentials.java @@ -234,7 +234,19 @@ public class Credentials { * @return true if OK-AS_DELEGATE flag is set, otherwise, return false. */ public boolean checkDelegate() { - return (flags.get(Krb5.TKT_OPTS_DELEGATE)); + return flags.get(Krb5.TKT_OPTS_DELEGATE); + } + + /** + * Reset TKT_OPTS_DELEGATE to false, called at credentials acquirement + * when one of the cross-realm TGTs does not have the OK-AS-DELEGATE + * flag set. This info must be preservable and restorable through + * the Krb5Util.credsToTicket/ticketToCreds() methods so that even if + * the service ticket is cached it still remembers the cross-realm + * authentication result. + */ + public void resetDelegate() { + flags.set(Krb5.TKT_OPTS_DELEGATE, false); } public Credentials renew() throws KrbException, IOException { diff --git a/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java b/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java index fd2c925c046..7286aebcc84 100644 --- a/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java +++ b/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2001-2004 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2001-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 @@ -117,6 +117,7 @@ rs. // Get a list of realms to traverse String[] realms = Realm.getRealmsList(localRealm, serviceRealm); + boolean okAsDelegate = true; if (realms == null || realms.length == 0) { @@ -194,6 +195,15 @@ rs. */ newTgtRealm = newTgt.getServer().getInstanceComponent(); + if (okAsDelegate && !newTgt.checkDelegate()) { + if (DEBUG) + { + System.out.println(">>> Credentials acquireServiceCreds: " + + "global OK-AS-DELEGATE turned off at " + + newTgt.getServer()); + } + okAsDelegate = false; + } if (DEBUG) { @@ -283,6 +293,9 @@ rs. System.out.println(">>> Credentials acquireServiceCreds: returning creds:"); Credentials.printDebug(theCreds); } + if (!okAsDelegate) { + theCreds.resetDelegate(); + } return theCreds; } throw new KrbApErrException(Krb5.KRB_AP_ERR_GEN_CRED, diff --git a/jdk/test/sun/security/krb5/auto/Context.java b/jdk/test/sun/security/krb5/auto/Context.java index 140623f8310..3187e99d87e 100644 --- a/jdk/test/sun/security/krb5/auto/Context.java +++ b/jdk/test/sun/security/krb5/auto/Context.java @@ -72,7 +72,7 @@ import com.sun.security.jgss.AuthorizationDataEntry; public class Context { private Subject s; - private GSSContext x; + private ExtendedGSSContext x; private boolean f; // context established? private String name; private GSSCredential cred; // see static method delegated(). @@ -147,8 +147,8 @@ public class Context { @Override public byte[] run(Context me, byte[] dummy) throws Exception { GSSManager m = GSSManager.getInstance(); - me.x = m.createContext( - target.indexOf('@') < 0 ? + me.x = (ExtendedGSSContext)m.createContext( + target.indexOf('@') < 0 ? m.createName(target, null) : m.createName(target, GSSName.NT_HOSTBASED_SERVICE), mech, @@ -170,7 +170,7 @@ public class Context { @Override public byte[] run(Context me, byte[] dummy) throws Exception { GSSManager m = GSSManager.getInstance(); - me.x = m.createContext(m.createCredential( + me.x = (ExtendedGSSContext)m.createContext(m.createCredential( null, GSSCredential.INDEFINITE_LIFETIME, mech, @@ -193,7 +193,7 @@ public class Context { * * @return the GSSContext object */ - public GSSContext x() { + public ExtendedGSSContext x() { return x; } @@ -255,6 +255,11 @@ public class Context { if (x.getSequenceDetState()) { sb.append("seq det, "); } + if (x instanceof ExtendedGSSContext) { + if (((ExtendedGSSContext)x).getDelegPolicyState()) { + sb.append("deleg policy, "); + } + } System.out.println("Context status of " + name + ": " + sb.toString()); System.out.println(x.getSrcName() + " -> " + x.getTargName()); } catch (Exception e) { diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java index 586d8b23e61..169094c779b 100644 --- a/jdk/test/sun/security/krb5/auto/KDC.java +++ b/jdk/test/sun/security/krb5/auto/KDC.java @@ -63,6 +63,14 @@ import sun.security.util.DerValue; * settings after calling a KDC method, call Config.refresh() to * make sure your changes are reflected in the Config object. * + * System properties recognized: + *

+ * Support policies: + * * Issues and TODOs: *
    *
  1. Generates krb5.conf to be used on another machine, currently the kdc is @@ -151,7 +159,7 @@ public class KDC { * A standalone KDC server. */ public static void main(String[] args) throws Exception { - KDC kdc = create("RABBIT.HOLE", "kdc.rabbit,hole", 0, false); + KDC kdc = create("RABBIT.HOLE", "kdc.rabbit.hole", 0, false); kdc.addPrincipal("dummy", "bogus".toCharArray()); kdc.addPrincipal("foo", "bar".toCharArray()); kdc.addPrincipalRandKey("krbtgt/RABBIT.HOLE"); @@ -426,14 +434,17 @@ public class KDC { * @throws sun.security.krb5.KrbException when the principal is not inside * the database. */ - private char[] getPassword(PrincipalName p) throws KrbException { + private char[] getPassword(PrincipalName p, boolean server) + throws KrbException { String pn = p.toString(); if (p.getRealmString() == null) { pn = pn + "@" + getRealm(); } char[] pass = passwords.get(pn); if (pass == null) { - throw new KrbException(Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN); + throw new KrbException(server? + Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN: + Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN); } return pass; } @@ -457,10 +468,12 @@ public class KDC { * Returns the key for a given principal of the given encryption type * @param p the principal * @param etype the encryption type + * @param server looking for a server principal? * @return the key * @throws sun.security.krb5.KrbException for unknown/unsupported etype */ - private EncryptionKey keyForUser(PrincipalName p, int etype) throws KrbException { + private EncryptionKey keyForUser(PrincipalName p, int etype, boolean server) + throws KrbException { try { // Do not call EncryptionKey.acquireSecretKeys(), otherwise // the krb5.conf config file would be loaded. @@ -469,22 +482,71 @@ public class KDC { Integer kvno = null; // For service whose password ending with a number, use it as kvno if (p.toString().indexOf('/') >= 0) { - char[] pass = getPassword(p); + char[] pass = getPassword(p, server); if (Character.isDigit(pass[pass.length-1])) { kvno = pass[pass.length-1] - '0'; } } return new EncryptionKey((byte[]) stringToKey.invoke( - null, getPassword(p), getSalt(p), null, etype), + null, getPassword(p, server), getSalt(p), null, etype), etype, kvno); } catch (InvocationTargetException ex) { KrbException ke = (KrbException)ex.getCause(); throw ke; + } catch (KrbException ke) { + throw ke; } catch (Exception e) { throw new RuntimeException(e); // should not happen } } + private Map policies = new HashMap(); + + public void setPolicy(String rule, String value) { + if (value == null) { + policies.remove(rule); + } else { + policies.put(rule, value); + } + } + /** + * If the provided client/server pair matches a rule + * + * A system property named test.kdc.policy.RULE will be consulted. + * If it's unset, returns false. If its value is "", any pair is + * matched. Otherwise, it should contains the server name matched. + * + * TODO: client name is not used currently. + * + * @param c client name + * @param s server name + * @param rule rule name + * @return if a match is found + */ + private boolean configMatch(String c, String s, String rule) { + String policy = policies.get(rule); + boolean result = false; + if (policy == null) { + result = false; + } else if (policy.length() == 0) { + result = true; + } else { + String[] names = policy.split("\\s+"); + for (String name: names) { + if (name.equals(s)) { + result = true; + break; + } + } + } + if (result) { + System.out.printf(">>>> Policy match result (%s vs %s on %s) %b\n", + c, s, rule, result); + } + return result; + } + + /** * Processes an incoming request and generates a response. * @param in the request @@ -530,7 +592,7 @@ public class KDC { tkt = apReq.ticket; etype = tkt.encPart.getEType(); tkt.sname.setRealm(tkt.realm); - EncryptionKey kkey = keyForUser(tkt.sname, etype); + EncryptionKey kkey = keyForUser(tkt.sname, etype, true); byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET); DerInputStream derIn = new DerInputStream(bb); DerValue der = derIn.getDerValue(); @@ -541,7 +603,7 @@ public class KDC { throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP); } } - EncryptionKey skey = keyForUser(body.sname, etype); + EncryptionKey skey = keyForUser(body.sname, etype, true); if (skey == null) { throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP); // TODO } @@ -581,6 +643,10 @@ public class KDC { if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) { bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true; } + + if (configMatch("", body.sname.getNameString(), "ok-as-delegate")) { + bFlags[Krb5.TKT_OPTS_DELEGATE] = true; + } bFlags[Krb5.TKT_OPTS_INITIAL] = true; TicketFlags tFlags = new TicketFlags(bFlags); @@ -671,8 +737,8 @@ public class KDC { eTypes = (int[])f.get(body); int eType = eTypes[0]; - EncryptionKey ckey = keyForUser(body.cname, eType); - EncryptionKey skey = keyForUser(body.sname, eType); + EncryptionKey ckey = keyForUser(body.cname, eType, false); + EncryptionKey skey = keyForUser(body.sname, eType, true); if (ckey == null) { throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP); } diff --git a/jdk/test/sun/security/krb5/auto/OkAsDelegate.java b/jdk/test/sun/security/krb5/auto/OkAsDelegate.java new file mode 100644 index 00000000000..fee677b536b --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/OkAsDelegate.java @@ -0,0 +1,104 @@ +/* + * 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 com.sun.security.jgss.ExtendedGSSContext; +import org.ietf.jgss.GSSCredential; +import org.ietf.jgss.GSSException; +import org.ietf.jgss.Oid; +import sun.security.jgss.GSSUtil; +import sun.security.krb5.Config; + +public class OkAsDelegate { + + public static void main(String[] args) + throws Exception { + OkAsDelegate ok = new OkAsDelegate(); + ok.go( + Boolean.valueOf(args[0]), // FORWARDABLE in krb5.conf on? + Boolean.valueOf(args[1]), // requestDelegState + Boolean.valueOf(args[2]), // requestDelegPolicyState + Boolean.valueOf(args[3]), // DelegState in response + Boolean.valueOf(args[4]), // DelegPolicyState in response + Boolean.valueOf(args[5]) // getDelegCred OK? + ); + } + + void go( + boolean forwardable, + boolean requestDelegState, + boolean requestDelegPolicyState, + boolean delegState, + boolean delegPolicyState, + boolean delegated + ) throws Exception { + OneKDC kdc = new OneKDC(null); + kdc.setPolicy("ok-as-delegate", + System.getProperty("test.kdc.policy.ok-as-delegate")); + kdc.writeJAASConf(); + if (!forwardable) { + // The default OneKDC always includes "forwardable = true" + // in krb5.conf, override it. + KDC.saveConfig(OneKDC.KRB5_CONF, kdc, + "default_keytab_name = " + OneKDC.KTAB); + Config.refresh(); + } + + Context c, s; + c = Context.fromJAAS("client"); + s = Context.fromJAAS("server"); + + Oid mech = GSSUtil.GSS_KRB5_MECH_OID; + if (System.getProperty("test.spnego") != null) { + mech = GSSUtil.GSS_SPNEGO_MECH_OID; + } + c.startAsClient(OneKDC.SERVER, mech); + ExtendedGSSContext cx = (ExtendedGSSContext)c.x(); + cx.requestCredDeleg(requestDelegState); + cx.requestDelegPolicy(requestDelegPolicyState); + s.startAsServer(mech); + ExtendedGSSContext sx = (ExtendedGSSContext)s.x(); + + Context.handshake(c, s); + + if (cx.getCredDelegState() != delegState) { + throw new Exception("Initiator cred state error"); + } + if (sx.getCredDelegState() != delegState) { + throw new Exception("Acceptor cred state error"); + } + if (cx.getDelegPolicyState() != delegPolicyState) { + throw new Exception("Initiator cred policy state error"); + } + + GSSCredential cred = null; + try { + cred = s.x().getDelegCred(); + } catch (GSSException e) { + // leave cred as null + } + + if (delegated != (cred != null)) { + throw new Exception("get cred error"); + } + } +} diff --git a/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java b/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java new file mode 100644 index 00000000000..54c181fc8f6 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/OkAsDelegateXRealm.java @@ -0,0 +1,156 @@ +/* + * 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 com.sun.security.jgss.ExtendedGSSContext; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.Security; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import org.ietf.jgss.GSSContext; +import org.ietf.jgss.GSSCredential; +import org.ietf.jgss.GSSException; +import org.ietf.jgss.GSSManager; +import org.ietf.jgss.GSSName; +import sun.security.jgss.GSSUtil; +import sun.security.krb5.Config; + +public class OkAsDelegateXRealm implements CallbackHandler { + + /** + * @param args boolean if the program should succeed + */ + public static void main(String[] args) + throws Exception { + + // Create and start the KDCs. Here we have 3 realms: R1, R2 and R3. + // R1 is trusted by R2, and R2 trusted by R3. + KDC kdc1 = KDC.create("R1"); + kdc1.setPolicy("ok-as-delegate", + System.getProperty("test.kdc.policy.ok-as-delegate")); + kdc1.addPrincipal("dummy", "bogus".toCharArray()); + kdc1.addPrincipalRandKey("krbtgt/R1"); + kdc1.addPrincipal("krbtgt/R2@R1", "r1->r2".toCharArray()); + + KDC kdc2 = KDC.create("R2"); + kdc2.setPolicy("ok-as-delegate", + System.getProperty("test.kdc.policy.ok-as-delegate")); + kdc2.addPrincipalRandKey("krbtgt/R2"); + kdc2.addPrincipal("krbtgt/R2@R1", "r1->r2".toCharArray()); + kdc2.addPrincipal("krbtgt/R3@R2", "r2->r3".toCharArray()); + + KDC kdc3 = KDC.create("R3"); + kdc3.setPolicy("ok-as-delegate", + System.getProperty("test.kdc.policy.ok-as-delegate")); + kdc3.addPrincipalRandKey("krbtgt/R3"); + kdc3.addPrincipal("krbtgt/R3@R2", "r2->r3".toCharArray()); + kdc3.addPrincipalRandKey("host/host.r3.local"); + + KDC.saveConfig("krb5-localkdc.conf", kdc1, kdc2, kdc3, + "forwardable=true", + "[capaths]", + "R1 = {", + " R2 = .", + " R3 = R2", + "}", + "[domain_realm]", + ".r3.local=R3" + ); + + System.setProperty("java.security.krb5.conf", "krb5-localkdc.conf"); + kdc3.writeKtab("localkdc.ktab"); + + FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf"); + + // Defines the client and server on R1 and R3 respectively. + fos.write(("com.sun.security.jgss.krb5.initiate {\n" + + " com.sun.security.auth.module.Krb5LoginModule\n" + + " required\n" + + " principal=dummy\n" + + " doNotPrompt=false\n" + + " useTicketCache=false\n" + + " ;\n};\n" + + "com.sun.security.jgss.krb5.accept {\n" + + " com.sun.security.auth.module.Krb5LoginModule required\n" + + " principal=\"host/host.r3.local@R3\"\n" + + " useKeyTab=true\n" + + " keyTab=localkdc.ktab\n" + + " isInitiator=false\n" + + " storeKey=true;\n};\n" + + "\n").getBytes()); + fos.close(); + + Security.setProperty("auth.login.defaultCallbackHandler", + "OkAsDelegateXRealm"); + + System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf"); + + new File("krb5-localkdc.conf").deleteOnExit(); + new File("localkdc.ktab").deleteOnExit(); + new File("jaas-localkdc.conf").deleteOnExit(); + Config.refresh(); + + Context c = Context.fromJAAS("com.sun.security.jgss.krb5.initiate"); + Context s = Context.fromJAAS("com.sun.security.jgss.krb5.accept"); + + // Test twice. The frist time the whole cross realm process is tried, + // the second time the cached service ticket is used. This is to make sure + // the behaviors are the same, especailly for the case when one of the + // cross-realm TGTs does not have OK-AS-DELEGATE on. + + for (int i=0; i<2; i++) { + c.startAsClient("host@host.r3.local", GSSUtil.GSS_KRB5_MECH_OID); + s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID); + c.x().requestDelegPolicy(true); + + Context.handshake(c, s); + boolean succeed = true; + try { + s.x().getDelegCred(); + } catch (GSSException gsse) { + succeed = false; + } + if (succeed != Boolean.parseBoolean(args[0])) { + throw new Exception("Test fail at round #" + i); + } + } + } + + @Override + public void handle(Callback[] callbacks) + throws IOException, UnsupportedCallbackException { + for (Callback callback : callbacks) { + if (callback instanceof NameCallback) { + ((NameCallback) callback).setName("dummy"); + } + if (callback instanceof PasswordCallback) { + ((PasswordCallback) callback).setPassword("bogus".toCharArray()); + } + } + } +} + diff --git a/jdk/test/sun/security/krb5/auto/ok-as-delegate-xrealm.sh b/jdk/test/sun/security/krb5/auto/ok-as-delegate-xrealm.sh new file mode 100644 index 00000000000..850dae3e443 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/ok-as-delegate-xrealm.sh @@ -0,0 +1,79 @@ +# +# 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 6853328 +# @summary Support OK-AS-DELEGATE flag +# @run shell/timeout=600 ok-as-delegate-xrealm.sh +# + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC=`dirname $0` +fi + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + SEP=";" + ;; + CYGWIN* ) + FS="/" + SEP=";" + ;; + * ) + FS="/" + SEP=":" + ;; +esac + +${TESTJAVA}${FS}bin${FS}javac -XDignore.symbol.file -d . \ + ${TESTSRC}${FS}OkAsDelegateXRealm.java \ + ${TESTSRC}${FS}KDC.java \ + ${TESTSRC}${FS}OneKDC.java \ + ${TESTSRC}${FS}Action.java \ + ${TESTSRC}${FS}Context.java \ + || exit 10 + +# Add $TESTSRC to classpath so that customized nameservice can be used +J="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}." + +# KDC no OK-AS-DELEGATE, fail +$J OkAsDelegateXRealm false || exit 1 + +# KDC set OK-AS-DELEGATE for all, succeed +$J -Dtest.kdc.policy.ok-as-delegate OkAsDelegateXRealm true || exit 2 + +# KDC set OK-AS-DELEGATE for host/host.r3.local only, fail +$J -Dtest.kdc.policy.ok-as-delegate=host/host.r3.local OkAsDelegateXRealm false || exit 3 + +# KDC set OK-AS-DELEGATE for all, succeed +$J "-Dtest.kdc.policy.ok-as-delegate=host/host.r3.local krbtgt/R2 krbtgt/R3" OkAsDelegateXRealm true || exit 4 + +exit 0 diff --git a/jdk/test/sun/security/krb5/auto/ok-as-delegate.sh b/jdk/test/sun/security/krb5/auto/ok-as-delegate.sh new file mode 100644 index 00000000000..1647e1561f5 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/ok-as-delegate.sh @@ -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 +# @bug 6853328 +# @summary Support OK-AS-DELEGATE flag +# @run shell/timeout=600 ok-as-delegate.sh +# + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC=`dirname $0` +fi + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + SEP=";" + ;; + CYGWIN* ) + FS="/" + SEP=";" + ;; + * ) + FS="/" + SEP=":" + ;; +esac + +${TESTJAVA}${FS}bin${FS}javac -XDignore.symbol.file -d . \ + ${TESTSRC}${FS}OkAsDelegate.java \ + ${TESTSRC}${FS}KDC.java \ + ${TESTSRC}${FS}OneKDC.java \ + ${TESTSRC}${FS}Action.java \ + ${TESTSRC}${FS}Context.java \ + || exit 10 + +# Testing Kerberos 5 + +# Add $TESTSRC to classpath so that customized nameservice can be used +J="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}. OkAsDelegate" +JOK="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}. -Dtest.kdc.policy.ok-as-delegate OkAsDelegate" + +# FORWARDABLE ticket not allowed, always fail +$J false true true false false false || exit 1 + +# Service ticket no OK-AS-DELEGATE + +# Request nothing, gain nothing +$J true false false false false false || exit 2 +# Request deleg policy, gain nothing +$J true false true false false false || exit 3 +# Request deleg, granted +$J true true false true false true || exit 4 +# Request deleg and deleg policy, granted, with info not by policy +$J true true true true false true || exit 5 + +# Service ticket has OK-AS-DELEGATE + +# Request deleg policy, granted +$JOK true false true true true true || exit 6 +# Request deleg and deleg policy, granted, with info by policy +$JOK true true true true true true || exit 7 + +# Testing SPNEGO + +# Add $TESTSRC to classpath so that customized nameservice can be used +J="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}. -Dtest.spnego OkAsDelegate" +JOK="${TESTJAVA}${FS}bin${FS}java -cp $TESTSRC${SEP}. -Dtest.spnego -Dtest.kdc.policy.ok-as-delegate OkAsDelegate" + +# FORWARDABLE ticket not allowed, always fail +$J false true true false false false || exit 11 + +# Service ticket no OK-AS-DELEGATE + +# Request nothing, gain nothing +$J true false false false false false || exit 12 +# Request deleg policy, gain nothing +$J true false true false false false || exit 13 +# Request deleg, granted +$J true true false true false true || exit 14 +# Request deleg and deleg policy, granted, with info not by policy +$J true true true true false true || exit 15 + +# Service ticket has OK-AS-DELEGATE + +# Request deleg policy, granted +$JOK true false true true true true || exit 16 +# Request deleg and deleg policy, granted, with info by policy +$JOK true true true true true true || exit 17 + +exit 0 From 61fe319f78b36960f051c229f7493dfdd5c02ba2 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Fri, 27 Nov 2009 08:51:42 +0800 Subject: [PATCH 17/56] 6901085: SPNEGO does not works with native program Reviewed-by: valeriep --- .../security/jgss/spnego/SpNegoContext.java | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java index 7fbff5ef475..b002082d8cb 100644 --- a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java +++ b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoContext.java @@ -317,14 +317,9 @@ public class SpNegoContext implements GSSContextSpi { mechToken = GSS_initSecContext(null); errorCode = GSSException.DEFECTIVE_TOKEN; - byte[] micToken = null; - if (!GSSUtil.useMSInterop()) { - // calculate MIC only in normal mode - micToken = generateMechListMIC(DER_mechTypes); - } // generate SPNEGO token initToken = new NegTokenInit(DER_mechTypes, getContextFlags(), - mechToken, micToken); + mechToken, null); if (DEBUG) { System.out.println("SpNegoContext.initSecContext: " + "sending token of type = " + @@ -583,15 +578,9 @@ public class SpNegoContext implements GSSContextSpi { "negotiated result = " + negoResult); } - // calculate MIC only in normal mode - byte[] micToken = null; - if (!GSSUtil.useMSInterop() && valid) { - micToken = generateMechListMIC(DER_mechTypes); - } - // generate SPNEGO token NegTokenTarg targToken = new NegTokenTarg(negoResult.ordinal(), - mech_wanted, accept_token, micToken); + mech_wanted, accept_token, null); if (DEBUG) { System.out.println("SpNegoContext.acceptSecContext: " + "sending token of type = " + @@ -735,9 +724,9 @@ public class SpNegoContext implements GSSContextSpi { } /** - * generate MIC on mechList + * generate MIC on mechList. Not used at the moment. */ - private byte[] generateMechListMIC(byte[] mechTypes) + /*private byte[] generateMechListMIC(byte[] mechTypes) throws GSSException { // sanity check the required input @@ -774,7 +763,7 @@ public class SpNegoContext implements GSSContextSpi { } } return mic; - } + }*/ /** * verify MIC on MechList From 22d5c338dbc0d17989450fc33af5d0a8ddc6f425 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Fri, 27 Nov 2009 08:51:58 +0800 Subject: [PATCH 18/56] 6770883: Infinite loop if SPNEGO specified as sun.security.jgss.mechanism Reviewed-by: valeriep --- .../jgss/spnego/SpNegoMechFactory.java | 27 +++++++++--- .../jgss/spnego/NoSpnegoAsDefMech.java | 43 +++++++++++++++++++ 2 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 jdk/test/sun/security/jgss/spnego/NoSpnegoAsDefMech.java diff --git a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoMechFactory.java b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoMechFactory.java index ae12d6b3a78..72b77ac7166 100644 --- a/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoMechFactory.java +++ b/jdk/src/share/classes/sun/security/jgss/spnego/SpNegoMechFactory.java @@ -57,6 +57,12 @@ public final class SpNegoMechFactory implements MechanismFactory { GSSName.NT_HOSTBASED_SERVICE, GSSName.NT_EXPORT_NAME}; + // The default underlying mech of SPNEGO, must not be SPNEGO itself. + private static final Oid DEFAULT_SPNEGO_MECH_OID = + ProviderList.DEFAULT_MECH_OID.equals(GSS_SPNEGO_MECH_OID)? + GSSUtil.GSS_KRB5_MECH_OID: + ProviderList.DEFAULT_MECH_OID; + // Use an instance of a GSSManager whose provider list // does not include native provider final GSSManagerImpl manager; @@ -100,18 +106,27 @@ public final class SpNegoMechFactory implements MechanismFactory { availableMechs[j++] = mechs[i]; } } + // Move the preferred mech to first place + for (int i=0; i Date: Fri, 20 Nov 2009 11:01:32 -0800 Subject: [PATCH 19/56] 6367077: Purge LD_LIBRARY_PATH usage from the launcher 6899834: (launcher) remove the solaris libjvm.so symlink Fixes other related issues as well. Reviewed-by: darcy, ohair, xlu, martin --- jdk/make/java/jli/Makefile | 1 + jdk/make/java/main/java/Makefile | 3 - jdk/make/java/redist/Makefile | 2 - jdk/src/share/bin/java.c | 28 +- jdk/src/solaris/bin/java_md.c | 288 +++----------- jdk/test/tools/launcher/Arrrghs.java | 2 +- .../tools/launcher/ExecutionEnvironment.java | 358 ++++++++++++++++++ jdk/test/tools/launcher/SolarisDataModel.sh | 219 ----------- jdk/test/tools/launcher/SolarisRunpath.sh | 221 ----------- jdk/test/tools/launcher/TestHelper.java | 94 ++++- jdk/test/tools/launcher/libraryCaller.c | 56 --- jdk/test/tools/launcher/libraryCaller.h | 46 --- jdk/test/tools/launcher/libraryCaller.java | 46 --- 13 files changed, 504 insertions(+), 860 deletions(-) create mode 100644 jdk/test/tools/launcher/ExecutionEnvironment.java delete mode 100644 jdk/test/tools/launcher/SolarisDataModel.sh delete mode 100644 jdk/test/tools/launcher/SolarisRunpath.sh delete mode 100644 jdk/test/tools/launcher/libraryCaller.c delete mode 100644 jdk/test/tools/launcher/libraryCaller.h delete mode 100644 jdk/test/tools/launcher/libraryCaller.java diff --git a/jdk/make/java/jli/Makefile b/jdk/make/java/jli/Makefile index 861d5375e92..eeb64ca6e34 100644 --- a/jdk/make/java/jli/Makefile +++ b/jdk/make/java/jli/Makefile @@ -96,6 +96,7 @@ OTHER_CPPFLAGS += $(LIBARCH_DEFINES) ifneq ($(PLATFORM), windows) # UNIX systems + LD_RUNPATH_EXTRAS += .. LIB_LOCATION = $(LIBDIR)/$(LIBARCH)/jli # Note: its important to keep this order meaning -lc is the # last library otherwise it could cause compatibility issues diff --git a/jdk/make/java/main/java/Makefile b/jdk/make/java/main/java/Makefile index ae9ce618cdd..37fdf2bdd0f 100644 --- a/jdk/make/java/main/java/Makefile +++ b/jdk/make/java/main/java/Makefile @@ -61,8 +61,5 @@ OTHER_CPPFLAGS += -DLAUNCHER_NAME='"$(LAUNCHER_NAME)"' ifeq ($(PLATFORM), solaris) LDFLAGS += -R$(OPENWIN_LIB) -endif - -ifeq ($(PLATFORM), solaris) LDFLAGS += -M mapfile-$(ARCH) endif diff --git a/jdk/make/java/redist/Makefile b/jdk/make/java/redist/Makefile index b4ca64e5c14..69d95a60577 100644 --- a/jdk/make/java/redist/Makefile +++ b/jdk/make/java/redist/Makefile @@ -194,10 +194,8 @@ endif # For backwards compatability, make a link of the 32-bit client JVM to $(LIBDIR) IMPORT_LIST += $(LIB_LOCATION)/$(JVM_NAME) -# create a link from lib/libjvm.so to client/libjvm.so $(LIB_LOCATION)/$(JVM_NAME): $(LIB_LOCATION)/$(CLIENT_LOCATION)/$(JVM_NAME) @$(prep-target) - $(LN) -s $(CLIENT_LOCATION)/$(JVM_NAME) $@ # solaris ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ solaris endif # 32bit solaris diff --git a/jdk/src/share/bin/java.c b/jdk/src/share/bin/java.c index b8c0382b1d1..2494ce1ea2e 100644 --- a/jdk/src/share/bin/java.c +++ b/jdk/src/share/bin/java.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-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,15 +41,13 @@ * options are turned into "-foo" options to the vm. This option * filtering is handled in a number of places in the launcher, some of * it in machine-dependent code. In this file, the function - * CheckJVMType removes vm style options and TranslateApplicationArgs - * removes "-J" prefixes. On unix platforms, the - * CreateExecutionEnvironment function from the unix java_md.c file - * processes and removes -d options. However, in case - * CreateExecutionEnvironment does not need to exec because - * LD_LIBRARY_PATH is set acceptably and the data model does not need - * to be changed, ParseArguments will screen out the redundant -d - * options and prevent them from being passed to the vm; this is done - * by RemovableOption. + * CheckJvmType removes vm style options and TranslateApplicationArgs + * removes "-J" prefixes. The CreateExecutionEnvironment function processes + * and removes -d options. On unix, there is a possibility that the running + * data model may not match to the desired data model, in this case an exec is + * required to start the desired model. If the data models match, then + * ParseArguments will remove the -d flags. If the data models do not match + * the CreateExecutionEnviroment will remove the -d flags. */ @@ -1891,11 +1889,11 @@ DumpState() * Return JNI_TRUE for an option string that has no effect but should * _not_ be passed on to the vm; return JNI_FALSE otherwise. On * Solaris SPARC, this screening needs to be done if: - * 1) LD_LIBRARY_PATH does _not_ need to be reset and - * 2) -d32 or -d64 is passed to a binary with a matching data model - * (the exec in SetLibraryPath removes -d options and points the - * exec to the proper binary). When this exec is not done, these options - * would end up getting passed onto the vm. + * -d32 or -d64 is passed to a binary with an unmatched data model + * (the exec in CreateExecutionEnvironment removes -d options and points the + * exec to the proper binary). In the case of when the data model and the + * requested version is matched, an exec would not occur, and these options + * were erroneously passed to the vm. */ jboolean RemovableOption(char * option) diff --git a/jdk/src/solaris/bin/java_md.c b/jdk/src/solaris/bin/java_md.c index 73efc1090fd..7c68ed08316 100644 --- a/jdk/src/solaris/bin/java_md.c +++ b/jdk/src/solaris/bin/java_md.c @@ -1,5 +1,5 @@ /* - * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-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 @@ -51,9 +51,9 @@ * two data models and cohabitation of jre/jdk bits with both data * models is supported, then DUAL_MODE is defined. When DUAL_MODE is * defined, the architecture names for the narrow and wide version of - * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME. Currently - * only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; linux - * i586/amd64 could be defined as DUAL_MODE but that is not the + * the architecture are defined in LIBARCH64NAME and LIBARCH32NAME. + * Currently only Solaris on sparc/sparcv9 and i586/amd64 is DUAL_MODE; + * linux i586/amd64 could be defined as DUAL_MODE but that is not the * current policy. */ @@ -103,49 +103,56 @@ static char *execname = NULL; * platform independent routine SelectVersion. This may result in * the exec of the specified launcher version. * - * Typically, the launcher execs at least once to ensure a suitable - * LD_LIBRARY_PATH is in effect for the process. The first exec - * screens out all the data model options; leaving the choice of data - * model implicit in the binary selected to run. However, in case no - * exec is done, the data model options are screened out before the vm - * is invoked. + * Previously the launcher modified the LD_LIBRARY_PATH appropriately for the + * desired data model path, regardless if data models matched or not. The + * launcher subsequently exec'ed the desired executable, in order to make the + * LD_LIBRARY_PATH path available for the runtime linker. This is no longer the + * case, the launcher dlopens the target libjvm.so. All other required + * libraries are loaded by the runtime linker, by virtue of the $ORIGIN paths + * baked into the shared libraries, by the build infrastructure at compile time. * - * incoming argv ------------------------------ - * | | - * \|/ | - * CheckJVMType | - * (removes -client, -server, etc.) | - * \|/ - * CreateExecutionEnvironment - * (removes -d32 and -d64, - * determines desired data model, - * sets up LD_LIBRARY_PATH, - * and exec's) - * | - * -------------------------------------------- + * Main + * (incoming argv) * | * \|/ - * exec child 1 incoming argv ----------------- + * SelectVersion + * (selects the JRE version, note: not data model) + * | + * \|/ + * CreateExecutionEnvironment + * (determines desired data model) + * | + * | + * \|/ + * Have Desired Model ? --> NO --> Is Dual-Mode ? --> NO --> Exit(with error) + * | | * | | - * \|/ | - * CheckJVMType | - * (removes -client, -server, etc.) | * | \|/ - * | CreateExecutionEnvironment - * | (verifies desired data model - * | is running and acceptable - * | LD_LIBRARY_PATH; - * | no-op in child) + * | YES + * | | + * | | + * | \|/ + * | CheckJvmType + * | (removes -client, -server etc.) + * | | + * | | + * \|/ \|/ + * YES (find the desired executable and exec child) + * | | + * | | + * \|/ \|/ + * CheckJvmType Main + * (removes -client, -server, etc.) + * | * | * \|/ * TranslateDashJArgs... * (Prepare to pass args to vm) * | * | - * | * \|/ * ParseArguments - * (ignores -d32 and -d64, + * (removes -d32 and -d64 if any, * processes version options, * creates argument list for vm, * etc.) @@ -199,17 +206,13 @@ CreateExecutionEnvironment(int *_argcp, /* Compute/set the name of the executable */ SetExecname(*_argvp); - /* Set the LD_LIBRARY_PATH environment variable, check data model - flags, and exec process, if needed */ + /* Check data model flags, and exec process, if needed */ { char *arch = (char *)GetArch(); /* like sparc or sparcv9 */ char * jvmtype = NULL; int argc = *_argcp; char **argv = original_argv; - char *runpath = NULL; /* existing effective LD_LIBRARY_PATH - setting */ - int running = CURRENT_DATA_MODEL; int wanted = running; /* What data mode is being @@ -217,18 +220,8 @@ CreateExecutionEnvironment(int *_argcp, fine unless another model is asked for */ - char* new_runpath = NULL; /* desired new LD_LIBRARY_PATH string */ - char* newpath = NULL; /* path on new LD_LIBRARY_PATH */ - char* lastslash = NULL; - - char** newenvp = NULL; /* current environment */ - char** newargv = NULL; int newargc = 0; -#ifdef __solaris__ - char* dmpath = NULL; /* data model specific LD_LIBRARY_PATH, - Solaris only */ -#endif /* * Starting in 1.5, all unix platforms accept the -d32 and -d64 @@ -306,6 +299,11 @@ CreateExecutionEnvironment(int *_argcp, JLI_ReportErrorMessage(CFG_ERROR8, jvmtype, jvmpath); exit(4); } + /* + * we seem to have everything we need, so without further ado + * we return back. + */ + return; } else { /* do the same speculatively or exit */ #ifdef DUAL_MODE if (running != wanted) { @@ -335,190 +333,6 @@ CreateExecutionEnvironment(int *_argcp, #endif } - /* - * We will set the LD_LIBRARY_PATH as follows: - * - * o $JVMPATH (directory portion only) - * o $JRE/lib/$LIBARCHNAME - * o $JRE/../lib/$LIBARCHNAME - * - * followed by the user's previous effective LD_LIBRARY_PATH, if - * any. - */ - -#ifdef __solaris__ - /* - * Starting in Solaris 7, ld.so.1 supports three LD_LIBRARY_PATH - * variables: - * - * 1. LD_LIBRARY_PATH -- used for 32 and 64 bit searches if - * data-model specific variables are not set. - * - * 2. LD_LIBRARY_PATH_64 -- overrides and replaces LD_LIBRARY_PATH - * for 64-bit binaries. - * - * 3. LD_LIBRARY_PATH_32 -- overrides and replaces LD_LIBRARY_PATH - * for 32-bit binaries. - * - * The vm uses LD_LIBRARY_PATH to set the java.library.path system - * property. To shield the vm from the complication of multiple - * LD_LIBRARY_PATH variables, if the appropriate data model - * specific variable is set, we will act as if LD_LIBRARY_PATH had - * the value of the data model specific variant and the data model - * specific variant will be unset. Note that the variable for the - * *wanted* data model must be used (if it is set), not simply the - * current running data model. - */ - - switch(wanted) { - case 0: - if(running == 32) { - dmpath = getenv("LD_LIBRARY_PATH_32"); - wanted = 32; - } - else { - dmpath = getenv("LD_LIBRARY_PATH_64"); - wanted = 64; - } - break; - - case 32: - dmpath = getenv("LD_LIBRARY_PATH_32"); - break; - - case 64: - dmpath = getenv("LD_LIBRARY_PATH_64"); - break; - - default: - JLI_ReportErrorMessage(JRE_ERROR3, __LINE__); - exit(1); /* unknown value in wanted */ - break; - } - - /* - * If dmpath is NULL, the relevant data model specific variable is - * not set and normal LD_LIBRARY_PATH should be used. - */ - if( dmpath == NULL) { - runpath = getenv("LD_LIBRARY_PATH"); - } - else { - runpath = dmpath; - } -#else - /* - * If not on Solaris, assume only a single LD_LIBRARY_PATH - * variable. - */ - runpath = getenv("LD_LIBRARY_PATH"); -#endif /* __solaris__ */ - -#ifdef __linux - /* - * On linux, if a binary is running as sgid or suid, glibc sets - * LD_LIBRARY_PATH to the empty string for security purposes. (In - * contrast, on Solaris the LD_LIBRARY_PATH variable for a - * privileged binary does not lose its settings; but the dynamic - * linker does apply more scrutiny to the path.) The launcher uses - * the value of LD_LIBRARY_PATH to prevent an exec loop. - * Therefore, if we are running sgid or suid, this function's - * setting of LD_LIBRARY_PATH will be ineffective and we should - * return from the function now. Getting the right libraries to - * be found must be handled through other mechanisms. - */ - if((getgid() != getegid()) || (getuid() != geteuid()) ) { - return; - } -#endif - - /* runpath contains current effective LD_LIBRARY_PATH setting */ - - jvmpath = JLI_StringDup(jvmpath); - new_runpath = JLI_MemAlloc( ((runpath!=NULL)?JLI_StrLen(runpath):0) + - 2*JLI_StrLen(jrepath) + 2*JLI_StrLen(arch) + - JLI_StrLen(jvmpath) + 52); - newpath = new_runpath + JLI_StrLen("LD_LIBRARY_PATH="); - - - /* - * Create desired LD_LIBRARY_PATH value for target data model. - */ - { - /* remove the name of the .so from the JVM path */ - lastslash = JLI_StrRChr(jvmpath, '/'); - if (lastslash) - *lastslash = '\0'; - - - /* jvmpath, ((running != wanted)?((wanted==64)?"/"LIBARCH64NAME:"/.."):""), */ - - sprintf(new_runpath, "LD_LIBRARY_PATH=" - "%s:" - "%s/lib/%s:" - "%s/../lib/%s", - jvmpath, -#ifdef DUAL_MODE - jrepath, GetArchPath(wanted), - jrepath, GetArchPath(wanted) -#else - jrepath, arch, - jrepath, arch -#endif - ); - - - /* - * Check to make sure that the prefix of the current path is the - * desired environment variable setting. - */ - if (runpath != NULL && - JLI_StrNCmp(newpath, runpath, JLI_StrLen(newpath))==0 && - (runpath[JLI_StrLen(newpath)] == 0 || runpath[JLI_StrLen(newpath)] == ':') && - (running == wanted) /* data model does not have to be changed */ -#ifdef __solaris__ - && (dmpath == NULL) /* data model specific variables not set */ -#endif - ) { - - return; - - } - } - - /* - * Place the desired environment setting onto the prefix of - * LD_LIBRARY_PATH. Note that this prevents any possible infinite - * loop of execv() because we test for the prefix, above. - */ - if (runpath != 0) { - JLI_StrCat(new_runpath, ":"); - JLI_StrCat(new_runpath, runpath); - } - - if( putenv(new_runpath) != 0) { - exit(1); /* problem allocating memory; LD_LIBRARY_PATH not set - properly */ - } - - /* - * Unix systems document that they look at LD_LIBRARY_PATH only - * once at startup, so we have to re-exec the current executable - * to get the changed environment variable to have an effect. - */ - -#ifdef __solaris__ - /* - * If dmpath is not NULL, remove the data model specific string - * in the environment for the exec'ed child. - */ - - if( dmpath != NULL) - (void)UnsetEnv((wanted==32)?"LD_LIBRARY_PATH_32":"LD_LIBRARY_PATH_64"); -#endif - - newenvp = environ; - { char *newexec = execname; #ifdef DUAL_MODE @@ -549,17 +363,16 @@ CreateExecutionEnvironment(int *_argcp, argv[0] = newexec; } #endif - + JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n"); (void)fflush(stdout); (void)fflush(stderr); - execve(newexec, argv, newenvp); + execv(newexec, argv); JLI_ReportErrorMessageSys(JRE_ERROR4, newexec); #ifdef DUAL_MODE if (running != wanted) { JLI_ReportErrorMessage(JRE_ERROR5, wanted, running); # ifdef __solaris__ - # ifdef __sparc JLI_ReportErrorMessage(JRE_ERROR6); # else @@ -570,13 +383,11 @@ CreateExecutionEnvironment(int *_argcp, #endif } - exit(1); } } - /* * On Solaris VM choosing is done by the launcher (java.c). */ @@ -1123,6 +934,7 @@ ExecJRE(char *jre, char **argv) printf(" %s", argv[i]); printf("\n"); } + JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n"); (void)fflush(stdout); (void)fflush(stderr); execv(wanted, argv); diff --git a/jdk/test/tools/launcher/Arrrghs.java b/jdk/test/tools/launcher/Arrrghs.java index 4853b905166..b7ba2737dfa 100644 --- a/jdk/test/tools/launcher/Arrrghs.java +++ b/jdk/test/tools/launcher/Arrrghs.java @@ -25,7 +25,7 @@ * @test * @bug 5030233 6214916 6356475 6571029 6684582 6742159 4459600 6758881 * @summary Argument parsing validation. - * @compile Arrrghs.java TestHelper.java + * @compile -XDignore.symbol.file Arrrghs.java TestHelper.java * @run main Arrrghs */ diff --git a/jdk/test/tools/launcher/ExecutionEnvironment.java b/jdk/test/tools/launcher/ExecutionEnvironment.java new file mode 100644 index 00000000000..217de4670e0 --- /dev/null +++ b/jdk/test/tools/launcher/ExecutionEnvironment.java @@ -0,0 +1,358 @@ +/* + * 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 4780570 4731671 6354700 6367077 6670965 4882974 + * @summary Checks for LD_LIBRARY_PATH and execution on *nixes + * @compile -XDignore.symbol.file ExecutionEnvironment.java TestHelper.java + * @run main ExecutionEnvironment + */ + +/* + * This test tests for various things as follows: + * Ensures that: + * 1. uneccessary execs do not occur + * 2. the environment is pristine, users environment variable wrt. + * LD_LIBRARY_PATH if set are not modified in any way. + * 3. the correct vm is chosen with -server and -client options + * 4. the VM on Solaris correctly interprets the LD_LIBRARY_PATH32 + * and LD_LIBRARY_PATH64 variables if set by the user, ie. + * i. on 32 bit systems: + * a. if LD_LIBRARY_PATH32 is set it will override LD_LIBRARY_PATH + * b. LD_LIBRARY_PATH64 is ignored if set + * ii. on 64 bit systems: + * a. if LD_LIBRARY_PATH64 is set it will override LD_LIBRARY_PATH + * b. LD_LIBRARY_PATH32 is ignored if set + * 5. no extra symlink exists on Solaris ie. + * jre/lib/$arch/libjvm.so -> client/libjvm.so + * TODO: + * a. perhaps we need to add a test to audit all environment variables are + * in pristine condition after the launch, there may be a few that the + * launcher may add as implementation details. + * b. add a pldd for solaris to ensure only one libjvm.so is linked + */ +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class ExecutionEnvironment { + static final String LD_LIBRARY_PATH = "LD_LIBRARY_PATH"; + static final String LD_LIBRARY_PATH_32 = LD_LIBRARY_PATH + "_32"; + static final String LD_LIBRARY_PATH_64 = LD_LIBRARY_PATH + "_64"; + + // Note: these paths need not exist on the filesytem + static final String LD_LIBRARY_PATH_VALUE = "/Bridge/On/The/River/Kwai"; + static final String LD_LIBRARY_PATH_32_VALUE = "/Lawrence/Of/Arabia"; + static final String LD_LIBRARY_PATH_64_VALUE = "/A/Passage/To/India"; + + static final String JLDEBUG_KEY = "_JAVA_LAUNCHER_DEBUG"; + static final String EXPECTED_MARKER = "TRACER_MARKER:About to EXEC"; + + static final String[] LD_PATH_STRINGS = { + LD_LIBRARY_PATH + "=" + LD_LIBRARY_PATH_VALUE, + LD_LIBRARY_PATH_32 + "=" + LD_LIBRARY_PATH_32_VALUE, + LD_LIBRARY_PATH_64 + "=" + LD_LIBRARY_PATH_64_VALUE + }; + + static final File testJarFile = new File("EcoFriendly.jar"); + + static int errors = 0; + static int passes = 0; + + private static void createTestJar() { + try { + List codeList = new ArrayList(); + codeList.add("static void printValue(String name, boolean property) {\n"); + codeList.add(" String value = (property) ? System.getProperty(name) : System.getenv(name);\n"); + codeList.add(" System.out.println(name + \"=\" + value);\n"); + codeList.add("}\n"); + codeList.add("public static void main(String... args) {\n"); + codeList.add(" System.out.println(\"Execute test:\");\n"); + codeList.add(" printValue(\"os.name\", true);\n"); + codeList.add(" printValue(\"os.arch\", true);\n"); + codeList.add(" printValue(\"os.version\", true);\n"); + codeList.add(" printValue(\"sun.arch.data.model\", true);\n"); + codeList.add(" printValue(\"java.library.path\", true);\n"); + codeList.add(" printValue(\"" + LD_LIBRARY_PATH + "\", false);\n"); + codeList.add(" printValue(\"" + LD_LIBRARY_PATH_32 + "\", false);\n"); + codeList.add(" printValue(\"" + LD_LIBRARY_PATH_64 + "\", false);\n"); + codeList.add("}\n"); + String[] clist = new String[codeList.size()]; + TestHelper.createJar(testJarFile, codeList.toArray(clist)); + } catch (FileNotFoundException fnfe) { + throw new RuntimeException(fnfe); + } + } + + /* + * tests if the launcher pollutes the LD_LIBRARY_PATH variables ie. there + * should not be any new variables or pollution/mutations of any kind, the + * environment should be pristine. + */ + private static void ensureEcoFriendly() { + TestHelper.TestResult tr = null; + + Map env = new HashMap(); + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-jar", + testJarFile.getAbsolutePath()); + + if (!tr.isNotZeroOutput()) { + throw new RuntimeException("Error: No output at all. Did the test execute ?"); + } + + for (String x : LD_PATH_STRINGS) { + if (!tr.contains(x)) { + System.out.println("FAIL: did not get <" + x + ">"); + System.out.println(tr); + errors++; + } else { + passes++; + } + } + } + + /* + * ensures that there are no execs as long as we are in the same + * data model + */ + static void ensureNoExec() { + Map env = new HashMap(); + env.put(JLDEBUG_KEY, "true"); + TestHelper.TestResult tr = + TestHelper.doExec(env, TestHelper.javaCmd, "-version"); + if (tr.testOutput.contains(EXPECTED_MARKER)) { + System.out.println("FAIL: EnsureNoExecs: found expected warning <" + + EXPECTED_MARKER + + "> the process execing ?"); + errors++; + } else { + passes++; + } + return; + } + + /* + * This test ensures that LD_LIBRARY_PATH* values are interpreted by the VM + * and the expected java.library.path behaviour. + * For Generic platforms (All *nixes): + * * All LD_LIBRARY_PATH variable should be on java.library.path + * For Solaris 32-bit + * * The LD_LIBRARY_PATH_32 should override LD_LIBRARY_PATH if specified + * For Solaris 64-bit + * * The LD_LIBRARY_PATH_64 should override LD_LIBRARY_PATH if specified + */ + + static void verifyJavaLibraryPath() { + TestHelper.TestResult tr = null; + + Map env = new HashMap(); + + + if (TestHelper.isLinux) { + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathGeneric(tr); + } else { + // no override + env.clear(); + env.put(LD_LIBRARY_PATH, LD_LIBRARY_PATH_VALUE); + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathGeneric(tr); + + env.clear(); + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + + // verify the override occurs, since we know the invocation always + // uses by default is 32-bit, therefore we also set the test + // expectation to be the same. + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathOverride(tr, true); + + // try changing the model from 32 to 64 bit + if (TestHelper.java64Cmd != null && TestHelper.is32Bit) { + // verify the override occurs + env.clear(); + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-d64", "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathOverride(tr, false); + + // no override + env.clear(); + env.put(LD_LIBRARY_PATH, LD_LIBRARY_PATH_VALUE); + tr = TestHelper.doExec(env, TestHelper.javaCmd, "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathGeneric(tr); + } + + // try changing the model from 64 to 32 bit + if (TestHelper.java64Cmd != null && TestHelper.is64Bit) { + // verify the override occurs + env.clear(); + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + tr = TestHelper.doExec(env, TestHelper.java64Cmd, "-d32", "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathOverride(tr, true); + + // no override + env.clear(); + env.put(LD_LIBRARY_PATH, LD_LIBRARY_PATH_VALUE); + tr = TestHelper.doExec(env, TestHelper.java64Cmd, "-d32", "-jar", + testJarFile.getAbsolutePath()); + verifyJavaLibraryPathGeneric(tr); + } + } + } + + private static void verifyJavaLibraryPathGeneric(TestHelper.TestResult tr) { + if (!tr.matches("java.library.path=.*" + LD_LIBRARY_PATH_VALUE + ".*")) { + System.out.print("FAIL: verifyJavaLibraryPath: "); + System.out.println(" java.library.path does not contain " + + LD_LIBRARY_PATH_VALUE); + System.out.println(tr); + errors++; + } else { + passes++; + } + } + + private static void verifyJavaLibraryPathOverride(TestHelper.TestResult tr, + boolean is32Bit) { + // make sure the 32/64 bit value exists + if (!tr.matches("java.library.path=.*" + + (is32Bit ? LD_LIBRARY_PATH_32_VALUE : LD_LIBRARY_PATH_64_VALUE) + ".*")) { + System.out.print("FAIL: verifyJavaLibraryPathOverride: "); + System.out.println(" java.library.path does not contain " + + (is32Bit ? LD_LIBRARY_PATH_32_VALUE : LD_LIBRARY_PATH_64_VALUE)); + System.out.println(tr); + errors++; + } else { + passes++; + } + // make sure the generic value is absent + if (tr.matches("java.library.path=.*" + LD_LIBRARY_PATH_VALUE + ".*")) { + System.out.print("FAIL: verifyJavaLibraryPathOverride: "); + System.out.println(" java.library.path contains " + + LD_LIBRARY_PATH_VALUE); + System.out.println(tr); + errors++; + } else { + passes++; + } + } + + /* + * ensures we have indeed exec'ed the correct vm of choice, all VMs support + * -server, however 32-bit VMs support -client and -server. + */ + static void verifyVmSelection() { + + TestHelper.TestResult tr = null; + + if (TestHelper.is32Bit) { + tr = TestHelper.doExec(TestHelper.javaCmd, "-client", "-version"); + if (!tr.matches("Java.*Client VM.*")) { + System.out.println("FAIL: the expected vm -client did launch"); + System.out.println(tr); + errors++; + } else { + passes++; + } + } + tr = TestHelper.doExec(TestHelper.javaCmd, "-server", "-version"); + if (!tr.matches("Java.*Server VM.*")) { + System.out.println("FAIL: the expected vm -server did launch"); + System.out.println(tr); + errors++; + } else { + passes++; + } + } + + /* + * checks to see there is no extra libjvm.so than needed + */ + static void verifyNoSymLink() { + if (TestHelper.is64Bit) { + return; + } + + File symLink = null; + String libPathPrefix = TestHelper.isSDK ? "jre/lib" : "/lib"; + symLink = new File(TestHelper.JAVAHOME, libPathPrefix + + TestHelper.getJreArch() + "/libjvm.so"); + if (symLink.exists()) { + System.out.println("FAIL: The symlink exists " + + symLink.getAbsolutePath()); + errors++; + } else { + passes++; + } + } + + public static void main(String... args) throws Exception { + if (TestHelper.isWindows) { + System.out.println("Warning: noop on windows"); + return; + } + // create our test jar first + createTestJar(); + ensureNoExec(); + verifyVmSelection(); + ensureEcoFriendly(); + verifyJavaLibraryPath(); + verifyNoSymLink(); + if (errors > 0) { + throw new Exception("ExecutionEnvironment: FAIL: with " + + errors + " errors and passes " + passes ); + } else { + System.out.println("ExecutionEnvironment: PASS " + passes); + } + } +} diff --git a/jdk/test/tools/launcher/SolarisDataModel.sh b/jdk/test/tools/launcher/SolarisDataModel.sh deleted file mode 100644 index 36398d7fe39..00000000000 --- a/jdk/test/tools/launcher/SolarisDataModel.sh +++ /dev/null @@ -1,219 +0,0 @@ -# Copyright 2007 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 4780570 -# @run shell SolarisDataModel.sh -# @summary Verify Solaris SPARC -d32 and -d64 options work with preset LD_LIBRARY_PATH -# @author Joseph D. Darcy - -# Test to see if presetting LD_LIBRARY_PATH affects the treatment of -# -d32 and -d64 options; also checks that -d options result in the -# desired data model. - -# If the test is not being run on a Solaris SPARC box SPARC the test -# succeeds immediately. - -OS=`uname -s`; - -case "$OS" in - SunOS ) - # ARCH should be sparc or i386 - ARCH=`uname -p` - case "$ARCH" in - sparc) - PATHSEP=":" - ;; - - * ) - echo "Non-SPARC Solaris environment; test vacuously succeeds." - exit 0 - esac - ;; - - * ) - echo "Not a Solaris SPARC environment; test vacuously succeeds." - exit 0; - ;; -esac - - -# Verify directory context variables are set -if [ "${TESTJAVA}" = "" ] -then - echo "TESTJAVA not set. Test cannot execute. Failed." - exit 1 -fi - -if [ "${TESTSRC}" = "" ] -then - echo "TESTSRC not set. Test cannot execute. Failed." - exit 1 -fi - - -if [ "${TESTCLASSES}" = "" ] -then - echo "TESTCLASSES not set. Test cannot execute. Failed." - exit 1 -fi - - -JAVAC="$TESTJAVA/bin/javac" - -# Create our little Java tests on the fly -( printf "public class GetDataModel {" - printf " public static void main(String argv[]) {" - printf " System.out.println(System.getProperty(\"sun.arch.data.model\", \"none\"));" - printf " }" - printf "}" -) > GetDataModel.java - -$JAVAC GetDataModel.java - -( printf "public class GetLdLibraryPath {" - printf " public static void main(String argv[]) {" - printf " System.out.println(System.getProperty(\"java.library.path\"));" - printf " }" - printf "}" -) > GetLdLibraryPath.java - -$JAVAC GetLdLibraryPath.java - - - -# All preconditions are met; run the tests - - -# Construct path to 32-bit Java executable -JAVA="$TESTJAVA/bin/java -classpath $TESTCLASSES${PATHSEP}." - - -# Construct path to 64-bit Java executable, might not exist -JAVA64="$TESTJAVA/bin/sparcv9/java -classpath $TESTCLASSES${PATHSEP}." -JAVA64FILE="$TESTJAVA/bin/sparcv9/java" - - -# java -d32 tests - -LD_LIBRARY_PATH="" -export LD_LIBRARY_PATH - -DM=`$JAVA -d32 GetDataModel` -case "$DM" in - 32 ) - ;; - - * ) - echo "The combination \"java -d32\" failed." - echo $DM - exit 1 -esac - -# Rerun test with LD_LIBRARY_PATH preset -LD_LIBRARY_PATH=`$JAVA GetLdLibraryPath`; -DM=`$JAVA -d32 GetDataModel` -case "$DM" in - 32 ) - ;; - - * ) - echo "The combination \"java -d32\" failed with preset LD_LIBRARY_PATH." - echo $DM - exit 1 -esac - -# Reset LD_LIBRARY_PATH -LD_LIBRARY_PATH= - - -# Test for 64-bit executable - -if [ -f $JAVA64FILE ]; then - - DM=`$JAVA -d64 GetDataModel` - case "$DM" in - 64 ) - ;; - - * ) - echo "The combination \"java -d64\" failed." - exit 1 - esac - - DM=`$JAVA64 -d32 GetDataModel` - case "$DM" in - 32 ) - ;; - - * ) - echo "The combination \"sparcv9/java -d32\" failed." - exit 1 - esac - - DM=`$JAVA64 -d64 GetDataModel` - case "$DM" in - 64 ) - ;; - - * ) - echo "The combination \"sparcv9/java -d64\" failed." - exit 1 - esac - - # Rerun tests with LD_LIBRARY_PATH preset - LD_LIBRARY_PATH=`$JAVA GetLdLibraryPath`; - echo "Presetting LD_LIBRARY_PATH" - - DM=`$JAVA -d64 GetDataModel` - case "$DM" in - 64 ) - ;; - - * ) - echo "The combination \"java -d64\" failed with preset LD_LIBRARY_PATH." - exit 1 - esac - - DM=`$JAVA64 -d32 GetDataModel` - case "$DM" in - 32 ) - ;; - - * ) - echo "The combination \"sparcv9/java -d32\" failed with preset LD_LIBRARY_PATH." - exit 1 - esac - - DM=`$JAVA64 -d64 GetDataModel` - case "$DM" in - 64 ) - ;; - - * ) - echo "The combination \"sparcv9/java -d64\" failed with preset LD_LIBRARY_PATH." - exit 1 - esac - -else - echo "Warning: no 64-bit components found; only java -d32 tests have been run." -fi -exit 0; diff --git a/jdk/test/tools/launcher/SolarisRunpath.sh b/jdk/test/tools/launcher/SolarisRunpath.sh deleted file mode 100644 index 26dd964f654..00000000000 --- a/jdk/test/tools/launcher/SolarisRunpath.sh +++ /dev/null @@ -1,221 +0,0 @@ -# Copyright 2007 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 4731671 -# @build libraryCaller -# @run shell SolarisRunpath.sh -# @summary Verify that Solaris LD_LIBRARY_PATH rules are followed -# @author Joseph D. Darcy - -# The launcher has been updated to properly take account of Solaris -# LD_LIBRARY_PATH rules when constructing the runpath for the Java -# executable. That is, data model dependent LD_LIBRARY_PATH variables -# are tested for and override LD_LIBRARY_PATH if present. The current -# launcher design relies on LD_LIBRARY_PATH settings to ensure the -# proper jre/jdk libraries are opening during program execution. In -# the future, this dependence might be removed by having the vm -# explicitly dlopen the needed files. If that change occurs, this -# test will be harmless but no long relevant. - -# A more robust test for Solaris SPARC would set the different -# LD_LIBRARY_PATH variables while also varying the -d[32|64] options -# to make sure the LD_LIBRARY_PATH of the *target* data model were -# being respected. That is "java -d64" should use the 64-bit -# LD_LIBRARY_PATH while "java -d32" should use the 32-bit -# LD_LIBRARY_PATH regardless of the data model of the "java" binary. -# However, by default builds do not contain both 32 and 64 bit -# components so such a test would often not be applicable. - - -# If the test is not being run on a Solaris box, SPARC or x86, the -# test succeeds immediately. - -OS=`uname -s`; - -case "$OS" in - SunOS ) - PATHSEP=":" - ;; - - * ) - echo "Not a Solaris environment; test vacuously succeeds." - exit 0; - ;; -esac - -# Verify directory context variables are set -if [ "${TESTJAVA}" = "" ] -then - echo "TESTJAVA not set. Test cannot execute. Failed." - exit 1 -fi - -if [ "${TESTSRC}" = "" ] -then - echo "TESTSRC not set. Test cannot execute. Failed." - exit 1 -fi - - -if [ "${TESTCLASSES}" = "" ] -then - echo "TESTCLASSES not set. Test cannot execute. Failed." - exit 1 -fi - -# Construct paths to default Java executables -JAVAC="$TESTJAVA/bin/javac" - - -# Create our little Java test on the fly -( printf "public class GetDataModel {" - printf " public static void main(String argv[]) {" - printf " System.out.println(System.getProperty(\"sun.arch.data.model\", \"none\"));" - printf " }" - printf "}" -) > GetDataModel.java - -$JAVAC GetDataModel.java - - -# ARCH should be sparc or i386 -ARCH=`uname -p` -case "$ARCH" in - sparc | i386 ) - ;; - - * ) - echo "Unrecognized architecture; test fails." - exit 1 -esac - -# The following construction may not work as desired in a -# 64-bit build. -JAVA="$TESTJAVA/bin/java -classpath $TESTCLASSES${PATHSEP}." - -# Determine data model -DM=`$JAVA GetDataModel` - -# verify DM is 32 or 64 -case "$DM" in - 32 ) - ODM=64; - ;; - - 64 ) - ODM=32; - ;; - - * ) - echo "Unknown data model \"$DM\"; test fails." - exit 1 -esac - -# -------------------- Test 1 -------------------- - -LD_LIBRARY_PATH=$TESTSRC/lib/$ARCH/lib$DM -export LD_LIBRARY_PATH -unset LD_LIBRARY_PATH_32 -unset LD_LIBRARY_PATH_64 - -# With plain LD_LIBRARY_PATH, result should always be 0 -RESULT=`$JAVA libraryCaller` -if [ "${RESULT}" != "0" ]; -then - echo "Not using LD_LIBRARY_PATH; test fails." - exit 1 -fi - -# The following two tests sets both data model dependent -# LD_LIBRARY_PATH variables individually. - -# -------------------- Test 2 -------------------- - -# Set opposite data model variable; should return same result -# as plain LD_LIBRARY_PATH. - -if [ "${DM}" = "32" ]; then - LD_LIBRARY_PATH_64=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_64 -else - LD_LIBRARY_PATH_32=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_32 -fi - -RESULT=`$JAVA libraryCaller` -if [ "${RESULT}" != "0" ]; -then - echo "Using LD_LIBRARY_PATH_$ODM for $DM binary;" - echo "test fails." - exit 1 -fi - -unset LD_LIBRARY_PATH_32 -unset LD_LIBRARY_PATH_64 - -# -------------------- Test 3 -------------------- - -# Set appropriate data model variable; result should match -# data model. -if [ "${DM}" = "32" ]; then - LD_LIBRARY_PATH_32=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_32 -else - LD_LIBRARY_PATH_64=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_64 -fi - -RESULT=`$JAVA libraryCaller` -if [ "${RESULT}" != "$DM" ]; -then - echo "Data model dependent LD_LIBRARY_PATH_$DM" - echo "not overriding LD_LIBRARY_PATH; test fails." - exit 1 -fi - -unset LD_LIBRARY_PATH -unset LD_LIBRARY_PATH_32 -unset LD_LIBRARY_PATH_64 - -# -------------------- Test 4 -------------------- - -# Have only data model dependent LD_LIBRARY_PATH set; result -# should match data model. - -if [ "${DM}" = "32" ]; then - LD_LIBRARY_PATH_32=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_32 -else - LD_LIBRARY_PATH_64=$TESTSRC/lib/$ARCH/lib$DM/lib$DM - export LD_LIBRARY_PATH_64 -fi - -RESULT=`$JAVA libraryCaller` -if [ "${RESULT}" != "$DM" ]; -then - echo "Not using data-model dependent LD_LIBRARY_PATH; test fails." - exit 1 -fi - -# All tests have passed -exit 0 diff --git a/jdk/test/tools/launcher/TestHelper.java b/jdk/test/tools/launcher/TestHelper.java index fb63114b6d5..da7b084dfd7 100644 --- a/jdk/test/tools/launcher/TestHelper.java +++ b/jdk/test/tools/launcher/TestHelper.java @@ -39,18 +39,36 @@ import javax.tools.JavaCompiler; */ public enum TestHelper { INSTANCE; - static final String JAVAHOME = System.getProperty("java.home", "."); + static final String JAVAHOME = System.getProperty("java.home"); static final boolean isSDK = JAVAHOME.endsWith("jre"); static final String javaCmd; + static final String java64Cmd; static final String javacCmd; static final JavaCompiler compiler; - static final boolean debug = Boolean.getBoolean("Arrrghs.Debug"); + static final boolean debug = Boolean.getBoolean("TestHelper.Debug"); static final boolean isWindows = System.getProperty("os.name", "unknown").startsWith("Windows"); + static final boolean is64Bit = + System.getProperty("sun.arch.data.model").equals("64"); + static final boolean is32Bit = + System.getProperty("sun.arch.data.model").equals("32"); + static final boolean isSolaris = + System.getProperty("os.name", "unknown").startsWith("SunOS"); + static final boolean isLinux = + System.getProperty("os.name", "unknown").startsWith("Linux"); + static final boolean isDualMode = isSolaris; + static final boolean isSparc = System.getProperty("os.arch").startsWith("sparc"); + static int testExitValue = 0; static { + if (is64Bit && is32Bit) { + throw new RuntimeException("arch model cannot be both 32 and 64 bit"); + } + if (!is64Bit && !is32Bit) { + throw new RuntimeException("arch model is not 32 or 64 bit ?"); + } compiler = ToolProvider.getSystemJavaCompiler(); File binDir = (isSDK) ? new File((new File(JAVAHOME)).getParentFile(), "bin") : new File(JAVAHOME, "bin"); @@ -69,6 +87,33 @@ public enum TestHelper { if (!javacCmdFile.canExecute()) { throw new RuntimeException("java <" + javacCmd + "> must exist"); } + if (isSolaris) { + File sparc64BinDir = new File(binDir,isSparc ? "sparcv9" : "amd64"); + File java64CmdFile= new File(sparc64BinDir, "java"); + if (java64CmdFile.exists() && java64CmdFile.canExecute()) { + java64Cmd = java64CmdFile.getAbsolutePath(); + } else { + java64Cmd = null; + } + } else { + java64Cmd = null; + } + } + + /* + * usually the jre/lib/arch-name is the same as os.arch, except for x86. + */ + static String getJreArch() { + String arch = System.getProperty("os.arch"); + return arch.equals("x86") ? "i386" : arch; + } + + /* + * A convenience method to create a jar with jar file name and defs + */ + static void createJar(File jarName, String... mainDefs) + throws FileNotFoundException{ + createJar(null, jarName, new File("Foo"), mainDefs); } /* @@ -123,16 +168,23 @@ public enum TestHelper { } } + static TestResult doExec(String...cmds) { + return doExec(null, cmds); + } + /* * A method which executes a java cmd and returns the results in a container */ - static TestResult doExec(String...cmds) { + static TestResult doExec(Map envToSet, String...cmds) { String cmdStr = ""; for (String x : cmds) { cmdStr = cmdStr.concat(x + " "); } ProcessBuilder pb = new ProcessBuilder(cmds); Map env = pb.environment(); + if (envToSet != null) { + env.putAll(envToSet); + } BufferedReader rdr = null; try { List outputList = new ArrayList(); @@ -163,21 +215,25 @@ public enum TestHelper { List testOutput; public TestResult(String str, int rv, List oList) { - status = new StringBuilder(str); + status = new StringBuilder("Executed command: " + str + "\n"); exitValue = rv; testOutput = oList; } + void appendStatus(String x) { + status = status.append(" " + x + "\n"); + } + void checkNegative() { if (exitValue == 0) { - status = status.append(" Error: test must not return 0 exit value"); + appendStatus("Error: test must not return 0 exit value"); testExitValue++; } } void checkPositive() { if (exitValue != 0) { - status = status.append(" Error: test did not return 0 exit value"); + appendStatus("Error: test did not return 0 exit value"); testExitValue++; } } @@ -188,7 +244,7 @@ public enum TestHelper { boolean isZeroOutput() { if (!testOutput.isEmpty()) { - status = status.append(" Error: No message from cmd please"); + appendStatus("Error: No message from cmd please"); testExitValue++; return false; } @@ -197,19 +253,20 @@ public enum TestHelper { boolean isNotZeroOutput() { if (testOutput.isEmpty()) { - status = status.append(" Error: Missing message"); + appendStatus("Error: Missing message"); testExitValue++; return false; } return true; } + @Override public String toString() { - if (debug) { - for (String x : testOutput) { - status = status.append(x + "\n"); - } + status = status.append("++++Test Output Begin++++\n"); + for (String x : testOutput) { + appendStatus(x); } + status = status.append("++++Test Output End++++\n"); return status.toString(); } @@ -219,7 +276,18 @@ public enum TestHelper { return true; } } - status = status.append(" Error: string <" + str + "> not found "); + appendStatus("Error: string <" + str + "> not found"); + testExitValue++; + return false; + } + + boolean matches(String stringToMatch) { + for (String x : testOutput) { + if (x.matches(stringToMatch)) { + return true; + } + } + appendStatus("Error: string <" + stringToMatch + "> not found"); testExitValue++; return false; } diff --git a/jdk/test/tools/launcher/libraryCaller.c b/jdk/test/tools/launcher/libraryCaller.c deleted file mode 100644 index e77f402b799..00000000000 --- a/jdk/test/tools/launcher/libraryCaller.c +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2007 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. - */ - -/* - * - * - * Indictly used by SolarisRunpath.sh; this file is used to generate - * the shared objects: - * - * ./lib/sparc/lib32/liblibrary.so - * ./lib/sparc/lib32/lib32/liblibrary.so - * - * ./lib/sparc/lib64/liblibrary.so - * ./lib/sparc/lib64/lib64/liblibrary.so - * - * ./lib/i386/lib32/liblibrary.so - * ./lib/i386/lib32/lib32/liblibrary.so - * - * The function defined below returns either 0 or the size of an - * integer in the data model used to compile the file (32 for ILP; 64 - * for LP). The libraries in ./lib/$ARCH/lib$DM return 0; those in - * ./lib/$ARCH/lib$DM/lib$DM return 32 or 64. - */ - - -#include -#include "libraryCaller.h" - -#ifndef RETURN_VALUE -#define RETURN_VALUE 0 -#endif - -JNIEXPORT jint JNICALL Java_libraryCaller_number -(JNIEnv *je, jclass jc) { - return RETURN_VALUE; -} diff --git a/jdk/test/tools/launcher/libraryCaller.h b/jdk/test/tools/launcher/libraryCaller.h deleted file mode 100644 index df2ce33f8b6..00000000000 --- a/jdk/test/tools/launcher/libraryCaller.h +++ /dev/null @@ -1,46 +0,0 @@ - -/* - * Copyright 2007 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. - */ - -/* DO NOT EDIT THIS FILE - it is machine generated */ - -#include -/* Header for class libraryCaller */ - -#ifndef _Included_libraryCaller -#define _Included_libraryCaller -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: libraryCaller - * Method: number - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_libraryCaller_number - (JNIEnv *, jclass); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/jdk/test/tools/launcher/libraryCaller.java b/jdk/test/tools/launcher/libraryCaller.java deleted file mode 100644 index f938a2fce23..00000000000 --- a/jdk/test/tools/launcher/libraryCaller.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2007 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. - */ - - -/* - * - * - * Used by SolarisRunpath.sh to help test if the launcher fully - * respects Solaris LD_LIBRARY_PATH semantics. The ./lib directory is - * structured so that the results of the dynamically linked number - * method varies depending on the value the data model dependent - * LD_LIBRARY_PATH variable. - */ - - - -class libraryCaller { - static { - System.loadLibrary("library"); - } - static native int number(); - - public static void main(String argv[]) { - System.out.println(number()); - } -} From bab0e148d6fd632d843ad8c63d3a903ed5834ff8 Mon Sep 17 00:00:00 2001 From: Gary Benson Date: Mon, 23 Nov 2009 10:04:41 +0000 Subject: [PATCH 20/56] 6903453: Zero build on ARM and IA-64 Correctly set uname on ARM, and correctly build fdlibm on IA-64 Reviewed-by: ohair --- corba/make/common/shared/Platform.gmk | 3 +++ 1 file changed, 3 insertions(+) diff --git a/corba/make/common/shared/Platform.gmk b/corba/make/common/shared/Platform.gmk index c444d06f802..b0474d82e16 100644 --- a/corba/make/common/shared/Platform.gmk +++ b/corba/make/common/shared/Platform.gmk @@ -187,6 +187,9 @@ ifeq ($(SYSTEM_UNAME), Linux) sparc*) \ echo sparc \ ;; \ + arm*) \ + echo arm \ + ;; \ *) \ echo $(mach) \ ;; \ From d6a4ac9734648cea5ca5270d02426f2401912b3d Mon Sep 17 00:00:00 2001 From: Gary Benson Date: Mon, 23 Nov 2009 10:04:47 +0000 Subject: [PATCH 21/56] 6903453: Zero build on ARM and IA-64 Correctly set uname on ARM, and correctly build fdlibm on IA-64 Reviewed-by: ohair --- jdk/make/common/shared/Platform.gmk | 3 +++ jdk/src/share/native/java/lang/fdlibm/include/fdlibm.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/jdk/make/common/shared/Platform.gmk b/jdk/make/common/shared/Platform.gmk index e07de2499fb..ee6f38f3bb0 100644 --- a/jdk/make/common/shared/Platform.gmk +++ b/jdk/make/common/shared/Platform.gmk @@ -165,6 +165,9 @@ ifeq ($(SYSTEM_UNAME), Linux) sparc*) \ echo sparc \ ;; \ + arm*) \ + echo arm \ + ;; \ *) \ echo $(mach) \ ;; \ diff --git a/jdk/src/share/native/java/lang/fdlibm/include/fdlibm.h b/jdk/src/share/native/java/lang/fdlibm/include/fdlibm.h index 906bcf94916..874b964871b 100644 --- a/jdk/src/share/native/java/lang/fdlibm/include/fdlibm.h +++ b/jdk/src/share/native/java/lang/fdlibm/include/fdlibm.h @@ -29,7 +29,7 @@ #ifdef __NEWVALID /* special setup for Sun test regime */ #if defined(i386) || defined(i486) || \ defined(intel) || defined(x86) || \ - defined(i86pc) || defined(_M_IA64) + defined(i86pc) || defined(_M_IA64) || defined(ia64) #define _LITTLE_ENDIAN #endif #endif From 01a5fb5da52782b2de1272a0e4486593a4826e6f Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Mon, 23 Nov 2009 08:21:20 -0800 Subject: [PATCH 22/56] 6903638: Remove dependency on AuthPermission from SecurityConstants Move two static fields from SecurityConstants to javax.security.auth.Subject Reviewed-by: mullan --- .../classes/javax/security/auth/Subject.java | 54 ++++++++++++------- .../sun/security/util/SecurityConstants.java | 9 ---- 2 files changed, 35 insertions(+), 28 deletions(-) diff --git a/jdk/src/share/classes/javax/security/auth/Subject.java b/jdk/src/share/classes/javax/security/auth/Subject.java index ecc66fbe055..1e404d6db1d 100644 --- a/jdk/src/share/classes/javax/security/auth/Subject.java +++ b/jdk/src/share/classes/javax/security/auth/Subject.java @@ -40,7 +40,6 @@ import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import java.security.ProtectionDomain; import sun.security.util.ResourcesMgr; -import sun.security.util.SecurityConstants; /** *

    A Subject represents a grouping of related information @@ -239,7 +238,7 @@ public final class Subject implements java.io.Serializable { public void setReadOnly() { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(new AuthPermission("setReadOnly")); + sm.checkPermission(AuthPermissionHolder.SET_READ_ONLY_PERMISSION); } this.readOnly = true; @@ -285,7 +284,7 @@ public final class Subject implements java.io.Serializable { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(new AuthPermission("getSubject")); + sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION); } if (acc == null) { @@ -343,7 +342,7 @@ public final class Subject implements java.io.Serializable { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.DO_AS_PERMISSION); + sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION); } if (action == null) throw new NullPointerException @@ -402,7 +401,7 @@ public final class Subject implements java.io.Serializable { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.DO_AS_PERMISSION); + sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION); } if (action == null) @@ -456,7 +455,7 @@ public final class Subject implements java.io.Serializable { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION); + sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION); } if (action == null) @@ -520,7 +519,7 @@ public final class Subject implements java.io.Serializable { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.DO_AS_PRIVILEGED_PERMISSION); + sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION); } if (action == null) @@ -1044,16 +1043,13 @@ public final class Subject implements java.io.Serializable { if (sm != null) { switch (which) { case Subject.PRINCIPAL_SET: - sm.checkPermission(new AuthPermission - ("modifyPrincipals")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION); break; case Subject.PUB_CREDENTIAL_SET: - sm.checkPermission(new AuthPermission - ("modifyPublicCredentials")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION); break; default: - sm.checkPermission(new AuthPermission - ("modifyPrivateCredentials")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION); break; } } @@ -1073,16 +1069,13 @@ public final class Subject implements java.io.Serializable { if (sm != null) { switch (which) { case Subject.PRINCIPAL_SET: - sm.checkPermission - (new AuthPermission("modifyPrincipals")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PRINCIPALS_PERMISSION); break; case Subject.PUB_CREDENTIAL_SET: - sm.checkPermission - (new AuthPermission("modifyPublicCredentials")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PUBLIC_CREDENTIALS_PERMISSION); break; default: - sm.checkPermission - (new AuthPermission("modifyPrivateCredentials")); + sm.checkPermission(AuthPermissionHolder.MODIFY_PRIVATE_CREDENTIALS_PERMISSION); break; } } @@ -1405,4 +1398,27 @@ public final class Subject implements java.io.Serializable { return set.add(o); } } + + static class AuthPermissionHolder { + static final AuthPermission DO_AS_PERMISSION = + new AuthPermission("doAs"); + + static final AuthPermission DO_AS_PRIVILEGED_PERMISSION = + new AuthPermission("doAsPrivileged"); + + static final AuthPermission SET_READ_ONLY_PERMISSION = + new AuthPermission("setReadOnly"); + + static final AuthPermission GET_SUBJECT_PERMISSION = + new AuthPermission("getSubject"); + + static final AuthPermission MODIFY_PRINCIPALS_PERMISSION = + new AuthPermission("modifyPrincipals"); + + static final AuthPermission MODIFY_PUBLIC_CREDENTIALS_PERMISSION = + new AuthPermission("modifyPublicCredentials"); + + static final AuthPermission MODIFY_PRIVATE_CREDENTIALS_PERMISSION = + new AuthPermission("modifyPrivateCredentials"); + } } diff --git a/jdk/src/share/classes/sun/security/util/SecurityConstants.java b/jdk/src/share/classes/sun/security/util/SecurityConstants.java index 89c6fd7fdea..8ba512390b1 100644 --- a/jdk/src/share/classes/sun/security/util/SecurityConstants.java +++ b/jdk/src/share/classes/sun/security/util/SecurityConstants.java @@ -33,7 +33,6 @@ import java.security.Permission; import java.security.BasicPermission; import java.security.SecurityPermission; import java.security.AllPermission; -import javax.security.auth.AuthPermission; /** * Permission constants and string constants used to create permissions @@ -259,12 +258,4 @@ public final class SecurityConstants { // java.lang.SecurityManager public static final SocketPermission LOCAL_LISTEN_PERMISSION = new SocketPermission("localhost:1024-", SOCKET_LISTEN_ACTION); - - // javax.security.auth.Subject - public static final AuthPermission DO_AS_PERMISSION = - new AuthPermission("doAs"); - - // javax.security.auth.Subject - public static final AuthPermission DO_AS_PRIVILEGED_PERMISSION = - new AuthPermission("doAsPrivileged"); } From 3552fe5b4a2e620ecd3151d56a85ad0289b1368b Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Mon, 23 Nov 2009 10:29:33 -0700 Subject: [PATCH 23/56] 6903102: 3/3 fixes in nightly testing version of ShellScaffold.sh need to be committed Merge Jim's ShellScaffold.sh fixes with Tim's ShellScaffold.sh fixes. Reviewed-by: tbell --- jdk/test/com/sun/jdi/ShellScaffold.sh | 177 +++++++++++++++++++------- 1 file changed, 128 insertions(+), 49 deletions(-) diff --git a/jdk/test/com/sun/jdi/ShellScaffold.sh b/jdk/test/com/sun/jdi/ShellScaffold.sh index 855ba8ba092..6d35af52dd8 100644 --- a/jdk/test/com/sun/jdi/ShellScaffold.sh +++ b/jdk/test/com/sun/jdi/ShellScaffold.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright 2002-2005 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 @@ -194,7 +194,7 @@ findPid() # Return 0 if $1 is the pid of a running process. if [ -z "$isWin98" ] ; then if [ "$osname" = SunOS ] ; then - #Solaris and OpenSolaris use pgrep and not ps in psCmd + # Solaris and OpenSolaris use pgrep and not ps in psCmd findPidCmd="$psCmd" else # Never use plain 'ps', which requires a "controlling terminal" @@ -298,15 +298,15 @@ EOF # On linux, core files take a long time, and can leave # zombie processes if [ "$osname" = SunOS ] ; then - #Experiments show Solaris '/usr/ucb/ps -axwww' and - #'/usr/bin/pgrep -f -l' provide the same small amount of the - #argv string (PRARGSZ=80 in /usr/include/sys/procfs.h) - # 1) This seems to have been working OK in ShellScaffold. - # 2) OpenSolaris does not provide /usr/ucb/ps, so use pgrep - # instead - #The alternative would be to use /usr/bin/pargs [pid] to get - #all the args for a process, splice them back into one - #long string, then grep. + # Experiments show Solaris '/usr/ucb/ps -axwww' and + # '/usr/bin/pgrep -f -l' provide the same small amount of the + # argv string (PRARGSZ=80 in /usr/include/sys/procfs.h) + # 1) This seems to have been working OK in ShellScaffold. + # 2) OpenSolaris does not provide /usr/ucb/ps, so use pgrep + # instead + # The alternative would be to use /usr/bin/pargs [pid] to get + # all the args for a process, splice them back into one + # long string, then grep. UU=`/usr/xpg4/bin/id -u -n` psCmd="pgrep -f -l -U $UU" else @@ -519,7 +519,7 @@ cmd() # if jdb got a cont cmd that caused the debuggee # to run to completion, jdb can be gone before # we get here. - echo quit >& 2 + echo "--Sending cmd: quit" >& 2 echo quit # See 6562090. Maybe there is a way that the exit # can cause jdb to not get the quit. @@ -531,7 +531,7 @@ cmd() # because after starting jdb, we waited # for the prompt. fileSize=`wc -c $jdbOutFile | awk '{ print $1 }'` - echo $* >&2 + echo "--Sending cmd: " $* >&2 # jjh: We have a few intermittent failures here. # It is as if every so often, jdb doesn't @@ -558,12 +558,85 @@ cmd() # seen the ]. echo $* - # wait for jdb output to appear + # Now we have to wait for the next jdb prompt. We wait for a pattern + # to appear in the last line of jdb output. Normally, the prompt is + # + # 1) ^main[89] @ + # + # where ^ means start of line, and @ means end of file with no end of line + # and 89 is the current command counter. But we have complications e.g., + # the following jdb output can appear: + # + # 2) a[89] = 10 + # + # The above form is an array assignment and not a prompt. + # + # 3) ^main[89] main[89] ... + # + # This occurs if the next cmd is one that causes no jdb output, e.g., + # 'trace methods'. + # + # 4) ^main[89] [main[89]] .... > @ + # + # jdb prints a > as a prompt after something like a cont. + # Thus, even though the above is the last 'line' in the file, it + # isn't the next prompt we are waiting for after the cont completes. + # HOWEVER, sometimes we see this for a cont command: + # + # ^main[89] $ + # + # + # 5) ^main[89] > @ + # + # i.e., the > prompt comes out AFTER the prompt we we need to wait for. + # + # So, how do we know when the next prompt has appeared?? + # 1. Search for + # main[89] $ + # This will handle cases 1, 2, 3 + # 2. This leaves cases 4 and 5. + # + # What if we wait for 4 more chars to appear and then search for + # + # main[89] [>]$ + # + # on the last line? + # + # a. if we are currently at + # + # ^main[89] main[89] @ + # + # and a 'trace methods comes in, we will wait until at least + # + # ^main[89] main[89] main@ + # + # and then the search will find the new prompt when it completes. + # + # b. if we are currently at + # + # ^main[89] main[89] @ + # + # and the first form of cont comes in, then we will see + # + # ^main[89] main[89] > $ + # ^x@ + # + # where x is the first char of the msg output when the bkpt is hit + # and we will start our search, which will find the prompt + # when it comes out after the bkpt output, with or without the + # trailing > + # + + # wait for 4 new chars to appear in the jdb output count=0 + desiredFileSize=`expr $fileSize + 4` msg1=`echo At start: cmd/size/waiting : $* / $fileSize / \`date\`` while [ 1 = 1 ] ; do newFileSize=`wc -c $jdbOutFile | awk '{ print $1 } '` - if [ "$fileSize" != "$newFileSize" ] ; then + #echo jj: desired = $desiredFileSize, new = $newFileSize >& 2 + + done=`expr $newFileSize \>= $desiredFileSize` + if [ $done = 1 ] ; then break fi sleep ${sleep_seconds} @@ -573,14 +646,19 @@ cmd() echo "--DEBUG: jdb $$ didn't responded to command in $count secs: $*" >& 2 echo "--DEBUG:" $msg1 >& 2 echo "--DEBUG: "done size/waiting : / $newFileSize / `date` >& 2 - $psCmd | sed -e '/com.sun.javatest/d' -e '/nsk/d' >& 2 + echo "-- $jdbOutFile follows-------------------------------" >& 2 + cat $jdbOutFile >& 2 + echo "------------------------------------------" >& 2 + dojstack + #$psCmd | sed -e '/com.sun.javatest/d' -e '/nsk/d' >& 2 if [ $count = 60 ] ; then dofail "jdb never responded to command: $*" fi fi done - - waitForJdbMsg '^.*\[[0-9]*\] $' 1 allowExit + # Note that this assumes just these chars in thread names. + waitForJdbMsg '[a-zA-Z0-9_-][a-zA-Z0-9_-]*\[[1-9][0-9]*\] [ >]*$' \ + 1 allowExit } setBkpts() @@ -596,15 +674,19 @@ setBkpts() runToBkpt() { cmd run + # Don't need to do this - the above waits for the next prompt which comes out + # AFTER the Breakpoint hit message. # Wait for jdb to hit the bkpt - waitForJdbMsg "Breakpoint hit" 5 + #waitForJdbMsg "Breakpoint hit" 5 } contToBkpt() { cmd cont + # Don't need to do this - the above waits for the next prompt which comes out + # AFTER the Breakpoint hit message. # Wait for jdb to hit the bkpt - waitForJdbMsg "Breakpoint hit" 5 + #waitForJdbMsg "Breakpoint hit" 5 } @@ -618,7 +700,7 @@ waitForJdbMsg() nlines=$2 allowExit="$3" myCount=0 - timeLimit=40 # wait a max of 40 secs for a response from a jdb command + timeLimit=40 # wait a max of this many secs for a response from a jdb command while [ 1 = 1 ] ; do if [ -r $jdbOutFile ] ; then # Something here causes jdb to complain about Unrecognized cmd on x86. @@ -654,8 +736,11 @@ waitForJdbMsg() myCount=`expr $myCount + ${sleep_seconds}` if [ $myCount -gt $timeLimit ] ; then + echo "--Fail: waitForJdbMsg timed out after $timeLimit seconds, looking for /$1/, in $nlines lines; exitting" >> $failFile + echo "vv jdbOutFile vvvvvvvvvvvvvvvvvvvvvvvvvvvv" >& 2 + cat $jdbOutFile >& 2 + echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" >& 2 dojstack - echo "--Fail: waitForJdbMsg timed out after $timeLimit seconds; exitting" >> $failFile exit 1 fi done @@ -865,35 +950,29 @@ grepForString() # get inserted into the string we are searching for # so ignore those chars. if [ -z "$3" ] ; then - case "$2" in - *\>*) - # Target string contains a > so we better - # not ignore it - $grep -s "$2" $1 > $devnull 2>&1 - stat=$? - ;; - *) - # Target string does not contain a >. - # Ignore > and '> ' in the file. - cat $1 | sed -e 's@> @@g' -e 's@>@@g' | $grep -s "$2" > $devnull 2>&1 - stat=$? - esac + theCmd=cat else - case "$2" in - *\>*) - # Target string contains a > so we better - # not ignore it - tail -$3 $1 | $grep -s "$2" > $devnull 2>&1 - stat=$? - ;; - *) - # Target string does not contain a >. - # Ignore > and '> ' in the file. - tail -$3 $1 | sed -e 's@> @@g' -e 's@>@@g' | $grep -s "$2" > $devnull 2>&1 - stat=$? - ;; - esac + theCmd="tail -$3" fi + case "$2" in + *\>*) + # Target string contains a > so we better + # not ignore it + $theCmd $1 | $grep -s "$2" > $devnull 2>&1 + return $? + ;; + esac + # Target string does not contain a >. + # Ignore > and '> ' in the file. + # NOTE: if $1 does not end with a new line, piping it to sed doesn't include the + # chars on the last line. Detect this case, and add a new line. + cp $1 $1.tmp + if [ `tail -1 $1.tmp | wc -l | sed -e 's@ @@g'` = 0 ] ; then + echo >> $1.tmp + fi + $theCmd $1.tmp | sed -e 's@> @@g' -e 's@>@@g' | $grep -s "$2" > $devnull 2>&1 + stat=$? + rm -f $1.tmp return $stat } From 3932bb1884dc42382409a679c5f60477e366cc12 Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Mon, 23 Nov 2009 12:36:54 -0500 Subject: [PATCH 24/56] 6899503: Security code issue using Verisign root certificate Add support for reordering out-of-order certificate chains Reviewed-by: vinnie, xuelei --- .../sun/security/validator/PKIXValidator.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/classes/sun/security/validator/PKIXValidator.java b/jdk/src/share/classes/sun/security/validator/PKIXValidator.java index 1cc6a4ee5a4..eb12ef22002 100644 --- a/jdk/src/share/classes/sun/security/validator/PKIXValidator.java +++ b/jdk/src/share/classes/sun/security/validator/PKIXValidator.java @@ -150,9 +150,17 @@ public final class PKIXValidator extends Validator { ("null or zero-length certificate chain"); } if (TRY_VALIDATOR) { - // check if chain contains trust anchor + // check that chain is in correct order and check if chain contains + // trust anchor + X500Principal prevIssuer = null; for (int i = 0; i < chain.length; i++) { - if (trustedCerts.contains(chain[i])) { + X509Certificate cert = chain[i]; + if (i != 0 && + !cert.getSubjectX500Principal().equals(prevIssuer)) { + // chain is not ordered correctly, call builder instead + return doBuild(chain, otherCerts); + } + if (trustedCerts.contains(cert)) { if (i == 0) { return new X509Certificate[] {chain[0]}; } @@ -161,6 +169,7 @@ public final class PKIXValidator extends Validator { System.arraycopy(chain, 0, newChain, 0, i); return doValidate(newChain); } + prevIssuer = cert.getIssuerX500Principal(); } // apparently issued by trust anchor? @@ -303,5 +312,4 @@ public final class PKIXValidator extends Validator { ("PKIX path building failed: " + e.toString(), e); } } - } From d020b04219baa27e8a4a112f67639f6feeb1be5d Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Mon, 23 Nov 2009 09:51:52 -0800 Subject: [PATCH 25/56] 6902666: Include closed tests in the test/Makefile jdk_* targets 6902667: Fix JT_HOME not working from env in jdk/test/Makefile Reviewed-by: mullan, dcubed --- jdk/test/Makefile | 52 ++++++++++++++++++++++++++++------------ jdk/test/ProblemList.txt | 15 ++++++++++++ 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/jdk/test/Makefile b/jdk/test/Makefile index 602d8fc0a91..c5a982972b1 100644 --- a/jdk/test/Makefile +++ b/jdk/test/Makefile @@ -337,9 +337,11 @@ clean: # jtreg tests # Expect JT_HOME to be set for jtreg tests. (home for jtreg) -JT_HOME = $(SLASH_JAVA)/re/jtreg/4.0/promoted/latest/binaries/jtreg -ifdef JPRT_JTREG_HOME - JT_HOME = $(JPRT_JTREG_HOME) +ifndef JT_HOME + JT_HOME = $(SLASH_JAVA)/re/jtreg/4.0/promoted/latest/binaries/jtreg + ifdef JPRT_JTREG_HOME + JT_HOME = $(JPRT_JTREG_HOME) + endif endif # Expect JPRT to set TESTDIRS to the jtreg test dirs @@ -361,21 +363,22 @@ endif # Some tests annoy me and fail frequently PROBLEM_LIST=ProblemList.txt +PROBLEM_LISTS=$(PROBLEM_LIST) $(wildcard closed/$(PROBLEM_LIST)) EXCLUDELIST=$(ABS_TEST_OUTPUT_DIR)/excludelist.txt # Create exclude list for this platform and arch ifdef NO_EXCLUDES -$(EXCLUDELIST): $(PROBLEM_LIST) $(TESTDIRS) +$(EXCLUDELIST): $(PROBLEM_LISTS) $(TESTDIRS) @$(ECHO) "NOTHING_EXCLUDED" > $@ else -$(EXCLUDELIST): $(PROBLEM_LIST) $(TESTDIRS) +$(EXCLUDELIST): $(PROBLEM_LISTS) $(TESTDIRS) @$(RM) $@ $@.temp1 $@.temp2 - @( ( $(EGREP) -- '$(OS_NAME)-all' $< ) ;\ - ( $(EGREP) -- '$(OS_NAME)-$(OS_ARCH)' $< ) ;\ - ( $(EGREP) -- '$(OS_NAME)-$(OS_VERSION)' $< ) ;\ - ( $(EGREP) -- 'generic-$(OS_ARCH)' $< ) ;\ - ( $(EGREP) -- 'generic-all' $< ) ;\ - ( $(ECHO) "#") ;\ + @(($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- '$(OS_NAME)-all' ) ;\ + ($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- '$(OS_NAME)-$(OS_ARCH)' ) ;\ + ($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- '$(OS_NAME)-$(OS_VERSION)') ;\ + ($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- 'generic-$(OS_ARCH)' ) ;\ + ($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- 'generic-all' ) ;\ + ($(ECHO) "#") ;\ ) | $(SED) -e 's@^[\ ]*@@' \ | $(EGREP) -v '^#' > $@.temp1 @for tdir in $(TESTDIRS) ; do \ @@ -386,14 +389,18 @@ $(EXCLUDELIST): $(PROBLEM_LIST) $(TESTDIRS) @$(ECHO) "Excluding list contains `$(EXPAND) $@ | $(WC) -l` items" endif +# Select list of directories that exist +define TestDirs +$(foreach i,$1,$(wildcard ${i})) $(foreach i,$1,$(wildcard closed/${i})) +endef # Running batches of tests with or without samevm define RunSamevmBatch -$(ECHO) "Running tests in samevm mode: $?" -$(MAKE) TESTDIRS="$?" USE_JTREG_SAMEVM=true UNIQUE_DIR=$@ jtreg_tests +$(ECHO) "Running tests in samevm mode: $(call TestDirs, $?)" +$(MAKE) TESTDIRS="$(call TestDirs, $?)" USE_JTREG_SAMEVM=true UNIQUE_DIR=$@ jtreg_tests endef define RunOthervmBatch -$(ECHO) "Running tests in othervm mode: $?" -$(MAKE) TESTDIRS="$?" USE_JTREG_SAMEVM=false UNIQUE_DIR=$@ jtreg_tests +$(ECHO) "Running tests in othervm mode: $(call TestDirs, $?)" +$(MAKE) TESTDIRS="$(call TestDirs, $?)" USE_JTREG_SAMEVM=false UNIQUE_DIR=$@ jtreg_tests endef define SummaryInfo $(ECHO) "Summary for: $?" @@ -428,6 +435,9 @@ JDK_ALL_TARGETS += jdk_beans3 jdk_beans3: java/beans/XMLEncoder $(call RunOthervmBatch) +jdk_beans: jdk_beans1 jdk_beans2 jdk_beans3 + @$(SummaryInfo) + # Stable samevm testruns (minus items from PROBLEM_LIST) JDK_ALL_TARGETS += jdk_io jdk_io: java/io @@ -450,6 +460,9 @@ JDK_ALL_TARGETS += jdk_management2 jdk_management2: com/sun/jmx com/sun/management sun/management $(call RunOthervmBatch) +jdk_management: jdk_management1 jdk_management2 + @$(SummaryInfo) + # Stable samevm testruns (minus items from PROBLEM_LIST) JDK_ALL_TARGETS += jdk_math jdk_math: java/math @@ -482,6 +495,9 @@ JDK_ALL_TARGETS += jdk_nio3 jdk_nio3: com/sun/nio sun/nio $(call RunOthervmBatch) +jdk_nio: jdk_nio1 jdk_nio2 jdk_nio3 + @$(SummaryInfo) + # Stable othervm testruns (minus items from PROBLEM_LIST) # Using samevm has serious problems with these tests JDK_ALL_TARGETS += jdk_rmi @@ -502,6 +518,9 @@ JDK_ALL_TARGETS += jdk_security3 jdk_security3: com/sun/security lib/security javax/security sun/security $(call RunOthervmBatch) +jdk_security: jdk_security1 jdk_security2 jdk_security3 + @$(SummaryInfo) + # Stable othervm testruns (minus items from PROBLEM_LIST) # Using samevm has problems, and doesn't help performance as much as others. JDK_ALL_TARGETS += jdk_swing @@ -522,6 +541,9 @@ JDK_ALL_TARGETS += jdk_tools2 jdk_tools2: com/sun/tools sun/jvmstat sun/tools tools vm com/sun/servicetag com/sun/tracing $(call RunOthervmBatch) +jdk_tools: jdk_tools1 jdk_tools2 + @$(SummaryInfo) + # Stable samevm testruns (minus items from PROBLEM_LIST) JDK_ALL_TARGETS += jdk_util jdk_util: java/util sun/util diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 4bced4d851b..d9620c8b28f 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -344,6 +344,9 @@ java/io/StreamTokenizer/Comment.java generic-all # Some of these tests (like java/lang/management) may just need to be marked # othervm, but that is partially speculation. +# Samevm failure on OpenSolaris, security manager? +java/lang/ClassLoader/UninitializedParent.java generic-all + # Times out on solaris 10 sparc java/lang/ClassLoader/Assert.java generic-all @@ -538,6 +541,18 @@ javax/imageio/plugins/jpeg/ReadAsGrayTest.java generic-all # Missing close on file wbmp*, windows samevm javax/imageio/plugins/wbmp/CanDecodeTest.java generic-all +# Failures on OpenSolaris, cannot read input files? samevm issues? +javax/imageio/metadata/BooleanAttributes.java generic-all +javax/imageio/plugins/bmp/BMPSubsamplingTest.java generic-all +javax/imageio/plugins/bmp/TopDownTest.java generic-all +javax/imageio/plugins/gif/EncodeSubImageTest.java generic-all +javax/imageio/plugins/gif/GifTransparencyTest.java generic-all +javax/imageio/plugins/png/GrayPngTest.java generic-all +javax/imageio/plugins/png/ItxtUtf8Test.java generic-all +javax/imageio/plugins/png/MergeStdCommentTest.java generic-all +javax/imageio/plugins/png/ShortHistogramTest.java generic-all +javax/imageio/plugins/shared/BitDepth.java generic-all + # Exclude all javax/print tests, even if they passed, they may need samevm work # Times out on solaris-sparc, sparcv9, x64 -server, some on i586 -client From 84a48a729362bb039b1d050fecea45325f3fcf56 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Mon, 23 Nov 2009 19:26:16 +0000 Subject: [PATCH 26/56] 6888171: JMX Monitor API should not require JavaBeans to be present Reviewed-by: emcmanus --- .../com/sun/jmx/mbeanserver/Introspector.java | 261 +++++++++++++++++- .../jmx/mbeanserver/MBeanIntrospector.java | 2 +- 2 files changed, 257 insertions(+), 6 deletions(-) diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java index 09b5701a95e..a841e992b4a 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -26,6 +26,7 @@ package com.sun.jmx.mbeanserver; import java.lang.annotation.Annotation; +import java.lang.ref.SoftReference; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Method; @@ -33,8 +34,13 @@ import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; +import java.util.List; +import java.util.LinkedList; +import java.util.Locale; import java.util.Map; +import java.util.WeakHashMap; import javax.management.Descriptor; import javax.management.DescriptorKey; @@ -506,11 +512,25 @@ public class Introspector { } else { // Java Beans introspection // - BeanInfo bi = java.beans.Introspector.getBeanInfo(complex.getClass()); - PropertyDescriptor[] pds = bi.getPropertyDescriptors(); - for (PropertyDescriptor pd : pds) - if (pd.getName().equals(element)) - return pd.getReadMethod().invoke(complex); + Class clazz = complex.getClass(); + Method readMethod = null; + if (BeansHelper.isAvailable()) { + Object bi = BeansHelper.getBeanInfo(clazz); + Object[] pds = BeansHelper.getPropertyDescriptors(bi); + for (Object pd: pds) { + if (BeansHelper.getPropertyName(pd).equals(element)) { + readMethod = BeansHelper.getReadMethod(pd); + break; + } + } + } else { + // Java Beans not available so use simple introspection + // to locate method + readMethod = SimpleIntrospector.getReadMethod(clazz, element); + } + if (readMethod != null) + return readMethod.invoke(complex); + throw new AttributeNotFoundException( "Could not find the getter method for the property " + element + " using the Java Beans introspector"); @@ -524,4 +544,235 @@ public class Introspector { new AttributeNotFoundException(e.getMessage()), e); } } + + /** + * A simple introspector that uses reflection to analyze a class and + * identify its "getter" methods. This class is intended for use only when + * Java Beans is not present (which implies that there isn't explicit + * information about the bean available). + */ + private static class SimpleIntrospector { + private SimpleIntrospector() { } + + private static final String GET_METHOD_PREFIX = "get"; + private static final String IS_METHOD_PREFIX = "is"; + + // cache to avoid repeated lookups + private static final Map,SoftReference>> cache = + Collections.synchronizedMap( + new WeakHashMap,SoftReference>> ()); + + /** + * Returns the list of methods cached for the given class, or {@code null} + * if not cached. + */ + private static List getCachedMethods(Class clazz) { + // return cached methods if possible + SoftReference> ref = cache.get(clazz); + if (ref != null) { + List cached = ref.get(); + if (cached != null) + return cached; + } + return null; + } + + /** + * Returns {@code true} if the given method is a "getter" method (where + * "getter" method is a public method of the form getXXX or "boolean + * isXXX") + */ + static boolean isReadMethod(Method method) { + // ignore static methods + int modifiers = method.getModifiers(); + if (Modifier.isStatic(modifiers)) + return false; + + String name = method.getName(); + Class[] paramTypes = method.getParameterTypes(); + int paramCount = paramTypes.length; + + if (paramCount == 0 && name.length() > 2) { + // boolean isXXX() + if (name.startsWith(IS_METHOD_PREFIX)) + return (method.getReturnType() == boolean.class); + // getXXX() + if (name.length() > 3 && name.startsWith(GET_METHOD_PREFIX)) + return (method.getReturnType() != void.class); + } + return false; + } + + /** + * Returns the list of "getter" methods for the given class. The list + * is ordered so that isXXX methods appear before getXXX methods - this + * is for compatability with the JavaBeans Introspector. + */ + static List getReadMethods(Class clazz) { + // return cached result if available + List cachedResult = getCachedMethods(clazz); + if (cachedResult != null) + return cachedResult; + + // get list of public methods, filtering out methods that have + // been overridden to return a more specific type. + List methods = + StandardMBeanIntrospector.getInstance().getMethods(clazz); + methods = MBeanAnalyzer.eliminateCovariantMethods(methods); + + // filter out the non-getter methods + List result = new LinkedList(); + for (Method m: methods) { + if (isReadMethod(m)) { + // favor isXXX over getXXX + if (m.getName().startsWith(IS_METHOD_PREFIX)) { + result.add(0, m); + } else { + result.add(m); + } + } + } + + // add result to cache + cache.put(clazz, new SoftReference>(result)); + + return result; + } + + /** + * Returns the "getter" to read the given property from the given class or + * {@code null} if no method is found. + */ + static Method getReadMethod(Class clazz, String property) { + // first character in uppercase (compatability with JavaBeans) + property = property.substring(0, 1).toUpperCase(Locale.ENGLISH) + + property.substring(1); + String getMethod = GET_METHOD_PREFIX + property; + String isMethod = IS_METHOD_PREFIX + property; + for (Method m: getReadMethods(clazz)) { + String name = m.getName(); + if (name.equals(isMethod) || name.equals(getMethod)) { + return m; + } + } + return null; + } + } + + /** + * A class that provides access to the JavaBeans Introspector and + * PropertyDescriptors without creating a static dependency on java.beans. + */ + private static class BeansHelper { + private static final Class introspectorClass = + getClass("java.beans.Introspector"); + private static final Class beanInfoClass = + (introspectorClass == null) ? null : getClass("java.beans.BeanInfo"); + private static final Class getPropertyDescriptorClass = + (beanInfoClass == null) ? null : getClass("java.beans.PropertyDescriptor"); + + private static final Method getBeanInfo = + getMethod(introspectorClass, "getBeanInfo", Class.class); + private static final Method getPropertyDescriptors = + getMethod(beanInfoClass, "getPropertyDescriptors"); + private static final Method getPropertyName = + getMethod(getPropertyDescriptorClass, "getName"); + private static final Method getReadMethod = + getMethod(getPropertyDescriptorClass, "getReadMethod"); + + private static Class getClass(String name) { + try { + return Class.forName(name, true, null); + } catch (ClassNotFoundException e) { + return null; + } + } + private static Method getMethod(Class clazz, + String name, + Class... paramTypes) + { + if (clazz != null) { + try { + return clazz.getMethod(name, paramTypes); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } else { + return null; + } + } + + private BeansHelper() { } + + /** + * Returns {@code true} if java.beans is available. + */ + static boolean isAvailable() { + return introspectorClass != null; + } + + /** + * Invokes java.beans.Introspector.getBeanInfo(Class) + */ + static Object getBeanInfo(Class clazz) throws Exception { + try { + return getBeanInfo.invoke(null, clazz); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof Exception) + throw (Exception)cause; + throw new AssertionError(e); + } catch (IllegalAccessException iae) { + throw new AssertionError(iae); + } + } + + /** + * Invokes java.beans.BeanInfo.getPropertyDescriptors() + */ + static Object[] getPropertyDescriptors(Object bi) { + try { + return (Object[])getPropertyDescriptors.invoke(bi); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) + throw (RuntimeException)cause; + throw new AssertionError(e); + } catch (IllegalAccessException iae) { + throw new AssertionError(iae); + } + } + + /** + * Invokes java.beans.PropertyDescriptor.getName() + */ + static String getPropertyName(Object pd) { + try { + return (String)getPropertyName.invoke(pd); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) + throw (RuntimeException)cause; + throw new AssertionError(e); + } catch (IllegalAccessException iae) { + throw new AssertionError(iae); + } + } + + /** + * Invokes java.beans.PropertyDescriptor.getReadMethod() + */ + static Method getReadMethod(Object pd) { + try { + return (Method)getReadMethod.invoke(pd); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof RuntimeException) + throw (RuntimeException)cause; + throw new AssertionError(e); + } catch (IllegalAccessException iae) { + throw new AssertionError(iae); + } + } + } } diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java index 9edde66faf2..17f31d16a9e 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java @@ -175,7 +175,7 @@ abstract class MBeanIntrospector { /** * Get the methods to be analyzed to build the MBean interface. */ - List getMethods(final Class mbeanType) throws Exception { + List getMethods(final Class mbeanType) { return Arrays.asList(mbeanType.getMethods()); } From 812677f7203d8ba5c9cc7a56610342bf8f53d800 Mon Sep 17 00:00:00 2001 From: Denis Fokin Date: Tue, 24 Nov 2009 18:46:17 +0300 Subject: [PATCH 27/56] 5098433: REG: DnD of File-List between JVM is broken for non ASCII file names - Win32 Reviewed-by: uta, dav --- .../sun/awt/datatransfer/DataTransferer.java | 25 ++- .../windows/native/sun/windows/awt_DnDDS.cpp | 4 +- .../AbsoluteComponentCenterCalculator.java | 34 +++ .../DragUnicodeBetweenJVMTest.html | 25 +++ .../DragUnicodeBetweenJVMTest.java | 193 ++++++++++++++++++ .../FileListTransferable.java | 68 ++++++ .../InterprocessMessages.java | 28 +++ .../NextFramePositionCalculator.java | 43 ++++ .../SourcePanel.java | 50 +++++ .../TargetPanel.java | 115 +++++++++++ 10 files changed, 577 insertions(+), 8 deletions(-) create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/AbsoluteComponentCenterCalculator.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.html create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/FileListTransferable.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/InterprocessMessages.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/NextFramePositionCalculator.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/SourcePanel.java create mode 100644 jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/TargetPanel.java diff --git a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java index 277d3bd9e28..a0853088e42 100644 --- a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java +++ b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java @@ -203,6 +203,8 @@ public abstract class DataTransferer { private static final Map nativeEOLNs = Collections.synchronizedMap(new HashMap()); + private static final byte [] UNICODE_NULL_TERMINATOR = new byte [] {0,0}; + /** * The number of terminating NUL bytes for the Set of textNatives. */ @@ -1299,7 +1301,7 @@ search: } final List list = (List)obj; - final ArrayList fileList = new ArrayList(); + final ArrayList fileList = new ArrayList(); final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents); @@ -1331,13 +1333,24 @@ search: throw new IOException(pae.getMessage()); } - for (int i = 0; i < fileList.size(); i++) - { - byte[] bytes = ((String)fileList.get(i)).getBytes(); - if (i != 0) bos.write(0); - bos.write(bytes, 0, bytes.length); + if(fileList.isEmpty()) { + //store empty unicode string (null terminator) + bos.write(UNICODE_NULL_TERMINATOR); + } else { + for (int i = 0; i < fileList.size(); i++) { + byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding()); + //store unicode string with null terminator + bos.write(bytes, 0, bytes.length); + bos.write(UNICODE_NULL_TERMINATOR); + } } + // According to MSDN the byte array have to be double NULL-terminated. + // The array contains Unicode characters, so each NULL-terminator is + // a pair of bytes + + bos.write(UNICODE_NULL_TERMINATOR); + // Source data is an InputStream. For arbitrary flavors, just grab the // bytes and dump them into a byte array. For text flavors, decode back // to a String and recur to reencode according to the requested format. diff --git a/jdk/src/windows/native/sun/windows/awt_DnDDS.cpp b/jdk/src/windows/native/sun/windows/awt_DnDDS.cpp index bb2ac566493..b0438eae061 100644 --- a/jdk/src/windows/native/sun/windows/awt_DnDDS.cpp +++ b/jdk/src/windows/native/sun/windows/awt_DnDDS.cpp @@ -648,7 +648,7 @@ HRESULT __stdcall AwtDragSource::GetData(FORMATETC __RPC_FAR *pFormatEtc, dropfiles->pt.x = m_dropPoint.x; dropfiles->pt.y = m_dropPoint.y; dropfiles->fNC = m_fNC; - dropfiles->fWide = FALSE; // good guess! + dropfiles->fWide = TRUE; // good guess! dataout += sizeof(DROPFILES); } @@ -815,7 +815,7 @@ HRESULT __stdcall AwtDragSource::GetDataHere(FORMATETC __RPC_FAR *pFormatEtc, dropfiles->pt.x = m_dropPoint.x; dropfiles->pt.y = m_dropPoint.y; dropfiles->fNC = m_fNC; - dropfiles->fWide = FALSE; // good guess! + dropfiles->fWide = TRUE; // good guess! dataout += sizeof(DROPFILES); } diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/AbsoluteComponentCenterCalculator.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/AbsoluteComponentCenterCalculator.java new file mode 100644 index 00000000000..83bb3dfecd3 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/AbsoluteComponentCenterCalculator.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. + */ + +import java.awt.*; + +class AbsoluteComponentCenterCalculator { + private AbsoluteComponentCenterCalculator () {} + public static int calculateXCenterCoordinate(Component component) { + return (int)component.getLocationOnScreen().getX()+(component.getWidth()/2); + } + public static int calculateYCenterCoordinate(Component component) { + return (int)component.getLocationOnScreen().getY()+(component.getHeight()/2); + } +} diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.html b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.html new file mode 100644 index 00000000000..49fbaced533 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.html @@ -0,0 +1,25 @@ + + + + REG: DnD of File-List between JVM is broken for non ASCII file names - Win32 + + + +

    DragUnicodeBetweenJVMTest
    Bug ID: 5098433

    + +

    This is an AUTOMATIC test, simply wait for completion

    + + + + diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java new file mode 100644 index 00000000000..e64f15b63f2 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/DragUnicodeBetweenJVMTest.java @@ -0,0 +1,193 @@ +/* + * 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 5098433 + @summary REG: DnD of File-List between JVM is broken for non ASCII file names - Win32 + @author Denis Fokin: area=dnd + @library ../../regtesthelpers + @library ../../regtesthelpers/process + @build Util + @build ProcessResults ProcessCommunicator + + + @run applet/othervm DragUnicodeBetweenJVMTest.html +*/ + +/** + * DragUnicodeBetweenJVMTest.java + * + * summary: The test drags a list of files (DataFlavor.javaFileListFlavor) from one jvm to another. + * The files have Unicode names. The list on target side must be equal to + * the list on the source side. + */ + + +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; + +import test.java.awt.regtesthelpers.process.ProcessCommunicator; +import test.java.awt.regtesthelpers.process.ProcessResults; +import test.java.awt.regtesthelpers.Util; +import static java.lang.Thread.sleep; + +public class DragUnicodeBetweenJVMTest extends Applet +{ + + public void init() { + setLayout(new BorderLayout()); + }//End init() + + public void start() { + + String toolkit = Toolkit.getDefaultToolkit().getClass().getName(); + if (!toolkit.equals("sun.awt.windows.WToolkit")){ + System.out.println("This test is for Windows only. Passed."); + return; + } + else{ + System.out.println("Toolkit = " + toolkit); + } + + final Frame sourceFrame = new Frame("Source frame"); + final SourcePanel sourcePanel = new SourcePanel(); + sourceFrame.add(sourcePanel); + sourceFrame.pack(); + sourceFrame.addWindowListener( new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + sourceFrame.dispose(); + } + }); + sourceFrame.setVisible(true); + + Util.waitForIdle(null); + + NextFramePositionCalculator positionCalculator = new NextFramePositionCalculator(sourceFrame); + + String [] args = new String [] { + String.valueOf(positionCalculator.getNextLocationX()), + String.valueOf(positionCalculator.getNextLocationY()), + String.valueOf(AbsoluteComponentCenterCalculator.calculateXCenterCoordinate(sourcePanel)), + String.valueOf(AbsoluteComponentCenterCalculator.calculateYCenterCoordinate(sourcePanel)), + }; + + + ProcessResults processResults = + // ProcessCommunicator.executeChildProcess(this.getClass()," -cp \"C:\\Documents and Settings\\df153228\\IdeaProjects\\UnicodeTestDebug\\out\\production\\UnicodeTestDebug\" -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 ", args); + ProcessCommunicator.executeChildProcess(this.getClass(), args); + + verifyTestResults(processResults); + + }// start() + + + + private static void verifyTestResults(ProcessResults processResults) { + if ( InterprocessMessages.FILES_ON_TARGET_ARE_CORRUPTED == + processResults.getExitValue()) + { + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target has recieved" + + " broken file list."); + } + processResults.verifyStdErr(System.err); + processResults.verifyProcessExitValue(System.err); + processResults.printProcessStandartOutput(System.out); + } + + //We cannot make an instance of the applet without the default constructor + public DragUnicodeBetweenJVMTest () { + super(); + } + + //We need in this constructor to pass frame position between JVMs + public DragUnicodeBetweenJVMTest (Point targetFrameLocation, Point dragSourcePoint) + throws InterruptedException + { + final Frame targetFrame = new Frame("Target frame"); + final TargetPanel targetPanel = new TargetPanel(targetFrame); + targetFrame.add(targetPanel); + targetFrame.addWindowListener( new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + targetFrame.dispose(); + } + }); + targetFrame.setLocation(targetFrameLocation); + targetFrame.pack(); + targetFrame.setVisible(true); + + doTest(dragSourcePoint, targetPanel); + } + + private void doTest(Point dragSourcePoint, TargetPanel targetPanel) { + Util.waitForIdle(null); + + final Robot robot = Util.createRobot(); + + robot.mouseMove((int)dragSourcePoint.getX(),(int)dragSourcePoint.getY()); + try { + sleep(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + sleep(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + Util.drag(robot, dragSourcePoint, new Point (AbsoluteComponentCenterCalculator.calculateXCenterCoordinate(targetPanel), + AbsoluteComponentCenterCalculator.calculateYCenterCoordinate(targetPanel)), + InputEvent.BUTTON1_MASK); + } + + + enum InterprocessArguments { + TARGET_FRAME_X_POSITION_ARGUMENT, + TARGET_FRAME_Y_POSITION_ARGUMENT, + DRAG_SOURCE_POINT_X_ARGUMENT, + DRAG_SOURCE_POINT_Y_ARGUMENT; + + int extract (String [] args) { + return Integer.parseInt(args[this.ordinal()]); + } + } + + public static void main (String [] args) { + Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extract(args), + InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extract(args)); + Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extract(args), + InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extract(args)); + + try { + new DragUnicodeBetweenJVMTest(targetFrameLocation, dragSourcePoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + +} diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/FileListTransferable.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/FileListTransferable.java new file mode 100644 index 00000000000..f2dcf607c4c --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/FileListTransferable.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. + */ + +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.IOException; +import java.io.File; +import java.util.Arrays; +import java.util.List; + +class FileListTransferable implements Transferable { + + public static File [] files = new File [] { + new File ("\u042f\u0020\u0441\u0440\u0430\u0437\u0443\u0020\u0441\u043c\u0430\u0437\u0430\u043b" + + "\u0020\u043a\u0430\u0440\u0442\u0443\u0020\u0431\u0443\u0434\u043d\u044f"), + new File ("\u043f\u043b\u0435\u0441\u043d\u0443\u0432\u0448\u0438\u0020\u043a\u0440\u0430\u0441" + + "\u043a\u0443\u0020\u0438\u0437\u0020\u0441\u0442\u0430\u043a\u0430\u043d\u0430"), + new File ("\u044f\u0020\u043f\u043e\u043a\u0430\u0437\u0430\u043b\u0020\u043d\u0430\u0020\u0431" + + "\u043b\u044e\u0434\u0435\u0020\u0441\u0442\u0443\u0434\u043d\u044f"), + new File ("\u043a\u043e\u0441\u044b\u0435\u0020\u0441\u043a\u0443\u043b\u044b\u0020\u043e\u043a" + + "\u0435\u0430\u043d\u0430"), + new File ("\u041d\u0430\u0020\u0447\u0435\u0448\u0443\u0435\u0020\u0436\u0435\u0441\u0442\u044f" + + "\u043d\u043e\u0439\u0020\u0440\u044b\u0431\u044b"), + new File ("\u043f\u0440\u043e\u0447\u0435\u043b\u0020\u044f\u0020\u0437\u043e\u0432\u044b\u0020" + + "\u043d\u043e\u0432\u044b\u0445\u0020\u0433\u0443\u0431"), + new File ("\u0410\u0020\u0432\u044b"), + new File ("\u043d\u043e\u043a\u0442\u044e\u0440\u043d\u0020\u0441\u044b\u0433\u0440\u0430\u0442" + + "\u044c"), + new File ("\u043c\u043e\u0433\u043b\u0438\u0020\u0431\u044b"), + new File ("\u043d\u0430\u0020\u0444\u043b\u0435\u0439\u0442\u0435\u0020\u0432\u043e\u0434\u043e" + + "\u0441\u0442\u043e\u0447\u043d\u044b\u0445\u0020\u0442\u0440\u0443\u0431"), + }; + + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor [] {DataFlavor.javaFileListFlavor}; + } + + public boolean isDataFlavorSupported(DataFlavor flavor) { + return flavor.equals(DataFlavor.javaFileListFlavor) ; + } + + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { + List list = Arrays.asList(files); + return list; + + } +} diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/InterprocessMessages.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/InterprocessMessages.java new file mode 100644 index 00000000000..33bb9a3cbd0 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/InterprocessMessages.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +interface InterprocessMessages { + final static int EXECUTION_IS_SUCCESSFULL = 0; + final static int FILES_ON_TARGET_ARE_CORRUPTED = 212; +} + diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/NextFramePositionCalculator.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/NextFramePositionCalculator.java new file mode 100644 index 00000000000..7d55be76e91 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/NextFramePositionCalculator.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. + * + * 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.awt.*; + + +class NextFramePositionCalculator { + + private final Frame currentFrame; + + public NextFramePositionCalculator (Frame currentFrame) { + this.currentFrame = currentFrame; + } + + public int getNextLocationX() { + return currentFrame.getX()+currentFrame.getWidth(); + } + + public int getNextLocationY() { + return currentFrame.getY(); + } + +} diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/SourcePanel.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/SourcePanel.java new file mode 100644 index 00000000000..075d64810f7 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/SourcePanel.java @@ -0,0 +1,50 @@ +/* + * 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.awt.dnd.DragSource; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.*; + +public class SourcePanel extends Panel +{ + + private final MyDragGestureListener dragGestureListener = + new MyDragGestureListener(); + + public SourcePanel () { + setPreferredSize(new Dimension(200, 200)); + DragSource defaultDragSource = + DragSource.getDefaultDragSource(); + defaultDragSource.createDefaultDragGestureRecognizer(this, + DnDConstants.ACTION_COPY_OR_MOVE, dragGestureListener); + setBackground(Color.RED); + } + + private class MyDragGestureListener implements DragGestureListener { + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, new FileListTransferable()); + } + } +} diff --git a/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/TargetPanel.java b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/TargetPanel.java new file mode 100644 index 00000000000..5688bf69ff2 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/DragUnicodeBetweenJVMTest/TargetPanel.java @@ -0,0 +1,115 @@ +/* + * 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.awt.dnd.*; +import java.awt.*; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Arrays; + +public class TargetPanel extends Panel implements DropTargetListener{ + + private java.util.List content = new ArrayList(); + + //private final CustomDropTargetListener dropTargetListener = new CustomDropTargetListener(); + + private Frame frame; + + public TargetPanel (Frame frame) + { + this.frame = frame; + setBackground(Color.DARK_GRAY); + setPreferredSize(new Dimension(200, 200)); + setDropTarget(new DropTarget(this, this)); + } + + public void dragEnter(DropTargetDragEvent dtde) { + if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); + } + } + + public void dragOver(DropTargetDragEvent dtde) { + if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); + } + } + + public void dropActionChanged(DropTargetDragEvent dtde) { + if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); + } + } + + public void dragExit(DropTargetEvent dte) { + + } + + public void drop(DropTargetDropEvent dtde) { + dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); + if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + try { + content = (java.util.List)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); + repaint(); + } catch (UnsupportedFlavorException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + dtde.dropComplete(true); + + + + boolean listsAreEqual = true; + + for (int i = 0; i < content.size(); i++) { + if(!FileListTransferable.files[i].getName().equals(content.get(i).getName())) { + listsAreEqual = false; + } + } + + if (listsAreEqual) { + System.err.println(InterprocessMessages.EXECUTION_IS_SUCCESSFULL); + System.exit(0); + } + } + dtde.rejectDrop(); + System.err.println(InterprocessMessages.FILES_ON_TARGET_ARE_CORRUPTED); + System.exit(1); + } + + public void paint(Graphics g) { + g.setColor(Color.YELLOW); + int i = 0; + for (Iterator iterator = content.iterator(); iterator.hasNext();i++) { + g.drawString(iterator.next().getName(), 5, g.getFontMetrics().getAscent()*i+20); + } + + } + +} From 547328d305d3cc11a98112c5d35f63fbe779614e Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Wed, 25 Nov 2009 08:24:58 -0800 Subject: [PATCH 28/56] 6904183: Fix jdk/test/com/sun/jdi tests to run with -samevm Reviewed-by: dcubed --- jdk/test/Makefile | 2 +- jdk/test/ProblemList.txt | 6 ------ jdk/test/com/sun/jdi/BadHandshakeTest.java | 2 ++ jdk/test/com/sun/jdi/DoubleAgentTest.java | 2 ++ jdk/test/com/sun/jdi/ExclusiveBind.java | 2 ++ jdk/test/com/sun/jdi/JITDebug.sh | 4 ++-- jdk/test/com/sun/jdi/RepStep.java | 2 +- jdk/test/com/sun/jdi/RunToExit.java | 4 +++- jdk/test/com/sun/jdi/SimulResumerTest.java | 2 +- jdk/test/com/sun/jdi/Solaris32AndSolaris64Test.sh | 4 ++-- jdk/test/com/sun/jdi/VMConnection.java | 3 ++- .../com/sun/jdi/connect/spi/DebugUsingCustomConnector.java | 2 +- jdk/test/com/sun/jdi/connect/spi/GeneratedConnectors.java | 2 +- .../com/sun/jdi/connect/spi/SimpleLaunchingConnector.java | 6 +++++- jdk/test/com/sun/jdi/redefine/RedefineTest.java | 2 +- 15 files changed, 26 insertions(+), 19 deletions(-) diff --git a/jdk/test/Makefile b/jdk/test/Makefile index c5a982972b1..b6fee3c59e2 100644 --- a/jdk/test/Makefile +++ b/jdk/test/Makefile @@ -536,7 +536,7 @@ jdk_text: java/text sun/text # Using samevm has serious problems with these tests JDK_ALL_TARGETS += jdk_tools1 jdk_tools1: com/sun/jdi - $(call RunOthervmBatch) + $(call RunSamevmBatch) JDK_ALL_TARGETS += jdk_tools2 jdk_tools2: com/sun/tools sun/jvmstat sun/tools tools vm com/sun/servicetag com/sun/tracing $(call RunOthervmBatch) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index d9620c8b28f..1867d67a218 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -1088,9 +1088,6 @@ java/text/Bidi/Bug6665028.java linux-x64 # So most if not all tools tests are now being run with "othervm" mode. # Some of these tools tests have a tendency to use fixed ports, bad idea. -# Solaris 10 client x86, java.lang.IndexOutOfBoundsException resumer Interrupted -com/sun/jdi/SimulResumerTest.java generic-all - # Output of jps differs from expected output. # Invalid argument count on solaris-sparc and x64 sun/tools/jstatd/jstatdPort.sh generic-all @@ -1105,9 +1102,6 @@ sun/tools/jps/jps-m_2.sh generic-all # Server name error, port 2098 problem? sun/tools/jstatd/jstatdServerName.sh generic-all -# Solaris, handshake failed, othervm mode -com/sun/jdi/RedefineException.sh generic-all - # These tests fail on solaris sparc, all the time com/sun/servicetag/DeleteServiceTag.java generic-all com/sun/servicetag/DuplicateNotFound.java generic-all diff --git a/jdk/test/com/sun/jdi/BadHandshakeTest.java b/jdk/test/com/sun/jdi/BadHandshakeTest.java index d5ecd0a73b8..6601b427230 100644 --- a/jdk/test/com/sun/jdi/BadHandshakeTest.java +++ b/jdk/test/com/sun/jdi/BadHandshakeTest.java @@ -112,6 +112,8 @@ public class BadHandshakeTest { String arch = System.getProperty("os.arch"); if (arch.equals("sparcv9")) { exe += "sparcv9/java"; + } else if (arch.equals("amd64")) { + exe += "amd64/java"; } else { exe += "java"; } diff --git a/jdk/test/com/sun/jdi/DoubleAgentTest.java b/jdk/test/com/sun/jdi/DoubleAgentTest.java index 77c72cb08fd..f76b17c154e 100644 --- a/jdk/test/com/sun/jdi/DoubleAgentTest.java +++ b/jdk/test/com/sun/jdi/DoubleAgentTest.java @@ -94,6 +94,8 @@ public class DoubleAgentTest { String arch = System.getProperty("os.arch"); if (arch.equals("sparcv9")) { exe += "sparcv9/java"; + } else if (arch.equals("amd64")) { + exe += "amd64/java"; } else { exe += "java"; } diff --git a/jdk/test/com/sun/jdi/ExclusiveBind.java b/jdk/test/com/sun/jdi/ExclusiveBind.java index ca2ba0229ec..0f56d072e2d 100644 --- a/jdk/test/com/sun/jdi/ExclusiveBind.java +++ b/jdk/test/com/sun/jdi/ExclusiveBind.java @@ -101,6 +101,8 @@ public class ExclusiveBind { String arch = System.getProperty("os.arch"); if (arch.equals("sparcv9")) { exe += "sparcv9/java"; + } else if (arch.equals("amd64")) { + exe += "amd64/java"; } else { exe += "java"; } diff --git a/jdk/test/com/sun/jdi/JITDebug.sh b/jdk/test/com/sun/jdi/JITDebug.sh index 33aaa471fd3..637c6deabd3 100644 --- a/jdk/test/com/sun/jdi/JITDebug.sh +++ b/jdk/test/com/sun/jdi/JITDebug.sh @@ -103,10 +103,10 @@ if [ -z "${TESTJAVA}" ] ; then #if running standalone (no test harness of any kind), compile the #support files and the test case ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \ - -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}." \ + -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" \ TestScaffold.java VMConnection.java TargetListener.java TargetAdapter.java ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \ - -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}." -g \ + -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" -g \ JITDebug.java fi echo "JDK under test is: $TESTJAVA" diff --git a/jdk/test/com/sun/jdi/RepStep.java b/jdk/test/com/sun/jdi/RepStep.java index da058b2a3e1..840ebb38427 100644 --- a/jdk/test/com/sun/jdi/RepStep.java +++ b/jdk/test/com/sun/jdi/RepStep.java @@ -29,7 +29,7 @@ * @run compile -g RepStepTarg.java * @run build VMConnection RepStep * - * @run main RepStep + * @run main/othervm RepStep * * @summary RepStep detects missed step events due to lack of * frame pop events (in back-end). diff --git a/jdk/test/com/sun/jdi/RunToExit.java b/jdk/test/com/sun/jdi/RunToExit.java index 947bcb26f97..9495e451669 100644 --- a/jdk/test/com/sun/jdi/RunToExit.java +++ b/jdk/test/com/sun/jdi/RunToExit.java @@ -26,7 +26,7 @@ * @summary Test that with server=y, when VM runs to System.exit() no error happens * * @build VMConnection RunToExit Exit0 - * @run main RunToExit + * @run main/othervm RunToExit */ import java.io.InputStream; import java.io.IOException; @@ -117,6 +117,8 @@ public class RunToExit { String arch = System.getProperty("os.arch"); if (arch.equals("sparcv9")) { exe += "sparcv9/java"; + } else if (arch.equals("amd64")) { + exe += "amd64/java"; } else { exe += "java"; } diff --git a/jdk/test/com/sun/jdi/SimulResumerTest.java b/jdk/test/com/sun/jdi/SimulResumerTest.java index cf7568e8be0..c0f54f806d8 100644 --- a/jdk/test/com/sun/jdi/SimulResumerTest.java +++ b/jdk/test/com/sun/jdi/SimulResumerTest.java @@ -30,7 +30,7 @@ * * @run build TestScaffold VMConnection TargetListener TargetAdapter * @run compile -g SimulResumerTest.java - * @run main SimulResumerTest + * @run main/othervm SimulResumerTest */ import com.sun.jdi.*; import com.sun.jdi.event.*; diff --git a/jdk/test/com/sun/jdi/Solaris32AndSolaris64Test.sh b/jdk/test/com/sun/jdi/Solaris32AndSolaris64Test.sh index c1b4491a706..c70dd465c3a 100644 --- a/jdk/test/com/sun/jdi/Solaris32AndSolaris64Test.sh +++ b/jdk/test/com/sun/jdi/Solaris32AndSolaris64Test.sh @@ -164,10 +164,10 @@ fi if [ -n "${STANDALONE}" ] ; then #if running standalone, compile the support files ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \ - -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}." \ + -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" \ TestScaffold.java VMConnection.java TargetListener.java TargetAdapter.java ${TESTJAVA}/bin/javac -d ${TESTCLASSES} \ - -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}." -g \ + -classpath "$TESTJAVA/lib/tools.jar${PATHSEP}${TESTSRC}" -g \ FetchLocals.java DataModelTest.java fi diff --git a/jdk/test/com/sun/jdi/VMConnection.java b/jdk/test/com/sun/jdi/VMConnection.java index 5d5f9e13bb6..bc07e034691 100644 --- a/jdk/test/com/sun/jdi/VMConnection.java +++ b/jdk/test/com/sun/jdi/VMConnection.java @@ -57,6 +57,7 @@ class VMConnection { if (testClasses == null) { return retVal; } + retVal += "-classpath " + testClasses + " "; File myFile = new File(testClasses, "@debuggeeVMOptions"); if (!myFile.canRead()) { @@ -97,7 +98,7 @@ class VMConnection { if (line.length() != 0 && !line.startsWith("#")) { System.out.println("-- Added debuggeeVM options from file " + wholePath + ": " + line); - retVal = line; + retVal += line; break; } // Else, read he next line. diff --git a/jdk/test/com/sun/jdi/connect/spi/DebugUsingCustomConnector.java b/jdk/test/com/sun/jdi/connect/spi/DebugUsingCustomConnector.java index d8c939e58c4..3073093f740 100644 --- a/jdk/test/com/sun/jdi/connect/spi/DebugUsingCustomConnector.java +++ b/jdk/test/com/sun/jdi/connect/spi/DebugUsingCustomConnector.java @@ -28,7 +28,7 @@ * This tests launches a debuggee using a custom LaunchingConnector. * * @build DebugUsingCustomConnector SimpleLaunchingConnector Foo NullTransportService - * @run main DebugUsingCustomConnector + * @run main/othervm DebugUsingCustomConnector */ import com.sun.jdi.*; import com.sun.jdi.connect.*; diff --git a/jdk/test/com/sun/jdi/connect/spi/GeneratedConnectors.java b/jdk/test/com/sun/jdi/connect/spi/GeneratedConnectors.java index d4926396ebe..e9dba8332ff 100644 --- a/jdk/test/com/sun/jdi/connect/spi/GeneratedConnectors.java +++ b/jdk/test/com/sun/jdi/connect/spi/GeneratedConnectors.java @@ -31,7 +31,7 @@ * created and that they have an "address" argument. * * @build GeneratedConnectors NullTransportService - * @run main GeneratedConnectors + * @run main/othervm GeneratedConnectors */ import com.sun.jdi.*; diff --git a/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java b/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java index 86154d5091d..858cbc71187 100644 --- a/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java +++ b/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java @@ -147,11 +147,15 @@ public class SimpleLaunchingConnector implements LaunchingConnector { String arch = System.getProperty("os.arch"); if (arch.equals("sparcv9")) { exe += "sparcv9/java"; + } else if (arch.equals("amd64")) { + exe += "amd64/java"; } else { exe += "java"; } String cmd = exe + " -Xdebug -Xrunjdwp:transport=dt_socket,timeout=15000,address=" + - key.address() + "" + className; + key.address() + + " -classpath " + System.getProperty("test.classes") + + " " + className; Process process = Runtime.getRuntime().exec(cmd); Connection conn = ts.accept(key, 30*1000, 9*1000); ts.stopListening(key); diff --git a/jdk/test/com/sun/jdi/redefine/RedefineTest.java b/jdk/test/com/sun/jdi/redefine/RedefineTest.java index e5980d59fd6..809e9db1b84 100644 --- a/jdk/test/com/sun/jdi/redefine/RedefineTest.java +++ b/jdk/test/com/sun/jdi/redefine/RedefineTest.java @@ -34,7 +34,7 @@ * @run build TestScaffold VMConnection TargetListener TargetAdapter * @run compile -g RedefineTest.java * @run shell RedefineSetUp.sh - * @run main RedefineTest + * @run main/othervm RedefineTest */ import com.sun.jdi.*; import com.sun.jdi.event.*; From f2e3043d12a90f5f8e5ce354004c7d4e17380a89 Mon Sep 17 00:00:00 2001 From: Damjan Jovanovic Date: Wed, 25 Nov 2009 21:27:06 +0300 Subject: [PATCH 29/56] 4899516: Transferable has no DataFlavors when dragging from Gnome window to Swing Reviewed-by: uta, dav --- .../sun/awt/datatransfer/DataTransferer.java | 161 +++++++++++++----- .../classes/sun/awt/X11/XDataTransferer.java | 84 +++++++++ jdk/src/solaris/lib/flavormap.properties | 1 + .../sun/awt/windows/WDataTransferer.java | 31 ++++ .../FileListTransferable.java | 58 +++++++ .../InterprocessMessages.java | 27 +++ .../SourceFileListFrame.java | 97 +++++++++++ .../TargetFileListFrame.java | 144 ++++++++++++++++ .../URIListBetweenJVMsTest.html | 25 +++ .../URIListBetweenJVMsTest.java | 158 +++++++++++++++++ .../process/ProcessCommunicator.java | 10 +- 11 files changed, 751 insertions(+), 45 deletions(-) create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/FileListTransferable.java create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/InterprocessMessages.java create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/SourceFileListFrame.java create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/TargetFileListFrame.java create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.html create mode 100644 jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java diff --git a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java index a0853088e42..64ff903ac90 100644 --- a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java +++ b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java @@ -51,6 +51,9 @@ import java.io.Reader; import java.io.SequenceInputStream; import java.io.StringReader; +import java.net.URI; +import java.net.URISyntaxException; + import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; @@ -203,8 +206,6 @@ public abstract class DataTransferer { private static final Map nativeEOLNs = Collections.synchronizedMap(new HashMap()); - private static final byte [] UNICODE_NULL_TERMINATOR = new byte [] {0,0}; - /** * The number of terminating NUL bytes for the Set of textNatives. */ @@ -627,6 +628,14 @@ public abstract class DataTransferer { */ public abstract boolean isImageFormat(long format); + /** + * Determines whether the format is a URI list we can convert to + * a DataFlavor.javaFileListFlavor. + */ + protected boolean isURIListFormat(long format) { + return false; + } + /** * Returns a Map whose keys are all of the possible formats into which the * Transferable's transfer data flavors can be translated. The value of @@ -1299,58 +1308,55 @@ search: if (!DataFlavor.javaFileListFlavor.equals(flavor)) { throw new IOException("data translation failed"); } - final List list = (List)obj; - final ArrayList fileList = new ArrayList(); + final List list = (List)obj; final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents); - int nFiles = 0; - for (int i = 0; i < list.size(); i++) { - Object o = list.get(i); - if (o instanceof File || o instanceof String) { - nFiles++; + final ArrayList fileList = castToFiles(list, userProtectionDomain); + + bos = convertFileListToBytes(fileList); + + + // Target data is a URI list. Source data must be a + // java.util.List which contains java.io.File or String instances. + } else if (isURIListFormat(format)) { + if (!DataFlavor.javaFileListFlavor.equals(flavor)) { + throw new IOException("data translation failed"); + } + String nat = getNativeForFormat(format); + String targetCharset = null; + if (nat != null) { + try { + targetCharset = new DataFlavor(nat).getParameter("charset"); + } catch (ClassNotFoundException cnfe) { + throw new IOException(cnfe); } } - - try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws IOException { - for (Object fileObject : list) - { - File file = castToFile(fileObject); - if (null == System.getSecurityManager() || - !(isFileInWebstartedCache(file) || - isForbiddenToRead(file, userProtectionDomain))) - { - fileList.add(file.getCanonicalPath()); - } - } - return null; - } - }); - } catch (PrivilegedActionException pae) { - throw new IOException(pae.getMessage()); + if (targetCharset == null) { + targetCharset = "UTF-8"; } + final List list = (List)obj; + final ProtectionDomain userProtectionDomain = getUserProtectionDomain(contents); + final ArrayList fileList = castToFiles(list, userProtectionDomain); + final ArrayList uriList = new ArrayList(fileList.size()); + for (String fileObject : fileList) { + final URI uri = new File(fileObject).toURI(); + // Some implementations are fussy about the number of slashes (file:///path/to/file is best) + try { + uriList.add(new URI(uri.getScheme(), "", uri.getPath(), uri.getFragment()).toString()); + } catch (URISyntaxException uriSyntaxException) { + throw new IOException(uriSyntaxException); + } + } - if(fileList.isEmpty()) { - //store empty unicode string (null terminator) - bos.write(UNICODE_NULL_TERMINATOR); - } else { - for (int i = 0; i < fileList.size(); i++) { - byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding()); - //store unicode string with null terminator - bos.write(bytes, 0, bytes.length); - bos.write(UNICODE_NULL_TERMINATOR); - } + byte[] eoln = "\r\n".getBytes(targetCharset); + for (int i = 0; i < uriList.size(); i++) { + byte[] bytes = uriList.get(i).getBytes(targetCharset); + bos.write(bytes, 0, bytes.length); + bos.write(eoln, 0, eoln.length); } - // According to MSDN the byte array have to be double NULL-terminated. - // The array contains Unicode characters, so each NULL-terminator is - // a pair of bytes - - bos.write(UNICODE_NULL_TERMINATOR); - // Source data is an InputStream. For arbitrary flavors, just grab the // bytes and dump them into a byte array. For text flavors, decode back // to a String and recur to reencode according to the requested format. @@ -1398,6 +1404,8 @@ search: return ret; } + protected abstract ByteArrayOutputStream convertFileListToBytes(ArrayList fileList) throws IOException; + private String removeSuspectedData(DataFlavor flavor, final Transferable contents, final String str) throws IOException { @@ -1465,6 +1473,33 @@ search: return true; } + private ArrayList castToFiles(final List files, + final ProtectionDomain userProtectionDomain) throws IOException + { + final ArrayList fileList = new ArrayList(); + try { + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws IOException { + for (Object fileObject : files) + { + File file = castToFile(fileObject); + if (file != null && + (null == System.getSecurityManager() || + !(isFileInWebstartedCache(file) || + isForbiddenToRead(file, userProtectionDomain)))) + { + fileList.add(file.getCanonicalPath()); + } + } + return null; + } + }); + } catch (PrivilegedActionException pae) { + throw new IOException(pae.getMessage()); + } + return fileList; + } + // It is important do not use user's successors // of File class. private File castToFile(Object fileObject) throws IOException { @@ -1473,6 +1508,8 @@ search: filePath = ((File)fileObject).getCanonicalPath(); } else if (fileObject instanceof String) { filePath = (String) fileObject; + } else { + return null; } return new File(filePath); } @@ -1578,6 +1615,29 @@ search: // Turn the list of Files into a List and return return Arrays.asList(files); + // Source data is a URI list. Convert to DataFlavor.javaFileListFlavor + // where possible. + } else if (isURIListFormat(format) && DataFlavor.javaFileListFlavor.equals(flavor)) { + try { + URI uris[] = dragQueryURIs(str, bytes, format, localeTransferable); + if (uris == null) { + return null; + } + ArrayList files = new ArrayList(); + for (URI uri : uris) { + try { + files.add(new File(uri)); + } catch (IllegalArgumentException illegalArg) { + // When converting from URIs to less generic files, + // common practice (Wine, SWT) seems to be to + // silently drop the URIs that aren't local files. + } + } + return files; + } finally { + str.close(); + } + // Target data is a String. Strip terminating NUL bytes. Decode bytes // into characters. Search-and-replace EOLN. } else if (String.class.equals(flavor.getRepresentationClass()) && @@ -1962,6 +2022,19 @@ search: */ protected abstract String[] dragQueryFile(byte[] bytes); + /** + * Decodes URIs from either a byte array or a stream. + */ + protected URI[] dragQueryURIs(InputStream stream, + byte[] bytes, + long format, + Transferable localeTransferable) + throws IOException + { + throw new IOException( + new UnsupportedOperationException("not implemented on this platform")); + } + /** * Translates either a byte array or an input stream which contain * platform-specific image data in the given format into an Image. diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java b/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java index c82f6b11b51..b08eed94dc2 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDataTransferer.java @@ -28,14 +28,21 @@ package sun.awt.X11; import java.awt.Image; import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; +import java.io.BufferedReader; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -48,6 +55,8 @@ import javax.imageio.spi.ImageWriterSpi; import sun.awt.datatransfer.DataTransferer; import sun.awt.datatransfer.ToolkitThreadBlockedHandler; +import java.io.ByteArrayOutputStream; + /** * Platform-specific support for the data transfer subsystem. */ @@ -108,6 +117,22 @@ public class XDataTransferer extends DataTransferer { return super.getCharsetForTextFormat(lFormat); } + protected boolean isURIListFormat(long format) { + String nat = getNativeForFormat(format); + if (nat == null) { + return false; + } + try { + DataFlavor df = new DataFlavor(nat); + if (df.getPrimaryType().equals("text") && df.getSubType().equals("uri-list")) { + return true; + } + } catch (Exception e) { + // Not a MIME format. + } + return false; + } + public boolean isFileFormat(long format) { return format == FILE_NAME_ATOM.getAtom() || format == DT_NET_FILE_ATOM.getAtom(); @@ -170,6 +195,19 @@ public class XDataTransferer extends DataTransferer { } } + protected ByteArrayOutputStream convertFileListToBytes(ArrayList fileList) + throws IOException + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + for (int i = 0; i < fileList.size(); i++) + { + byte[] bytes = fileList.get(i).getBytes(); + if (i != 0) bos.write(0); + bos.write(bytes, 0, bytes.length); + } + return bos; + } + /** * Translates either a byte array or an input stream which contain * platform-specific image data in the given format into an Image. @@ -215,6 +253,52 @@ public class XDataTransferer extends DataTransferer { } } + protected URI[] dragQueryURIs(InputStream stream, + byte[] bytes, + long format, + Transferable localeTransferable) + throws IOException { + + String charset = null; + if (localeTransferable != null && + isLocaleDependentTextFormat(format) && + localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor)) { + try { + charset = new String( + (byte[])localeTransferable.getTransferData(javaTextEncodingFlavor), + "UTF-8" + ); + } catch (UnsupportedFlavorException cannotHappen) { + } + } else { + charset = getCharsetForTextFormat(format); + } + if (charset == null) { + // Only happens when we have a custom text type. + charset = getDefaultTextCharset(); + } + + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(stream, charset)); + String line; + ArrayList uriList = new ArrayList(); + URI uri; + while ((line = reader.readLine()) != null) { + try { + uri = new URI(line); + } catch (URISyntaxException uriSyntaxException) { + throw new IOException(uriSyntaxException); + } + uriList.add(uri); + } + return uriList.toArray(new URI[uriList.size()]); + } finally { + if (reader != null) + reader.close(); + } + } + /** * Returns true if and only if the name of the specified format Atom * constitutes a valid MIME type with the specified primary type. diff --git a/jdk/src/solaris/lib/flavormap.properties b/jdk/src/solaris/lib/flavormap.properties index e96da314c93..223002a69aa 100644 --- a/jdk/src/solaris/lib/flavormap.properties +++ b/jdk/src/solaris/lib/flavormap.properties @@ -73,5 +73,6 @@ UTF8_STRING=text/plain;charset=UTF-8;eoln="\n";terminators=0 TEXT=text/plain;eoln="\n";terminators=0 STRING=text/plain;charset=iso8859-1;eoln="\n";terminators=0 FILE_NAME=application/x-java-file-list;class=java.util.List +text/uri-list=application/x-java-file-list;class=java.util.List PNG=image/x-java-image;class=java.awt.Image JFIF=image/x-java-image;class=java.awt.Image diff --git a/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java b/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java index b996974ff18..ec19fcd1b49 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java @@ -72,6 +72,10 @@ import sun.awt.datatransfer.ToolkitThreadBlockedHandler; import sun.awt.image.ImageRepresentation; import sun.awt.image.ToolkitImage; +import java.util.ArrayList; + +import java.io.ByteArrayOutputStream; + /** * Platform-specific support for the data transfer subsystem. * @@ -342,6 +346,33 @@ public class WDataTransferer extends DataTransferer { return imageDataToPlatformImageBytes(imageData, width, height, format); } + private static final byte [] UNICODE_NULL_TERMINATOR = new byte [] {0,0}; + + protected ByteArrayOutputStream convertFileListToBytes(ArrayList fileList) + throws IOException + { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + if(fileList.isEmpty()) { + //store empty unicode string (null terminator) + bos.write(UNICODE_NULL_TERMINATOR); + } else { + for (int i = 0; i < fileList.size(); i++) { + byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding()); + //store unicode string with null terminator + bos.write(bytes, 0, bytes.length); + bos.write(UNICODE_NULL_TERMINATOR); + } + } + + // According to MSDN the byte array have to be double NULL-terminated. + // The array contains Unicode characters, so each NULL-terminator is + // a pair of bytes + + bos.write(UNICODE_NULL_TERMINATOR); + return bos; + } + /** * Returns a byte array which contains data special for the given format * and for the given image data. diff --git a/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/FileListTransferable.java b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/FileListTransferable.java new file mode 100644 index 00000000000..24cdcb356f0 --- /dev/null +++ b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/FileListTransferable.java @@ -0,0 +1,58 @@ +/* + * 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.awt.datatransfer.Transferable; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.File; +import java.io.IOException; + +class FileListTransferable implements Transferable { + + final private DataFlavor[] supportedFlavors = + {DataFlavor.javaFileListFlavor}; + + private java.util.List list; + + public FileListTransferable(java.util.List list) { + this.list = list; + } + + public DataFlavor[] getTransferDataFlavors() { + return supportedFlavors; + } + + public boolean isDataFlavorSupported(DataFlavor flavor) { + for (DataFlavor df:supportedFlavors) { + if (df.equals(flavor)) return true; + } + return false; + } + + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { + if (flavor.equals(DataFlavor.javaFileListFlavor)) { + return list; + } + throw new UnsupportedFlavorException(flavor); + } +} diff --git a/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/InterprocessMessages.java b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/InterprocessMessages.java new file mode 100644 index 00000000000..c7a3230b5e8 --- /dev/null +++ b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/InterprocessMessages.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +public interface InterprocessMessages { + final static int EXECUTION_IS_SUCCESSFULL = 0; + final static int WRONG_FILES_NUMBER_ON_TARGET = 212; +} diff --git a/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/SourceFileListFrame.java b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/SourceFileListFrame.java new file mode 100644 index 00000000000..aa42c51276f --- /dev/null +++ b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/SourceFileListFrame.java @@ -0,0 +1,97 @@ +/* + * 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 test.java.awt.regtesthelpers.Util; + +import java.awt.*; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.io.File; +import java.util.Arrays; + + +class SourceFileListFrame extends Frame implements DragGestureListener { + + private final static int SOURCE_POINT_SHIFT = 3; + + private List list = new List(URIListBetweenJVMsTest.VISIBLE_RAWS_IN_LIST); + private File[] files; + + SourceFileListFrame() { + super("Source File List Frame"); + extractFilesFromTheWorkingDirectory(); + initList(); + initGUI(); + new DragSource().createDefaultDragGestureRecognizer(list, + DnDConstants.ACTION_COPY,this); + } + + private void extractFilesFromTheWorkingDirectory() { + files = new File(System.getProperty("java.home", "")).listFiles(); + } + + private void initList() { + for (File currFile:files) { + list.add(currFile.getName()); + } + } + + private void initGUI() { + this.addWindowListener(Util.getClosingWindowAdapter()); + this.setLocation(300,250); + this.add(new Panel().add(list)); + this.pack(); + this.setVisible(true); + } + + int getNextLocationX() { + return getX()+getWidth(); + } + + int getNextLocationY() { + return getY(); + } + + int getDragSourcePointX() { + return (int)list.getLocationOnScreen().getX()+(list.getWidth()/2); + } + + int getDragSourcePointY() { + return (int)list.getLocationOnScreen().getY()+ SOURCE_POINT_SHIFT; + } + + int getSourceFilesNumber() { + return files.length; + } + + public void dragGestureRecognized(DragGestureEvent dge) { + String [] filesAsStringArray = list.getItems(); + File [] files = new File[filesAsStringArray.length]; + for (int fileNumber=0; fileNumber fileList = extractListOfFiles(dtde); + for (File file:fileList) { + list.add(file.getName()); + } + + if (fileList.size() != expectationTransferredFilesNumber) + { + System.err.println("ERROR: Expected file number:" + + expectationTransferredFilesNumber + + "; Received file number: " + + fileList.size()); + TargetFileListFrame.this.dispose(); + System.exit(InterprocessMessages.WRONG_FILES_NUMBER_ON_TARGET); + } + + TargetFileListFrame.this.dispose(); + + } + + private java.util.List extractListOfFiles(DropTargetDropEvent dtde) { + BufferedReader reader = null; + ArrayList files = new ArrayList(); + try { + reader = new BufferedReader((Reader)dtde.getTransferable(). + getTransferData(dropFlavor)); + String line; + while ((line = reader.readLine()) != null) { + files.add(new File(new URI(line))); + } + } catch (UnsupportedFlavorException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ignored) { + } + } + } + return files; + } + + Point getDropTargetPoint() { + return new Point((int)list.getLocationOnScreen().getX()+(list.getWidth()/2), + (int)list.getLocationOnScreen().getY()+(list.getHeight()/2)); + } +} diff --git a/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.html b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.html new file mode 100644 index 00000000000..cf5a41c0f3c --- /dev/null +++ b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.html @@ -0,0 +1,25 @@ + + + + DnD of URI-List across JVM + + + +

    URIListBetweenJVMsTest
    Bug ID: 4899516

    + +

    This is an AUTOMATIC test, simply wait for completion

    + + + + diff --git a/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java new file mode 100644 index 00000000000..63775943465 --- /dev/null +++ b/jdk/test/java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java @@ -0,0 +1,158 @@ +/* + * 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 4899516 + @summary Transferable has no DataFlavors when dragging from Gnome window to Swing + @author : area=dnd + @run applet URIListBetweenJVMsTest.html +*/ + +/** + * URIListBetweenJVMsTest.java + * + * summary: Transferable has no DataFlavors when dragging from Gnome window to Swing + */ + +import static java.lang.Thread.sleep; + +import test.java.awt.regtesthelpers.process.ProcessCommunicator; +import test.java.awt.regtesthelpers.process.ProcessResults; +import test.java.awt.regtesthelpers.Util; +import java.applet.Applet; +import java.awt.*; +import java.awt.event.InputEvent; +import java.io.*; + +public class URIListBetweenJVMsTest extends Applet { + + // information related to the test in common + static int VISIBLE_RAWS_IN_LIST=15; + + public void init() { + setLayout(new BorderLayout()); + + }//End init() + + public void start() { + + String toolkit = Toolkit.getDefaultToolkit().getClass().getName(); + if (toolkit.equals("sun.awt.windows.WToolkit")){ + System.out.println("This test is not for the Windows platform. Passed."); + return; + } else { + System.out.println("Toolkit = " + toolkit); + } + + SourceFileListFrame sourceFrame = new SourceFileListFrame(); + + Util.waitForIdle(null); + + String [] args = new String [] { + String.valueOf(sourceFrame.getNextLocationX()), + String.valueOf(sourceFrame.getNextLocationY()), + String.valueOf(sourceFrame.getDragSourcePointX()), + String.valueOf(sourceFrame.getDragSourcePointY()), + String.valueOf(sourceFrame.getSourceFilesNumber()) + }; + + String classpath = System.getProperty("java.class.path"); + ProcessResults processResults = + ProcessCommunicator.executeChildProcess(this.getClass(), classpath, args); + + verifyTestResults(processResults); + + }// start() + + private static void verifyTestResults(ProcessResults processResults) { + if ( InterprocessMessages.WRONG_FILES_NUMBER_ON_TARGET == + processResults.getExitValue()) + { + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target has recieved" + + " wrong number of files."); + } + processResults.verifyStdErr(System.err); + processResults.verifyProcessExitValue(System.err); + processResults.printProcessStandartOutput(System.out); + } + + //We cannot make an instance of the applet without the default constructor + public URIListBetweenJVMsTest () { + super(); + } + + //We need in this constructor to pass frame position between JVMs + public URIListBetweenJVMsTest (Point targetFrameLocation, Point dragSourcePoint, + int transferredFilesNumber) + throws InterruptedException + { + TargetFileListFrame targetFrame = new TargetFileListFrame(targetFrameLocation, + transferredFilesNumber); + + Util.waitForIdle(null); + + final Robot robot = Util.createRobot(); + + robot.mouseMove((int)dragSourcePoint.getX(),(int)dragSourcePoint.getY()); + sleep(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + sleep(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + sleep(100); + + Util.drag(robot, dragSourcePoint, targetFrame.getDropTargetPoint(), + InputEvent.BUTTON1_MASK); + + } + + enum InterprocessArguments { + TARGET_FRAME_X_POSITION_ARGUMENT, + TARGET_FRAME_Y_POSITION_ARGUMENT, + DRAG_SOURCE_POINT_X_ARGUMENT, + DRAG_SOURCE_POINT_Y_ARGUMENT, + FILES_IN_THE_LIST_NUMBER_ARGUMENT; + + int extract (String [] args) { + return Integer.parseInt(args[this.ordinal()]); + } + } + + public static void main (String [] args) { + Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extract(args), + InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extract(args)); + Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extract(args), + InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extract(args)); + int transferredFilesNumber = InterprocessArguments.FILES_IN_THE_LIST_NUMBER_ARGUMENT.extract(args); + + try { + new URIListBetweenJVMsTest(targetFrameLocation, dragSourcePoint, transferredFilesNumber); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + +}// class URIListBetweenJVMsTest diff --git a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java index 820c6cb1803..15f5560cca0 100644 --- a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java +++ b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java @@ -146,7 +146,15 @@ public class ProcessCommunicator { final String classPathArguments, final String [] args) { StringBuilder commandBuilder = new StringBuilder(); - commandBuilder.append(javaPath).append(classPathArguments).append(classToExecute.getName()); + commandBuilder.append(javaPath).append(" "); + commandBuilder.append("-cp ").append(System.getProperty("test.classes", ".")).append(File.pathSeparatorChar); + + if (classPathArguments.trim().length() > 0) { + commandBuilder.append(classPathArguments).append(" "); + } + + commandBuilder.append(" "); + commandBuilder.append(classToExecute.getName()); for (String argument:args) { commandBuilder.append(" ").append(argument); } From a6dd224efda097fed75022dab88e7dfc19ea382c Mon Sep 17 00:00:00 2001 From: Artem Ananiev Date: Fri, 27 Nov 2009 15:26:07 +0300 Subject: [PATCH 30/56] 4913324: Deadlock when using two event queues Reviewed-by: anthony, ant, dcherepanov --- .../classes/java/awt/EventDispatchThread.java | 37 +- .../share/classes/java/awt/EventQueue.java | 347 ++++++++++++------ .../share/classes/sun/awt/AWTAccessor.java | 8 +- jdk/src/share/classes/sun/awt/AppContext.java | 19 +- jdk/src/share/classes/sun/awt/SunToolkit.java | 8 +- .../PushPopDeadlock2/PushPopTest.java | 103 ++++++ 6 files changed, 358 insertions(+), 164 deletions(-) create mode 100644 jdk/test/java/awt/EventQueue/PushPopDeadlock2/PushPopTest.java diff --git a/jdk/src/share/classes/java/awt/EventDispatchThread.java b/jdk/src/share/classes/java/awt/EventDispatchThread.java index e0c46a37d33..f546dc386ab 100644 --- a/jdk/src/share/classes/java/awt/EventDispatchThread.java +++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java @@ -104,11 +104,8 @@ class EventDispatchThread extends Thread { } else { stopEvent.dispatch(); } - synchronized (theQueue) { - if (theQueue.getDispatchThread() == this) { - theQueue.detachDispatchThread(); - } - } + + theQueue.detachDispatchThread(this, false); } public void stopDispatching() { @@ -142,35 +139,7 @@ class EventDispatchThread extends Thread { } }); } finally { - /* - * This synchronized block is to secure that the event dispatch - * thread won't die in the middle of posting a new event to the - * associated event queue. It is important because we notify - * that the event dispatch thread is busy after posting a new event - * to its queue, so the EventQueue.dispatchThread reference must - * be valid at that point. - */ - synchronized (theQueue) { - if (theQueue.getDispatchThread() == this) { - theQueue.detachDispatchThread(); - } - /* - * Event dispatch thread dies in case of an uncaught exception. - * A new event dispatch thread for this queue will be started - * only if a new event is posted to it. In case if no more - * events are posted after this thread died all events that - * currently are in the queue will never be dispatched. - */ - /* - * Fix for 4648733. Check both the associated java event - * queue and the PostEventQueue. - */ - if (theQueue.peekEvent() != null || - !SunToolkit.isPostEventQueueEmpty()) { - theQueue.initDispatchThread(); - } - AWTAutoShutdown.getInstance().notifyThreadFree(this); - } + theQueue.detachDispatchThread(this, true); } } diff --git a/jdk/src/share/classes/java/awt/EventQueue.java b/jdk/src/share/classes/java/awt/EventQueue.java index b5635f4a25c..cf1c364b3aa 100644 --- a/jdk/src/share/classes/java/awt/EventQueue.java +++ b/jdk/src/share/classes/java/awt/EventQueue.java @@ -45,6 +45,9 @@ import sun.awt.SunToolkit; import sun.awt.EventQueueItem; import sun.awt.AWTAccessor; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; + /** * EventQueue is a platform-independent class * that queues events, both from the underlying peer classes @@ -127,6 +130,14 @@ public class EventQueue { */ private EventQueue previousQueue; + /* + * A single lock to synchronize the push()/pop() and related operations with + * all the EventQueues from the AppContext. Synchronization on any particular + * event queue(s) is not enough: we should lock the whole stack. + */ + private final Lock pushPopLock; + private final Condition pushPopCond; + private EventDispatchThread dispatchThread; private final ThreadGroup threadGroup = @@ -158,11 +169,11 @@ public class EventQueue { static { AWTAccessor.setEventQueueAccessor( new AWTAccessor.EventQueueAccessor() { - public EventQueue getNextQueue(EventQueue eventQueue) { - return eventQueue.nextQueue; - } public Thread getDispatchThread(EventQueue eventQueue) { - return eventQueue.dispatchThread; + return eventQueue.getDispatchThread(); + } + public boolean isDispatchThreadImpl(EventQueue eventQueue) { + return eventQueue.isDispatchThreadImpl(); } }); } @@ -179,6 +190,9 @@ public class EventQueue { * may call AppContext.getAppContext() before createNewAppContext() * completes thus causing mess in thread group to appcontext mapping. */ + + pushPopLock = (Lock)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_LOCK_KEY); + pushPopCond = (Condition)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_COND_KEY); } /** @@ -207,7 +221,8 @@ public class EventQueue { */ final void postEventPrivate(AWTEvent theEvent) { theEvent.isPosted = true; - synchronized(this) { + pushPopLock.lock(); + try { if (dispatchThread == null && nextQueue == null) { if (theEvent.getSource() == AWTAutoShutdown.getInstance()) { return; @@ -221,6 +236,8 @@ public class EventQueue { return; } postEvent(theEvent, getPriority(theEvent)); + } finally { + pushPopLock.unlock(); } } @@ -280,9 +297,9 @@ public class EventQueue { if (theEvent.getSource() != AWTAutoShutdown.getInstance()) { AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); } - notifyAll(); + pushPopCond.signalAll(); } else if (notifyID) { - notifyAll(); + pushPopCond.signalAll(); } } else { // The event was not coalesced or has non-Component source. @@ -290,7 +307,7 @@ public class EventQueue { queues[priority].tail.next = newItem; queues[priority].tail = newItem; if (notifyID) { - notifyAll(); + pushPopCond.signalAll(); } } } @@ -482,7 +499,8 @@ public class EventQueue { * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(); - synchronized (this) { + pushPopLock.lock(); + try { for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { if (queues[i].head != null) { EventQueueItem entry = queues[i].head; @@ -495,7 +513,9 @@ public class EventQueue { } } AWTAutoShutdown.getInstance().notifyThreadFree(dispatchThread); - wait(); + pushPopCond.await(); + } finally { + pushPopLock.unlock(); } } while(true); } @@ -508,7 +528,8 @@ public class EventQueue { * event queues are nested with push()/pop(). */ SunToolkit.flushPendingEvents(); - synchronized (this) { + pushPopLock.lock(); + try { for (int i = 0; i < NUM_PRIORITIES; i++) { for (EventQueueItem entry = queues[i].head, prev = null; entry != null; prev = entry, entry = entry.next) @@ -527,9 +548,11 @@ public class EventQueue { } } } - this.waitForID = id; - wait(); - this.waitForID = 0; + waitForID = id; + pushPopCond.await(); + waitForID = 0; + } finally { + pushPopLock.unlock(); } } while(true); } @@ -539,11 +562,16 @@ public class EventQueue { * without removing it. * @return the first event */ - public synchronized AWTEvent peekEvent() { - for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { - if (queues[i].head != null) { - return queues[i].head.event; + public AWTEvent peekEvent() { + pushPopLock.lock(); + try { + for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { + if (queues[i].head != null) { + return queues[i].head.event; + } } + } finally { + pushPopLock.unlock(); } return null; @@ -555,14 +583,19 @@ public class EventQueue { * @return the first event of the specified id or null * if there is no such event */ - public synchronized AWTEvent peekEvent(int id) { - for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { - EventQueueItem q = queues[i].head; - for (; q != null; q = q.next) { - if (q.event.getID() == id) { - return q.event; + public AWTEvent peekEvent(int id) { + pushPopLock.lock(); + try { + for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { + EventQueueItem q = queues[i].head; + for (; q != null; q = q.next) { + if (q.event.getID() == id) { + return q.event; + } } } + } finally { + pushPopLock.unlock(); } return null; @@ -661,17 +694,27 @@ public class EventQueue { public static long getMostRecentEventTime() { return Toolkit.getEventQueue().getMostRecentEventTimeImpl(); } - private synchronized long getMostRecentEventTimeImpl() { - return (Thread.currentThread() == dispatchThread) - ? mostRecentEventTime - : System.currentTimeMillis(); + private long getMostRecentEventTimeImpl() { + pushPopLock.lock(); + try { + return (Thread.currentThread() == dispatchThread) + ? mostRecentEventTime + : System.currentTimeMillis(); + } finally { + pushPopLock.unlock(); + } } /** * @return most recent event time on all threads. */ - synchronized long getMostRecentEventTimeEx() { - return mostRecentEventTime; + long getMostRecentEventTimeEx() { + pushPopLock.lock(); + try { + return mostRecentEventTime; + } finally { + pushPopLock.unlock(); + } } /** @@ -689,10 +732,15 @@ public class EventQueue { public static AWTEvent getCurrentEvent() { return Toolkit.getEventQueue().getCurrentEventImpl(); } - private synchronized AWTEvent getCurrentEventImpl() { - return (Thread.currentThread() == dispatchThread) - ? ((AWTEvent)currentEvent.get()) - : null; + private AWTEvent getCurrentEventImpl() { + pushPopLock.lock(); + try { + return (Thread.currentThread() == dispatchThread) + ? ((AWTEvent)currentEvent.get()) + : null; + } finally { + pushPopLock.unlock(); + } } /** @@ -706,21 +754,22 @@ public class EventQueue { * @throws NullPointerException if newEventQueue is null * @since 1.2 */ - public synchronized void push(EventQueue newEventQueue) { + public void push(EventQueue newEventQueue) { if (eventLog.isLoggable(PlatformLogger.FINE)) { eventLog.fine("EventQueue.push(" + newEventQueue + ")"); } - if (nextQueue != null) { - nextQueue.push(newEventQueue); - return; - } + pushPopLock.lock(); + try { + EventQueue toPush = this; + while (toPush.nextQueue != null) { + toPush = toPush.nextQueue; + } - synchronized (newEventQueue) { // Transfer all events forward to new EventQueue. - while (peekEvent() != null) { + while (toPush.peekEvent() != null) { try { - newEventQueue.postEventPrivate(getNextEvent()); + newEventQueue.postEventPrivate(toPush.getNextEvent()); } catch (InterruptedException ie) { if (eventLog.isLoggable(PlatformLogger.FINE)) { eventLog.fine("Interrupted push", ie); @@ -728,27 +777,30 @@ public class EventQueue { } } - newEventQueue.previousQueue = this; - } - /* - * Stop the event dispatch thread associated with the currently - * active event queue, so that after the new queue is pushed - * on the top this event dispatch thread won't prevent AWT from - * being automatically shut down. - * Use stopDispatchingLater() to avoid deadlock: stopDispatching() - * waits for the dispatch thread to exit, so if the dispatch - * thread attempts to synchronize on this EventQueue object - * it will never exit since we already hold this lock. - */ - if (dispatchThread != null) { - dispatchThread.stopDispatchingLater(); - } + newEventQueue.previousQueue = toPush; - nextQueue = newEventQueue; + /* + * Stop the event dispatch thread associated with the currently + * active event queue, so that after the new queue is pushed + * on the top this event dispatch thread won't prevent AWT from + * being automatically shut down. + * Use stopDispatchingLater() to avoid deadlock: stopDispatching() + * waits for the dispatch thread to exit, which in turn waits + * for the lock in EQ.detachDispatchThread(), which is hold by + * this method. + */ + if (toPush.dispatchThread != null) { + toPush.dispatchThread.stopDispatchingLater(); + } - AppContext appContext = AppContext.getAppContext(); - if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { - appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue); + toPush.nextQueue = newEventQueue; + + AppContext appContext = AppContext.getAppContext(); + if (appContext.get(AppContext.EVENT_QUEUE_KEY) == toPush) { + appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue); + } + } finally { + pushPopLock.unlock(); } } @@ -770,25 +822,24 @@ public class EventQueue { eventLog.fine("EventQueue.pop(" + this + ")"); } - // To prevent deadlock, we lock on the previous EventQueue before - // this one. This uses the same locking order as everything else - // in EventQueue.java, so deadlock isn't possible. - EventQueue prev = previousQueue; - synchronized ((prev != null) ? prev : this) { - synchronized(this) { - if (nextQueue != null) { - nextQueue.pop(); - return; + EventDispatchThread dt = null; + pushPopLock.lock(); + try { + EventQueue toPop = this; + while (toPop.nextQueue != null) { + toPop = toPop.nextQueue; } - if (previousQueue == null) { + EventQueue prev = toPop.previousQueue; + if (prev == null) { throw new EmptyStackException(); } + toPop.previousQueue = null; // Transfer all events back to previous EventQueue. - previousQueue.nextQueue = null; - while (peekEvent() != null) { + prev.nextQueue = null; + while (toPop.peekEvent() != null) { try { - previousQueue.postEventPrivate(getNextEvent()); + prev.postEventPrivate(toPop.getNextEvent()); } catch (InterruptedException ie) { if (eventLog.isLoggable(PlatformLogger.FINE)) { eventLog.fine("Interrupted pop", ie); @@ -797,14 +848,14 @@ public class EventQueue { } AppContext appContext = AppContext.getAppContext(); if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { - appContext.put(AppContext.EVENT_QUEUE_KEY, previousQueue); + appContext.put(AppContext.EVENT_QUEUE_KEY, prev); } - previousQueue = null; - } + dt = toPop.dispatchThread; + } finally { + pushPopLock.unlock(); } - EventDispatchThread dt = this.dispatchThread; if (dt != null) { dt.stopDispatching(); // Must be done outside synchronized // block to avoid possible deadlock @@ -833,16 +884,27 @@ public class EventQueue { */ public static boolean isDispatchThread() { EventQueue eq = Toolkit.getEventQueue(); - EventQueue next = eq.nextQueue; - while (next != null) { - eq = next; - next = eq.nextQueue; + return eq.isDispatchThreadImpl(); + } + + final boolean isDispatchThreadImpl() { + EventQueue eq = this; + pushPopLock.lock(); + try { + EventQueue next = eq.nextQueue; + while (next != null) { + eq = next; + next = eq.nextQueue; + } + return (Thread.currentThread() == eq.dispatchThread); + } finally { + pushPopLock.unlock(); } - return (Thread.currentThread() == eq.dispatchThread); } final void initDispatchThread() { - synchronized (this) { + pushPopLock.lock(); + try { AppContext appContext = AppContext.getAppContext(); if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) { dispatchThread = (EventDispatchThread) @@ -861,11 +923,45 @@ public class EventQueue { AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); dispatchThread.start(); } + } finally { + pushPopLock.unlock(); } } - final void detachDispatchThread() { - dispatchThread = null; + final void detachDispatchThread(EventDispatchThread edt, boolean restart) { + /* + * This synchronized block is to secure that the event dispatch + * thread won't die in the middle of posting a new event to the + * associated event queue. It is important because we notify + * that the event dispatch thread is busy after posting a new event + * to its queue, so the EventQueue.dispatchThread reference must + * be valid at that point. + */ + pushPopLock.lock(); + try { + EventDispatchThread oldDispatchThread = dispatchThread; + if (dispatchThread == edt) { + dispatchThread = null; + } + if (restart) { + /* + * Event dispatch thread dies in case of an uncaught exception. + * A new event dispatch thread for this queue will be started + * only if a new event is posted to it. In case if no more + * events are posted after this thread died all events that + * currently are in the queue will never be dispatched. + * + * Fix for 4648733. Check both the associated java event + * queue and the PostEventQueue. + */ + if ((peekEvent() != null) || !SunToolkit.isPostEventQueueEmpty()) { + initDispatchThread(); + } + AWTAutoShutdown.getInstance().notifyThreadFree(oldDispatchThread); + } + } finally { + pushPopLock.unlock(); + } } /* @@ -878,7 +974,12 @@ public class EventQueue { * @see java.awt.EventQueue#detachDispatchThread */ final EventDispatchThread getDispatchThread() { - return dispatchThread; + pushPopLock.lock(); + try { + return dispatchThread; + } finally { + pushPopLock.unlock(); + } } /* @@ -895,7 +996,8 @@ public class EventQueue { */ final void removeSourceEvents(Object source, boolean removeAllEvents) { SunToolkit.flushPendingEvents(); - synchronized (this) { + pushPopLock.lock(); + try { for (int i = 0; i < NUM_PRIORITIES; i++) { EventQueueItem entry = queues[i].head; EventQueueItem prev = null; @@ -928,43 +1030,49 @@ public class EventQueue { } queues[i].tail = prev; } + } finally { + pushPopLock.unlock(); } } static void setCurrentEventAndMostRecentTime(AWTEvent e) { Toolkit.getEventQueue().setCurrentEventAndMostRecentTimeImpl(e); } - private synchronized void setCurrentEventAndMostRecentTimeImpl(AWTEvent e) - { - if (Thread.currentThread() != dispatchThread) { - return; - } + private void setCurrentEventAndMostRecentTimeImpl(AWTEvent e) { + pushPopLock.lock(); + try { + if (Thread.currentThread() != dispatchThread) { + return; + } - currentEvent = new WeakReference(e); + currentEvent = new WeakReference(e); - // This series of 'instanceof' checks should be replaced with a - // polymorphic type (for example, an interface which declares a - // getWhen() method). However, this would require us to make such - // a type public, or to place it in sun.awt. Both of these approaches - // have been frowned upon. So for now, we hack. - // - // In tiger, we will probably give timestamps to all events, so this - // will no longer be an issue. - long mostRecentEventTime2 = Long.MIN_VALUE; - if (e instanceof InputEvent) { - InputEvent ie = (InputEvent)e; - mostRecentEventTime2 = ie.getWhen(); - } else if (e instanceof InputMethodEvent) { - InputMethodEvent ime = (InputMethodEvent)e; - mostRecentEventTime2 = ime.getWhen(); - } else if (e instanceof ActionEvent) { - ActionEvent ae = (ActionEvent)e; - mostRecentEventTime2 = ae.getWhen(); - } else if (e instanceof InvocationEvent) { - InvocationEvent ie = (InvocationEvent)e; - mostRecentEventTime2 = ie.getWhen(); + // This series of 'instanceof' checks should be replaced with a + // polymorphic type (for example, an interface which declares a + // getWhen() method). However, this would require us to make such + // a type public, or to place it in sun.awt. Both of these approaches + // have been frowned upon. So for now, we hack. + // + // In tiger, we will probably give timestamps to all events, so this + // will no longer be an issue. + long mostRecentEventTime2 = Long.MIN_VALUE; + if (e instanceof InputEvent) { + InputEvent ie = (InputEvent)e; + mostRecentEventTime2 = ie.getWhen(); + } else if (e instanceof InputMethodEvent) { + InputMethodEvent ime = (InputMethodEvent)e; + mostRecentEventTime2 = ime.getWhen(); + } else if (e instanceof ActionEvent) { + ActionEvent ae = (ActionEvent)e; + mostRecentEventTime2 = ae.getWhen(); + } else if (e instanceof InvocationEvent) { + InvocationEvent ie = (InvocationEvent)e; + mostRecentEventTime2 = ie.getWhen(); + } + mostRecentEventTime = Math.max(mostRecentEventTime, mostRecentEventTime2); + } finally { + pushPopLock.unlock(); } - mostRecentEventTime = Math.max(mostRecentEventTime, mostRecentEventTime2); } /** @@ -1045,15 +1153,18 @@ public class EventQueue { * or starts a new one otherwise. */ private void wakeup(boolean isShutdown) { - synchronized(this) { + pushPopLock.lock(); + try { if (nextQueue != null) { // Forward call to the top of EventQueue stack. nextQueue.wakeup(isShutdown); } else if (dispatchThread != null) { - notifyAll(); + pushPopCond.signalAll(); } else if (!isShutdown) { initDispatchThread(); } + } finally { + pushPopLock.unlock(); } } } diff --git a/jdk/src/share/classes/sun/awt/AWTAccessor.java b/jdk/src/share/classes/sun/awt/AWTAccessor.java index c8bbc860877..67eb051003d 100644 --- a/jdk/src/share/classes/sun/awt/AWTAccessor.java +++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java @@ -248,14 +248,14 @@ public final class AWTAccessor { * An accessor for the EventQueue class */ public interface EventQueueAccessor { - /* - * Gets the next event queue. - */ - EventQueue getNextQueue(EventQueue eventQueue); /* * Gets the event dispatch thread. */ Thread getDispatchThread(EventQueue eventQueue); + /* + * Checks if the current thread is EDT for the given EQ. + */ + public boolean isDispatchThreadImpl(EventQueue eventQueue); } /* diff --git a/jdk/src/share/classes/sun/awt/AppContext.java b/jdk/src/share/classes/sun/awt/AppContext.java index 3dcabdc6358..882f0e3fe7c 100644 --- a/jdk/src/share/classes/sun/awt/AppContext.java +++ b/jdk/src/share/classes/sun/awt/AppContext.java @@ -43,6 +43,9 @@ import java.util.HashSet; import java.beans.PropertyChangeSupport; import java.beans.PropertyChangeListener; import sun.util.logging.PlatformLogger; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * The AppContext is a table referenced by ThreadGroup which stores @@ -132,10 +135,17 @@ public final class AppContext { /* Since the contents of an AppContext are unique to each Java * session, this class should never be serialized. */ - /* The key to put()/get() the Java EventQueue into/from the AppContext. + /* + * The key to put()/get() the Java EventQueue into/from the AppContext. */ public static final Object EVENT_QUEUE_KEY = new StringBuffer("EventQueue"); + /* + * The keys to store EventQueue push/pop lock and condition. + */ + public final static Object EVENT_QUEUE_LOCK_KEY = new StringBuilder("EventQueue.Lock"); + public final static Object EVENT_QUEUE_COND_KEY = new StringBuilder("EventQueue.Condition"); + /* A map of AppContexts, referenced by ThreadGroup. */ private static final Map threadGroup2appContext = @@ -244,6 +254,13 @@ public final class AppContext { return Thread.currentThread().getContextClassLoader(); } }); + + // Initialize push/pop lock and its condition to be used by all the + // EventQueues within this AppContext + Lock eventQueuePushPopLock = new ReentrantLock(); + put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock); + Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition(); + put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond); } private static final ThreadLocal threadAppContext = diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index e9bc0450bbd..14f8f9dc2a2 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -722,13 +722,7 @@ public abstract class SunToolkit extends Toolkit EventQueue eq = (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); AWTAccessor.EventQueueAccessor accessor = AWTAccessor.getEventQueueAccessor(); - EventQueue next = accessor.getNextQueue(eq); - while (next != null) { - eq = next; - next = accessor.getNextQueue(eq); - } - - return (Thread.currentThread() == accessor.getDispatchThread(eq)); + return accessor.isDispatchThreadImpl(eq); } public Dimension getScreenSize() { diff --git a/jdk/test/java/awt/EventQueue/PushPopDeadlock2/PushPopTest.java b/jdk/test/java/awt/EventQueue/PushPopDeadlock2/PushPopTest.java new file mode 100644 index 00000000000..dbc30c1f668 --- /dev/null +++ b/jdk/test/java/awt/EventQueue/PushPopDeadlock2/PushPopTest.java @@ -0,0 +1,103 @@ +/* + * 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 4913324 + @author Oleg Sukhodolsky: area=eventqueue + @run main/timeout=30 PushPopTest +*/ + +import java.awt.*; +import java.awt.event.*; +import java.util.EmptyStackException; +import sun.awt.SunToolkit; + +public class PushPopTest { + + public static Frame frame; + public static void main(String[] args) { + frame = new Frame(""); + frame.pack(); + + Runnable dummy = new Runnable() { + public void run() { + System.err.println("Dummy is here."); + } + }; + EventQueue seq = Toolkit.getDefaultToolkit().getSystemEventQueue(); + MyEventQueue1 eq1 = new MyEventQueue1(); + MyEventQueue2 eq2 = new MyEventQueue2(); + EventQueue.invokeLater(dummy); + + seq.push(eq1); + EventQueue.invokeLater(dummy); + + eq1.push(eq2); + EventQueue.invokeLater(dummy); + Runnable runnable = new Runnable() { + public void run() { + System.err.println("Dummy from SunToolkit"); + } + }; + InvocationEvent ie = new InvocationEvent(eq2, runnable, null, false); + System.err.println(ie); + SunToolkit.postEvent(SunToolkit.targetToAppContext(frame), ie); + eq1.pop(); + frame.dispose(); + } +} + +class MyEventQueue1 extends EventQueue { + + public void pop() throws EmptyStackException { + super.pop(); + } +} + +class MyEventQueue2 extends EventQueue { + + protected void pop() throws EmptyStackException { + System.err.println("pop2()"); + Thread.dumpStack(); + try { + EventQueue.invokeAndWait(new Runnable() { + public void run() { + Runnable runnable = new Runnable() { + public void run() { + System.err.println("Dummy from here"); + } + }; + InvocationEvent ie = new InvocationEvent(MyEventQueue2.this, runnable, null, false); + SunToolkit.postEvent(SunToolkit.targetToAppContext(PushPopTest.frame), ie); + postEvent(ie); + } + }); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } catch (java.lang.reflect.InvocationTargetException ie) { + ie.printStackTrace(); + } + super.pop(); + } +} From d7b200bf3590fc145b421447cc01c5236117a127 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Fri, 27 Nov 2009 16:07:32 +0300 Subject: [PATCH 31/56] 6402325: Swing toolbars vs native toolbars on Windows Introduce support for different window types: NORMAL, UTILITY, POPUP Reviewed-by: art, dcherepanov --- jdk/src/share/classes/java/awt/Window.java | 91 +++++++++++++++++++ jdk/src/share/classes/javax/swing/Popup.java | 8 +- jdk/src/share/classes/sun/awt/SunToolkit.java | 8 -- .../classes/sun/awt/X11/InfoWindow.java | 1 + .../classes/sun/awt/X11/XDecoratedPeer.java | 4 +- .../classes/sun/awt/X11/XNETProtocol.java | 7 +- .../solaris/classes/sun/awt/X11/XToolkit.java | 18 ---- .../classes/sun/awt/X11/XTrayIconPeer.java | 6 -- .../classes/sun/awt/X11/XWindowPeer.java | 56 +++++++++++- .../classes/sun/awt/windows/WDialogPeer.java | 7 +- .../classes/sun/awt/windows/WFramePeer.java | 1 + .../classes/sun/awt/windows/WWindowPeer.java | 10 ++ .../windows/native/sun/windows/awt_Dialog.cpp | 2 +- .../windows/native/sun/windows/awt_Window.cpp | 59 ++++++++++++ .../windows/native/sun/windows/awt_Window.h | 17 ++++ .../awt/Window/WindowType/WindowType.java | 61 +++++++++++++ 16 files changed, 308 insertions(+), 48 deletions(-) create mode 100644 jdk/test/java/awt/Window/WindowType/WindowType.java diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index c039a717984..88a196918ed 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -147,6 +147,51 @@ import sun.util.logging.PlatformLogger; */ public class Window extends Container implements Accessible { + /** + * Enumeration of available window types. + * + * A window type defines the generic visual appearance and behavior of a + * top-level window. For example, the type may affect the kind of + * decorations of a decorated {@code Frame} or {@code Dialog} instance. + *

    + * Some platforms may not fully support a certain window type. Depending on + * the level of support, some properties of the window type may be + * disobeyed. + * + * @see #getType + * @see #setType + * @since 1.7 + */ + public static enum Type { + /** + * Represents a normal window. + * + * This is the default type for objects of the {@code Window} class or + * its descendants. Use this type for regular top-level windows. + */ + NORMAL, + + /** + * Represents a utility window. + * + * A utility window is usually a small window such as a toolbar or a + * palette. The native system may render the window with smaller + * title-bar if the window is either a {@code Frame} or a {@code + * Dialog} object, and if it has its decorations enabled. + */ + UTILITY, + + /** + * Represents a popup window. + * + * A popup window is a temporary window such as a drop-down menu or a + * tooltip. On some platforms, windows of that type may be forcibly + * made undecorated even if they are instances of the {@code Frame} or + * {@code Dialog} class, and have decorations enabled. + */ + POPUP + } + /** * This represents the warning message that is * to be displayed in a non secure window. ie : @@ -2717,6 +2762,52 @@ public class Window extends Container implements Accessible { removeFromWindowList(appContext, weakThis); } + /** + * Window type. + * + * Synchronization: ObjectLock + */ + private Type type = Type.NORMAL; + + /** + * Sets the type of the window. + * + * This method can only be called while the window is not displayable. + * + * @throws IllegalComponentStateException if the window + * is displayable. + * @throws IllegalArgumentException if the type is {@code null} + * @see Component#isDisplayable + * @see #getType + * @since 1.7 + */ + public void setType(Type type) { + if (type == null) { + throw new IllegalArgumentException("type should not be null."); + } + synchronized (getTreeLock()) { + if (isDisplayable()) { + throw new IllegalComponentStateException( + "The window is displayable."); + } + synchronized (getObjectLock()) { + this.type = type; + } + } + } + + /** + * Returns the type of the window. + * + * @see #setType + * @since 1.7 + */ + public Type getType() { + synchronized (getObjectLock()) { + return type; + } + } + /** * The window serialized data version. * diff --git a/jdk/src/share/classes/javax/swing/Popup.java b/jdk/src/share/classes/javax/swing/Popup.java index 0d1f2d53f19..bd6e6fff8b5 100644 --- a/jdk/src/share/classes/javax/swing/Popup.java +++ b/jdk/src/share/classes/javax/swing/Popup.java @@ -227,12 +227,8 @@ public class Popup { HeavyWeightWindow(Window parent) { super(parent); setFocusableWindowState(false); - Toolkit tk = Toolkit.getDefaultToolkit(); - if (tk instanceof SunToolkit) { - // all the short-lived windows like Popups should be - // OverrideRedirect on X11 platforms - ((SunToolkit)tk).setOverrideRedirect(this); - } + setType(Window.Type.POPUP); + // Popups are typically transient and most likely won't benefit // from true double buffering. Turn it off here. getRootPane().setUseTrueDoubleBuffering(false); diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index 14f8f9dc2a2..3c7f16dff27 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -800,14 +800,6 @@ public abstract class SunToolkit extends Toolkit } - /** - * Makes the window OverrideRedirect, on X11 platforms. See - * ICCCM specification for more details about OverrideRedirect - * windows. Implemented in XToolkit, no-op in WToolkit. - */ - public void setOverrideRedirect(Window target) { - } - static SoftCache imgCache = new SoftCache(); static synchronized Image getImageFromHash(Toolkit tk, URL url) { diff --git a/jdk/src/solaris/classes/sun/awt/X11/InfoWindow.java b/jdk/src/solaris/classes/sun/awt/X11/InfoWindow.java index d0abaa0a97a..c5deb685813 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/InfoWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/InfoWindow.java @@ -45,6 +45,7 @@ public abstract class InfoWindow extends Window { protected InfoWindow(Frame parent, Color borderColor) { super(parent); + setType(Window.Type.POPUP); container = new Container() { @Override public Insets getInsets() { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java index a855ade0464..be9599ce332 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java @@ -1099,9 +1099,9 @@ abstract class XDecoratedPeer extends XWindowPeer { return false; } + @Override boolean isOverrideRedirect() { -// return false; - return ((XToolkit)Toolkit.getDefaultToolkit()).isOverrideRedirect((Window)target); + return Window.Type.POPUP.equals(getWindowType()); } public boolean requestWindowFocus(long time, boolean timeProvided) { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java index 86252721be5..a06f24ff62d 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java @@ -252,8 +252,11 @@ final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProt XAtom XA_NET_WM_STATE_SKIP_TASKBAR = XAtom.get("_NET_WM_STATE_SKIP_TASKBAR"); XAtom XA_NET_WM_STATE_SKIP_PAGER = XAtom.get("_NET_WM_STATE_SKIP_PAGER"); - XAtom XA_NET_WM_WINDOW_TYPE = XAtom.get("_NET_WM_WINDOW_TYPE"); - XAtom XA_NET_WM_WINDOW_TYPE_DIALOG = XAtom.get("_NET_WM_WINDOW_TYPE_DIALOG"); + public final XAtom XA_NET_WM_WINDOW_TYPE = XAtom.get("_NET_WM_WINDOW_TYPE"); + public final XAtom XA_NET_WM_WINDOW_TYPE_NORMAL = XAtom.get("_NET_WM_WINDOW_TYPE_NORMAL"); + public final XAtom XA_NET_WM_WINDOW_TYPE_DIALOG = XAtom.get("_NET_WM_WINDOW_TYPE_DIALOG"); + public final XAtom XA_NET_WM_WINDOW_TYPE_UTILITY = XAtom.get("_NET_WM_WINDOW_TYPE_UTILITY"); + public final XAtom XA_NET_WM_WINDOW_TYPE_POPUP_MENU = XAtom.get("_NET_WM_WINDOW_TYPE_POPUP_MENU"); XAtom XA_NET_WM_WINDOW_OPACITY = XAtom.get("_NET_WM_WINDOW_OPACITY"); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java index 1103ee6cdb9..f1ec8004264 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -109,11 +109,6 @@ public final class XToolkit extends UNIXToolkit implements Runnable { static int awt_multiclick_time; static boolean securityWarningEnabled; - // WeakSet should be used here, but there is no such class - // in JDK (at least in JDK6 and earlier versions) - private WeakHashMap overrideRedirectWindows = - new WeakHashMap(); - private static int screenWidth = -1, screenHeight = -1; // Dimensions of default screen static long awt_defaultFg; // Pixel private static XMouseInfoPeer xPeer; @@ -1316,19 +1311,6 @@ public final class XToolkit extends UNIXToolkit implements Runnable { } } - @Override - public void setOverrideRedirect(Window target) { - synchronized (overrideRedirectWindows) { - overrideRedirectWindows.put(target, true); - } - } - - public boolean isOverrideRedirect(Window target) { - synchronized (overrideRedirectWindows) { - return overrideRedirectWindows.containsKey(target); - } - } - static void dumpPeers() { if (log.isLoggable(PlatformLogger.FINE)) { log.fine("Mapped windows:"); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java index da4a6b0d43d..64ab4c268b0 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java @@ -483,12 +483,6 @@ public class XTrayIconPeer implements TrayIconPeer, } } - static boolean isTrayIconStuffWindow(Window w) { - return (w instanceof InfoWindow.Tooltip) || - (w instanceof InfoWindow.Balloon) || - (w instanceof XTrayIconEmbeddedFrame); - } - // *************************************** // Special embedded frame for tray icon // *************************************** diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java index b580bda3c8a..b7957dd8f92 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java @@ -53,7 +53,6 @@ import sun.util.logging.PlatformLogger; import sun.awt.AWTAccessor; import sun.awt.ComponentAccessor; import sun.awt.WindowAccessor; -import sun.awt.AWTAccessor; import sun.awt.DisplayChangedListener; import sun.awt.SunToolkit; import sun.awt.X11GraphicsDevice; @@ -106,6 +105,18 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, private boolean isBeforeFirstMapNotify = false; // Is the window (being shown) between // setVisible(true) & handleMapNotify(). + /** + * The type of the window. + * + * The type is supposed to be immutable while the peer object exists. + * The value gets initialized in the preInit() method. + */ + private Window.Type windowType = Window.Type.NORMAL; + + public final Window.Type getWindowType() { + return windowType; + } + // It need to be accessed from XFramePeer. protected Vector toplevelStateListeners = new Vector(); XWindowPeer(XCreateWindowParams params) { @@ -137,6 +148,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, void preInit(XCreateWindowParams params) { target = (Component)params.get(TARGET); + windowType = ((Window)target).getType(); params.put(REPARENTED, Boolean.valueOf(isOverrideRedirect() || isSimpleWindow())); super.preInit(params); @@ -1128,9 +1140,8 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, } boolean isOverrideRedirect() { - return (XWM.getWMID() == XWM.OPENLOOK_WM ? true : false) || - ((XToolkit)Toolkit.getDefaultToolkit()).isOverrideRedirect((Window)target) || - XTrayIconPeer.isTrayIconStuffWindow((Window)target); + return XWM.getWMID() == XWM.OPENLOOK_WM || + Window.Type.POPUP.equals(getWindowType()); } final boolean isOLWMDecorBug() { @@ -1826,12 +1837,49 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, void setActualFocusedWindow(XWindowPeer actualFocusedWindow) { } + /** + * Applies the current window type. + */ + private void applyWindowType() { + XNETProtocol protocol = XWM.getWM().getNETProtocol(); + if (protocol == null) { + return; + } + + XAtom typeAtom = null; + + switch (getWindowType()) + { + case NORMAL: + typeAtom = protocol.XA_NET_WM_WINDOW_TYPE_NORMAL; + break; + case UTILITY: + typeAtom = protocol.XA_NET_WM_WINDOW_TYPE_UTILITY; + break; + case POPUP: + typeAtom = protocol.XA_NET_WM_WINDOW_TYPE_POPUP_MENU; + break; + } + + if (typeAtom != null) { + XAtomList wtype = new XAtomList(); + wtype.add(typeAtom); + protocol.XA_NET_WM_WINDOW_TYPE. + setAtomListProperty(getWindow(), wtype); + } else { + protocol.XA_NET_WM_WINDOW_TYPE. + DeleteProperty(getWindow()); + } + } + + @Override public void xSetVisible(boolean visible) { if (log.isLoggable(PlatformLogger.FINE)) log.fine("Setting visible on " + this + " to " + visible); XToolkit.awtLock(); try { this.visible = visible; if (visible) { + applyWindowType(); XlibWrapper.XMapRaised(XToolkit.getDisplay(), getWindow()); } else { XlibWrapper.XUnmapWindow(XToolkit.getDisplay(), getWindow()); diff --git a/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java b/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java index 4424f1cc813..703edd0fdc5 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java @@ -53,7 +53,12 @@ class WDialogPeer extends WWindowPeer implements DialogPeer { } } - native void create(WComponentPeer parent); + native void createAwtDialog(WComponentPeer parent); + void create(WComponentPeer parent) { + preCreate(parent); + createAwtDialog(parent); + } + native void showModal(); native void endModal(); diff --git a/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java b/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java index 86bde26582b..c89d154132a 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java @@ -136,6 +136,7 @@ class WFramePeer extends WWindowPeer implements FramePeer { native void createAwtFrame(WComponentPeer parent); void create(WComponentPeer parent) { + preCreate(parent); createAwtFrame(parent); } diff --git a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java index 6189738da20..9a39d509f2b 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java @@ -199,7 +199,17 @@ public class WWindowPeer extends WPanelPeer implements WindowPeer, } native void createAwtWindow(WComponentPeer parent); + + private volatile Window.Type windowType = Window.Type.NORMAL; + + // This method must be called for Window, Dialog, and Frame before creating + // the hwnd + void preCreate(WComponentPeer parent) { + windowType = ((Window)target).getType(); + } + void create(WComponentPeer parent) { + preCreate(parent); createAwtWindow(parent); } diff --git a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp index c0637237da4..4d21489d2eb 100644 --- a/jdk/src/windows/native/sun/windows/awt_Dialog.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Dialog.cpp @@ -760,7 +760,7 @@ extern "C" { * Signature: (Lsun/awt/windows/WComponentPeer;)V */ JNIEXPORT void JNICALL -Java_sun_awt_windows_WDialogPeer_create(JNIEnv *env, jobject self, +Java_sun_awt_windows_WDialogPeer_createAwtDialog(JNIEnv *env, jobject self, jobject parent) { TRY; diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp index 8bb5c900219..c03420d3522 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp @@ -163,9 +163,11 @@ jfieldID AwtWindow::sysXID; jfieldID AwtWindow::sysYID; jfieldID AwtWindow::sysWID; jfieldID AwtWindow::sysHID; +jfieldID AwtWindow::windowTypeID; jmethodID AwtWindow::getWarningStringMID; jmethodID AwtWindow::calculateSecurityWarningPositionMID; +jmethodID AwtWindow::windowTypeNameMID; int AwtWindow::ms_instanceCounter = 0; HHOOK AwtWindow::ms_hCBTFilter; @@ -216,6 +218,8 @@ AwtWindow::AwtWindow() { hContentBitmap = NULL; ::InitializeCriticalSection(&contentBitmapCS); + + m_windowType = Type::NORMAL; } AwtWindow::~AwtWindow() @@ -475,6 +479,9 @@ void AwtWindow::CreateHWnd(JNIEnv *env, LPCWSTR title, } env->DeleteLocalRef(target); + InitType(env, peer); + TweakStyle(windowStyle, windowExStyle); + AwtCanvas::CreateHWnd(env, title, windowStyle, windowExStyle, @@ -982,6 +989,50 @@ void AwtWindow::_RepositionSecurityWarning(void* param) delete rsws; } +void AwtWindow::InitType(JNIEnv *env, jobject peer) +{ + jobject type = env->GetObjectField(peer, windowTypeID); + if (type == NULL) { + return; + } + + jstring value = (jstring)env->CallObjectMethod(type, windowTypeNameMID); + if (value == NULL) { + env->DeleteLocalRef(type); + return; + } + + const char* valueNative = env->GetStringUTFChars(value, 0); + if (valueNative == NULL) { + env->DeleteLocalRef(value); + env->DeleteLocalRef(type); + return; + } + + if (strcmp(valueNative, "UTILITY") == 0) { + m_windowType = Type::UTILITY; + } else if (strcmp(valueNative, "POPUP") == 0) { + m_windowType = Type::POPUP; + } + + env->ReleaseStringUTFChars(value, valueNative); + env->DeleteLocalRef(value); + env->DeleteLocalRef(type); +} + +void AwtWindow::TweakStyle(DWORD & style, DWORD & exStyle) +{ + switch (GetType()) { + case Type::UTILITY: + exStyle |= WS_EX_TOOLWINDOW; + break; + case Type::POPUP: + style &= ~WS_OVERLAPPED; + style |= WS_POPUP; + break; + } +} + /* Create a new AwtWindow object and window. */ AwtWindow* AwtWindow::Create(jobject self, jobject parent) { @@ -3008,6 +3059,11 @@ Java_java_awt_Window_initIDs(JNIEnv *env, jclass cls) AwtWindow::calculateSecurityWarningPositionMID = env->GetMethodID(cls, "calculateSecurityWarningPosition", "(DDDD)Ljava/awt/geom/Point2D;"); + jclass windowTypeClass = env->FindClass("java/awt/Window$Type"); + AwtWindow::windowTypeNameMID = + env->GetMethodID(windowTypeClass, "name", "()Ljava/lang/String;"); + env->DeleteLocalRef(windowTypeClass); + CATCH_BAD_ALLOC; } @@ -3035,6 +3091,9 @@ Java_sun_awt_windows_WWindowPeer_initIDs(JNIEnv *env, jclass cls) AwtWindow::sysWID = env->GetFieldID(cls, "sysW", "I"); AwtWindow::sysHID = env->GetFieldID(cls, "sysH", "I"); + AwtWindow::windowTypeID = env->GetFieldID(cls, "windowType", + "Ljava/awt/Window$Type;"); + CATCH_BAD_ALLOC; } diff --git a/jdk/src/windows/native/sun/windows/awt_Window.h b/jdk/src/windows/native/sun/windows/awt_Window.h index 001062835e3..fa611b481c7 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.h +++ b/jdk/src/windows/native/sun/windows/awt_Window.h @@ -63,8 +63,11 @@ public: static jfieldID sysWID; static jfieldID sysHID; + static jfieldID windowTypeID; + static jmethodID getWarningStringMID; static jmethodID calculateSecurityWarningPositionMID; + static jmethodID windowTypeNameMID; AwtWindow(); virtual ~AwtWindow(); @@ -362,10 +365,24 @@ protected: void EnableTranslucency(BOOL enable); + // Native representation of the java.awt.Window.Type enum + enum Type { + NORMAL, UTILITY, POPUP + }; + + inline Type GetType() { return m_windowType; } + private: int m_screenNum; void InitOwner(AwtWindow *owner); + + Type m_windowType; + void InitType(JNIEnv *env, jobject peer); + + // Tweak the style according to the type of the window + void TweakStyle(DWORD & style, DWORD & exStyle); + }; #endif /* AWT_WINDOW_H */ diff --git a/jdk/test/java/awt/Window/WindowType/WindowType.java b/jdk/test/java/awt/Window/WindowType/WindowType.java new file mode 100644 index 00000000000..9f277973fa5 --- /dev/null +++ b/jdk/test/java/awt/Window/WindowType/WindowType.java @@ -0,0 +1,61 @@ +/* + * 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 6402325 + @summary Test showing windows of different types + @author anthony.petrov@sun.com: area=awt.toplevel + @library ../../regtesthelpers + @build Util + @run main WindowType +*/ + +import java.awt.*; +import test.java.awt.regtesthelpers.Util; + +/** + * WindowType.java + * Summary: Test showing windows of different types. + */ +public class WindowType { + private static void test(Window window, Window.Type type) { + window.setType(type); + + window.setVisible(true); + Util.waitForIdle(null); + window.setVisible(false); + } + + private static void test(Window.Type type) { + test(new Window((Frame)null), type); + test(new Frame(), type); + test(new Dialog((Frame)null), type); + } + + public static void main(String[] args) { + test(Window.Type.NORMAL); + test(Window.Type.UTILITY); + test(Window.Type.POPUP); + } +} From cd8f275bdbf2f52a32d1c0923959c7401bd8408b Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Mon, 30 Nov 2009 14:15:15 -0800 Subject: [PATCH 32/56] 6903197: Some java template files need to be renamed to .java.template Reviewed-by: alanb --- jdk/make/java/java/Makefile | 2 +- jdk/make/java/java/genlocales.gmk | 2 +- jdk/make/java/java/localegen.sh | 2 +- jdk/make/java/nio/Makefile | 2 +- jdk/make/netbeans/README | 2 +- jdk/make/sun/nio/Makefile | 4 +++- .../{DoubleByte-X.java => DoubleByte-X.java.template} | 0 .../{SingleByte-X.java => SingleByte-X.java.template} | 0 .../tools/src/build/tools/charsetmapping/GenerateDBCS.java | 2 +- .../tools/src/build/tools/charsetmapping/GenerateSBCS.java | 2 +- ...ava => CoreResourceBundleControl-XLocales.java.template} | 0 ...cales.java => LocaleDataMetaInfo-XLocales.java.template} | 0 .../util/Formatter/{Basic-X.java => Basic-X.java.template} | 0 jdk/test/java/util/Formatter/genBasic.sh | 6 +++--- 14 files changed, 13 insertions(+), 11 deletions(-) rename jdk/make/tools/CharsetMapping/{DoubleByte-X.java => DoubleByte-X.java.template} (100%) rename jdk/make/tools/CharsetMapping/{SingleByte-X.java => SingleByte-X.java.template} (100%) rename jdk/src/share/classes/sun/util/{CoreResourceBundleControl-XLocales.java => CoreResourceBundleControl-XLocales.java.template} (100%) rename jdk/src/share/classes/sun/util/{LocaleDataMetaInfo-XLocales.java => LocaleDataMetaInfo-XLocales.java.template} (100%) rename jdk/test/java/util/Formatter/{Basic-X.java => Basic-X.java.template} (100%) diff --git a/jdk/make/java/java/Makefile b/jdk/make/java/java/Makefile index 8755a4c3a6e..b0e40530f4e 100644 --- a/jdk/make/java/java/Makefile +++ b/jdk/make/java/java/Makefile @@ -390,7 +390,7 @@ clean:: LOCALES_GEN_SH = localelist.sh $(GENSRCDIR)/sun/util/CoreResourceBundleControl.java: \ - $(SHARE_SRC)/classes/sun/util/CoreResourceBundleControl-XLocales.java $(LOCALES_GEN_SH) + $(SHARE_SRC)/classes/sun/util/CoreResourceBundleControl-XLocales.java.template $(LOCALES_GEN_SH) @$(prep-target) NAWK="$(NAWK)" SED="$(SED)" $(SH) $(LOCALES_GEN_SH) "$(JRE_NONEXIST_LOCALES)" \ $< $@ diff --git a/jdk/make/java/java/genlocales.gmk b/jdk/make/java/java/genlocales.gmk index bda003b9ce1..3adb769490d 100644 --- a/jdk/make/java/java/genlocales.gmk +++ b/jdk/make/java/java/genlocales.gmk @@ -68,7 +68,7 @@ NonEuro_Resources_properties := $(FILES_compiled_properties) FILES_java := $(FILES_java_orig) FILES_compiled_properties := $(FILES_compiled_properties_orig) -LocaleDataMetaInfo_Src=$(SHARE_SRC)/classes/sun/util/LocaleDataMetaInfo-XLocales.java +LocaleDataMetaInfo_Src=$(SHARE_SRC)/classes/sun/util/LocaleDataMetaInfo-XLocales.java.template LocaleDataMetaInfo_Dest=$(GENSRCDIR)/sun/util/LocaleDataMetaInfo.java LOCALEGEN_SH=localegen.sh RESOURCE_NAMES="FormatData CollationData TimeZoneNames LocaleNames CurrencyNames CalendarData" diff --git a/jdk/make/java/java/localegen.sh b/jdk/make/java/java/localegen.sh index 8f79eaebb88..a21c515dc1a 100644 --- a/jdk/make/java/java/localegen.sh +++ b/jdk/make/java/java/localegen.sh @@ -27,7 +27,7 @@ # # This script is to generate the supported locale list string and replace the -# LocaleDataMetaInfo-XLocales.java in /src/share/classes/sun/util +# LocaleDataMetaInfo-XLocales.java.template in /src/share/classes/sun/util # # SORT, NAWK & SED is passed in as environment variables. # diff --git a/jdk/make/java/nio/Makefile b/jdk/make/java/nio/Makefile index e0cb40839e8..455d7529f67 100644 --- a/jdk/make/java/nio/Makefile +++ b/jdk/make/java/nio/Makefile @@ -834,7 +834,7 @@ $(SCH_GEN)/SocketOptionRegistry.java: $(GENSOR_EXE) GENCSSRC = $(BUILDDIR)/tools/CharsetMapping CHARSETMAPPING_JARFILE = $(BUILDTOOLJARDIR)/charsetmapping.jar -$(FILES_gensbcs_out): $(GENCSSRC)/SingleByte-X.java $(GENCSSRC)/sbcs +$(FILES_gensbcs_out): $(GENCSSRC)/SingleByte-X.java.template $(GENCSSRC)/sbcs @$(prep-target) $(BOOT_JAVA_CMD) -jar $(CHARSETMAPPING_JARFILE) $(GENCSSRC) $(SCS_GEN) sbcs diff --git a/jdk/make/netbeans/README b/jdk/make/netbeans/README index 9c713190034..8f68dce0ee5 100644 --- a/jdk/make/netbeans/README +++ b/jdk/make/netbeans/README @@ -411,7 +411,7 @@ Creating your own NetBeans project java/util/regex/,\ java/util/spi/,\ java/util/zip/,\ - **/*-XLocales.java + **/*-XLocales.java.template jtreg.tests=\ java/util/**/*Collection/ \ java/util/**/*Map/ \ diff --git a/jdk/make/sun/nio/Makefile b/jdk/make/sun/nio/Makefile index e83c6f1f36d..4b46a1fb76d 100644 --- a/jdk/make/sun/nio/Makefile +++ b/jdk/make/sun/nio/Makefile @@ -82,7 +82,9 @@ $(FILES_DAT): $(FILES_MAP) $(FILES_MAP) $(FILES_DAT) sjis0213 -$(FILES_genout_extcs): $(GENCSDATASRC)/SingleByte-X.java $(GENCSDATASRC)/DoubleByte-X.java \ +$(FILES_genout_extcs): \ + $(GENCSDATASRC)/SingleByte-X.java.template \ + $(GENCSDATASRC)/DoubleByte-X.java.template \ $(GENCSDATASRC)/extsbcs $(GENCSDATASRC)/dbcs @$(prep-target) $(RM) -r $(GENCSEXT) diff --git a/jdk/make/tools/CharsetMapping/DoubleByte-X.java b/jdk/make/tools/CharsetMapping/DoubleByte-X.java.template similarity index 100% rename from jdk/make/tools/CharsetMapping/DoubleByte-X.java rename to jdk/make/tools/CharsetMapping/DoubleByte-X.java.template diff --git a/jdk/make/tools/CharsetMapping/SingleByte-X.java b/jdk/make/tools/CharsetMapping/SingleByte-X.java.template similarity index 100% rename from jdk/make/tools/CharsetMapping/SingleByte-X.java rename to jdk/make/tools/CharsetMapping/SingleByte-X.java.template diff --git a/jdk/make/tools/src/build/tools/charsetmapping/GenerateDBCS.java b/jdk/make/tools/src/build/tools/charsetmapping/GenerateDBCS.java index f38e759c456..27dc8719b95 100644 --- a/jdk/make/tools/src/build/tools/charsetmapping/GenerateDBCS.java +++ b/jdk/make/tools/src/build/tools/charsetmapping/GenerateDBCS.java @@ -63,7 +63,7 @@ public class GenerateDBCS { int b2Min = toInteger(fields[8]); int b2Max = toInteger(fields[9]); System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName); - genClass(args[0], args[1], "DoubleByte-X.java", + genClass(args[0], args[1], "DoubleByte-X.java.template", clzName, csName, hisName, pkgName, isASCII, type, b1Min, b1Max, b2Min, b2Max); diff --git a/jdk/make/tools/src/build/tools/charsetmapping/GenerateSBCS.java b/jdk/make/tools/src/build/tools/charsetmapping/GenerateSBCS.java index 8a57a6521bc..cb6496e0a99 100644 --- a/jdk/make/tools/src/build/tools/charsetmapping/GenerateSBCS.java +++ b/jdk/make/tools/src/build/tools/charsetmapping/GenerateSBCS.java @@ -55,7 +55,7 @@ public class GenerateSBCS { String pkgName = fields[4]; System.out.printf("%s,%s,%s,%b,%s%n", clzName, csName, hisName, isASCII, pkgName); - genClass(args[0], args[1], "SingleByte-X.java", + genClass(args[0], args[1], "SingleByte-X.java.template", clzName, csName, hisName, pkgName, isASCII); } } diff --git a/jdk/src/share/classes/sun/util/CoreResourceBundleControl-XLocales.java b/jdk/src/share/classes/sun/util/CoreResourceBundleControl-XLocales.java.template similarity index 100% rename from jdk/src/share/classes/sun/util/CoreResourceBundleControl-XLocales.java rename to jdk/src/share/classes/sun/util/CoreResourceBundleControl-XLocales.java.template diff --git a/jdk/src/share/classes/sun/util/LocaleDataMetaInfo-XLocales.java b/jdk/src/share/classes/sun/util/LocaleDataMetaInfo-XLocales.java.template similarity index 100% rename from jdk/src/share/classes/sun/util/LocaleDataMetaInfo-XLocales.java rename to jdk/src/share/classes/sun/util/LocaleDataMetaInfo-XLocales.java.template diff --git a/jdk/test/java/util/Formatter/Basic-X.java b/jdk/test/java/util/Formatter/Basic-X.java.template similarity index 100% rename from jdk/test/java/util/Formatter/Basic-X.java rename to jdk/test/java/util/Formatter/Basic-X.java.template diff --git a/jdk/test/java/util/Formatter/genBasic.sh b/jdk/test/java/util/Formatter/genBasic.sh index 2c352ad39cf..819afe7cd39 100644 --- a/jdk/test/java/util/Formatter/genBasic.sh +++ b/jdk/test/java/util/Formatter/genBasic.sh @@ -27,10 +27,10 @@ javac -d . ../../../../make/tools/src/build/tools/spp/Spp.java gen() { # if [ $3 = "true" ] -# then $SPP -K$1 -Dtype=$1 -DType=$2 -KprimBasic$2.java -# else $SPP -K$1 -Dtype=$1 -DType=$2 -K$3 Basic$2.java +# then $SPP -K$1 -Dtype=$1 -DType=$2 -KprimBasic$2.java +# else $SPP -K$1 -Dtype=$1 -DType=$2 -K$3 Basic$2.java # fi - java build.tools.spp.Spp -K$1 -Dtype=$1 -DType=$2 -K$3 -K$4 -K$5 -K$6 Basic$2.java + java build.tools.spp.Spp -K$1 -Dtype=$1 -DType=$2 -K$3 -K$4 -K$5 -K$6 Basic$2.java } gen boolean Boolean prim "" "" "" From 2bea841cbea6fef0142db1fb19ee2f1a83610039 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Mon, 30 Nov 2009 14:39:35 -0800 Subject: [PATCH 33/56] 6904962: GlyphVector.getVisualBounds should not be affected by leading or trailing white space Reviewed-by: igor, dougfelt --- .../classes/sun/font/StandardGlyphVector.java | 32 +++++++-- .../awt/font/GlyphVector/VisualBounds.java | 66 +++++++++++++++++++ 2 files changed, 91 insertions(+), 7 deletions(-) create mode 100644 jdk/test/java/awt/font/GlyphVector/VisualBounds.java diff --git a/jdk/src/share/classes/sun/font/StandardGlyphVector.java b/jdk/src/share/classes/sun/font/StandardGlyphVector.java index 347a44b88b7..9d26d91e444 100644 --- a/jdk/src/share/classes/sun/font/StandardGlyphVector.java +++ b/jdk/src/share/classes/sun/font/StandardGlyphVector.java @@ -396,12 +396,19 @@ public class StandardGlyphVector extends GlyphVector { // !!! not cached, assume TextLayout will cache if necessary public Rectangle2D getVisualBounds() { - if (glyphs.length == 0) { - return new Rectangle2D.Float(0, 0, 0, 0); + Rectangle2D result = null; + for (int i = 0; i < glyphs.length; ++i) { + Rectangle2D glyphVB = getGlyphVisualBounds(i).getBounds2D(); + if (!glyphVB.isEmpty()) { + if (result == null) { + result = glyphVB; + } else { + Rectangle2D.union(result, glyphVB, result); + } + } } - Rectangle2D result = getGlyphVisualBounds(0).getBounds2D(); - for (int i = 1; i < glyphs.length; ++i) { - Rectangle2D.union(result, getGlyphVisualBounds(i).getBounds2D(), result); + if (result == null) { + result = new Rectangle2D.Float(0, 0, 0, 0); } return result; } @@ -1787,8 +1794,19 @@ public class StandardGlyphVector extends GlyphVector { gp.transform(sgv.invdtx); result = gp.getBounds2D(); } - result.setRect(result.getMinX() + x + dx, result.getMinY() + y + dy, - result.getWidth(), result.getHeight()); + /* Since x is the logical advance of the glyph to this point. + * Because of the way that Rectangle.union is specified, this + * means that subsequent unioning of a rect including that + * will be affected, even if the glyph is empty. So skip such + * cases. This alone isn't a complete solution since x==0 + * may also not be what is wanted. The code that does the + * unioning also needs to be aware to ignore empty glyphs. + */ + if (!result.isEmpty()) { + result.setRect(result.getMinX() + x + dx, + result.getMinY() + y + dy, + result.getWidth(), result.getHeight()); + } return result; } diff --git a/jdk/test/java/awt/font/GlyphVector/VisualBounds.java b/jdk/test/java/awt/font/GlyphVector/VisualBounds.java new file mode 100644 index 00000000000..1af3631b1ee --- /dev/null +++ b/jdk/test/java/awt/font/GlyphVector/VisualBounds.java @@ -0,0 +1,66 @@ +/* + * 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 + * @summary leading and trailing spaces must not affect visual bounds + * @bug 6904962 + */ + + +import java.awt.*; +import java.awt.font.*; +import java.awt.geom.*; + +public class VisualBounds { + + public static void main(String args[]) { + + String s1 = "a"; + String s2 = s1+" "; + String s3 = " "+s1; + Font f = new Font("Dialog", Font.PLAIN, 12); + FontRenderContext frc = new FontRenderContext(null, false, false); + GlyphVector gv1 = f.createGlyphVector(frc, s1); + GlyphVector gv2 = f.createGlyphVector(frc, s2); + GlyphVector gv3 = f.createGlyphVector(frc, s3); + Rectangle2D bds1 = gv1.getVisualBounds(); + Rectangle2D bds2 = gv2.getVisualBounds(); + Rectangle2D bds3 = gv3.getVisualBounds(); + GlyphVector gv4 = f.createGlyphVector(frc, " "); + Rectangle2D bds4 = gv4.getVisualBounds(); + System.out.println(bds1); + System.out.println(bds2); + System.out.println(bds3); + System.out.println(bds4); + + if (!bds1.equals(bds2)) { + throw new RuntimeException("Trailing space: Visual bounds differ"); + } + if (bds2.getWidth() != bds3.getWidth()) { + throw new RuntimeException("Leading space: Visual widths differ"); + } + if (!bds4.isEmpty()) { + throw new RuntimeException("Non empty bounds for space"); + } + } +} From 0ce235a4da5c391c8ad9337b7f88896335e4dd1d Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Tue, 1 Dec 2009 08:51:16 -0800 Subject: [PATCH 34/56] 6905705: Fix broken exit code values in jdk/test/Makefile Reviewed-by: tbell --- jdk/test/Makefile | 27 ++++++++++++++----- jdk/test/ProblemList.txt | 12 +++++++++ jdk/test/com/sun/jdi/BadHandshakeTest.java | 5 ++-- jdk/test/com/sun/jdi/DoubleAgentTest.java | 5 ++-- jdk/test/com/sun/jdi/ExclusiveBind.java | 5 ++-- jdk/test/com/sun/jdi/RunToExit.java | 5 ++-- .../connect/spi/SimpleLaunchingConnector.java | 5 ++-- 7 files changed, 48 insertions(+), 16 deletions(-) diff --git a/jdk/test/Makefile b/jdk/test/Makefile index b6fee3c59e2..25f0dc1ed6f 100644 --- a/jdk/test/Makefile +++ b/jdk/test/Makefile @@ -282,11 +282,23 @@ STATS_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/$(STATS_TXT_NAME) RUNLIST = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/runlist.txt PASSLIST = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/passlist.txt FAILLIST = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/faillist.txt +EXITCODE = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/exitcode.txt + +TESTEXIT = \ + if [ ! -s $(EXITCODE) ] ; then \ + $(ECHO) "ERROR: EXITCODE file not filled in."; \ + $(ECHO) "1" > $(EXITCODE); \ + fi ; \ + testExitCode=`$(CAT) $(EXITCODE)`; \ + $(ECHO) "EXIT CODE: $${testExitCode}"; \ + exit ${testExitCode} + BUNDLE_UP_AND_EXIT = \ ( \ - exitCode=$$? && \ + jtregExitCode=$$? && \ _summary="$(SUMMARY_TXT)"; \ - $(RM) -f $(STATS_TXT) $(RUNLIST) $(PASSLIST) $(FAILLIST); \ + $(RM) -f $(STATS_TXT) $(RUNLIST) $(PASSLIST) $(FAILLIST) $(EXITCODE); \ + $(ECHO) "$${jtregExitCode}" > $(EXITCODE); \ if [ -r "$${_summary}" ] ; then \ $(ECHO) "Summary: $${_summary}" > $(STATS_TXT); \ $(EXPAND) $${_summary} | $(EGREP) -v ' Not run\.' > $(RUNLIST); \ @@ -297,10 +309,13 @@ BUNDLE_UP_AND_EXIT = \ $(EGREP) ' Error\.' $(RUNLIST); \ $(EGREP) -v ' Passed\.' $(RUNLIST) ) \ | $(SORT) | $(UNIQ) > $(FAILLIST); \ - if [ $${exitCode} != 0 -o -s $(FAILLIST) ] ; then \ + if [ $${jtregExitCode} != 0 -o -s $(FAILLIST) ] ; then \ $(EXPAND) $(FAILLIST) \ | $(CUT) -d' ' -f1 \ | $(SED) -e 's@^@FAILED: @' >> $(STATS_TXT); \ + if [ $${jtregExitCode} = 0 ] ; then \ + jtregExitCode=1; \ + fi; \ fi; \ runc="`$(CAT) $(RUNLIST) | $(WC) -l | $(AWK) '{print $$1;}'`"; \ passc="`$(CAT) $(PASSLIST) | $(WC) -l | $(AWK) '{print $$1;}'`"; \ @@ -312,8 +327,8 @@ BUNDLE_UP_AND_EXIT = \ $(ECHO) "Missing file: $${_summary}" >> $(STATS_TXT); \ fi; \ $(CAT) $(STATS_TXT); \ - $(ZIP_UP_RESULTS) && $(KILL_DISPLAY) && \ - exit $${exitCode} \ + $(ZIP_UP_RESULTS) && $(KILL_DISPLAY) ; \ + $(TESTEXIT) \ ) ################################################################ @@ -598,7 +613,7 @@ jtreg_tests: prep $(PRODUCT_HOME) $(JTREG) $(EXCLUDELIST) $(JTREG_TEST_OPTIONS) \ $(TESTDIRS) \ ) ; $(BUNDLE_UP_AND_EXIT) \ - ) 2>&1 | $(TEE) $(ABS_TEST_OUTPUT_DIR)/output.txt + ) 2>&1 | $(TEE) $(ABS_TEST_OUTPUT_DIR)/output.txt ; $(TESTEXIT) PHONY_LIST += jtreg_tests diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 1867d67a218..f145a246fc7 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -893,6 +893,10 @@ java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java generic-all # jdk_security +# Fails on OpenSolaris, IOException: Attempt to obtain kerberos service ticket +# for host/`hostname`@RABBIT.HOLE failed! +sun/security/krb5/auto/SSL.java generic-all + # Run too slow on Solaris 10 sparc sun/security/ssl/com/sun/net/ssl/internal/ssl/InputRecord/SSLSocketTimeoutNulls.java solaris-sparc sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/ClientTimeout.java solaris-sparc @@ -1099,6 +1103,14 @@ sun/tools/jps/jps-lm.sh generic-all sun/tools/jps/jps-Vvml_2.sh generic-all sun/tools/jps/jps-m_2.sh generic-all +# Fails on OpenSolaris "Could not synchronize with target" +sun/tools/jps/jps-Defaults.sh generic-all +sun/tools/jps/jps-V_2.sh generic-all +sun/tools/jps/jps-Vm_2.sh generic-all +sun/tools/jps/jps-Vvm.sh generic-all +sun/tools/jps/jps-Vvml.sh generic-all +sun/tools/jps/jps-m.sh generic-all + # Server name error, port 2098 problem? sun/tools/jstatd/jstatdServerName.sh generic-all diff --git a/jdk/test/com/sun/jdi/BadHandshakeTest.java b/jdk/test/com/sun/jdi/BadHandshakeTest.java index 6601b427230..e03aeb1001c 100644 --- a/jdk/test/com/sun/jdi/BadHandshakeTest.java +++ b/jdk/test/com/sun/jdi/BadHandshakeTest.java @@ -110,9 +110,10 @@ public class BadHandshakeTest { String exe = System.getProperty("java.home") + File.separator + "bin" + File.separator; String arch = System.getProperty("os.arch"); - if (arch.equals("sparcv9")) { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS") && arch.equals("sparcv9")) { exe += "sparcv9/java"; - } else if (arch.equals("amd64")) { + } else if (osname.equals("SunOS") && arch.equals("amd64")) { exe += "amd64/java"; } else { exe += "java"; diff --git a/jdk/test/com/sun/jdi/DoubleAgentTest.java b/jdk/test/com/sun/jdi/DoubleAgentTest.java index f76b17c154e..bb06b89b9e2 100644 --- a/jdk/test/com/sun/jdi/DoubleAgentTest.java +++ b/jdk/test/com/sun/jdi/DoubleAgentTest.java @@ -92,9 +92,10 @@ public class DoubleAgentTest { String exe = System.getProperty("java.home") + File.separator + "bin" + File.separator; String arch = System.getProperty("os.arch"); - if (arch.equals("sparcv9")) { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS") && arch.equals("sparcv9")) { exe += "sparcv9/java"; - } else if (arch.equals("amd64")) { + } else if (osname.equals("SunOS") && arch.equals("amd64")) { exe += "amd64/java"; } else { exe += "java"; diff --git a/jdk/test/com/sun/jdi/ExclusiveBind.java b/jdk/test/com/sun/jdi/ExclusiveBind.java index 0f56d072e2d..c3690e62e40 100644 --- a/jdk/test/com/sun/jdi/ExclusiveBind.java +++ b/jdk/test/com/sun/jdi/ExclusiveBind.java @@ -99,9 +99,10 @@ public class ExclusiveBind { String exe = System.getProperty("java.home") + File.separator + "bin" + File.separator; String arch = System.getProperty("os.arch"); - if (arch.equals("sparcv9")) { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS") && arch.equals("sparcv9")) { exe += "sparcv9/java"; - } else if (arch.equals("amd64")) { + } else if (osname.equals("SunOS") && arch.equals("amd64")) { exe += "amd64/java"; } else { exe += "java"; diff --git a/jdk/test/com/sun/jdi/RunToExit.java b/jdk/test/com/sun/jdi/RunToExit.java index 9495e451669..c5f11f724a2 100644 --- a/jdk/test/com/sun/jdi/RunToExit.java +++ b/jdk/test/com/sun/jdi/RunToExit.java @@ -115,9 +115,10 @@ public class RunToExit { String exe = System.getProperty("java.home") + File.separator + "bin" + File.separator; String arch = System.getProperty("os.arch"); - if (arch.equals("sparcv9")) { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS") && arch.equals("sparcv9")) { exe += "sparcv9/java"; - } else if (arch.equals("amd64")) { + } else if (osname.equals("SunOS") && arch.equals("amd64")) { exe += "amd64/java"; } else { exe += "java"; diff --git a/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java b/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java index 858cbc71187..82bc3b07b96 100644 --- a/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java +++ b/jdk/test/com/sun/jdi/connect/spi/SimpleLaunchingConnector.java @@ -145,9 +145,10 @@ public class SimpleLaunchingConnector implements LaunchingConnector { String exe = System.getProperty("java.home") + File.separator + "bin" + File.separator; String arch = System.getProperty("os.arch"); - if (arch.equals("sparcv9")) { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS") && arch.equals("sparcv9")) { exe += "sparcv9/java"; - } else if (arch.equals("amd64")) { + } else if (osname.equals("SunOS") && arch.equals("amd64")) { exe += "amd64/java"; } else { exe += "java"; From 44e0bda21c99ae211cf72b568e59e5009d420b97 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Wed, 2 Dec 2009 14:51:39 +0300 Subject: [PATCH 35/56] 6901021: Security Warning Icon not getting displayed properly when frame loses focus Make sure the gray icon is selected when hiding the security warning Reviewed-by: art, dcherepanov --- jdk/src/windows/native/sun/windows/awt_Toolkit.cpp | 1 + jdk/src/windows/native/sun/windows/awt_Window.cpp | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp index b612bd1bf16..9482f358fd1 100644 --- a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp @@ -1518,6 +1518,7 @@ HICON AwtToolkit::GetAwtIconSm() return defaultIconSm; } +// The icon at index 0 must be gray. See AwtWindow::GetSecurityWarningIcon() HICON AwtToolkit::GetSecurityWarningIcon(UINT index, UINT w, UINT h) { //Note: should not exceed 10 because of the current implementation. diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp index c03420d3522..1819115859b 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp @@ -652,7 +652,10 @@ void AwtWindow::UnregisterWarningWindowClass() HICON AwtWindow::GetSecurityWarningIcon() { - HICON ico = AwtToolkit::GetInstance().GetSecurityWarningIcon(securityWarningAnimationStage, + // It is assumed that the icon at index 0 is gray + const UINT index = securityAnimationKind == akShow ? + securityWarningAnimationStage : 0; + HICON ico = AwtToolkit::GetInstance().GetSecurityWarningIcon(index, warningWindowWidth, warningWindowHeight); return ico; } From b0a13700e131b4a98c59f6ce9944c0e1bad9c7be Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Wed, 2 Dec 2009 17:26:23 +0300 Subject: [PATCH 36/56] 6566375: PIT : test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.html Reviewed-by: art, dcherepanov --- .../TypeAhead/TestDialogTypeAhead.java | 80 ++++--------------- 1 file changed, 15 insertions(+), 65 deletions(-) diff --git a/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java b/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java index 10028be30d5..ac963e7622d 100644 --- a/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java +++ b/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java @@ -50,13 +50,7 @@ test import java.applet.Applet; import java.awt.*; -import java.lang.reflect.InvocationTargetException; import java.awt.event.*; -import java.awt.peer.DialogPeer; -import java.awt.peer.ComponentPeer; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import test.java.awt.regtesthelpers.Util; @@ -94,11 +88,13 @@ public class TestDialogTypeAhead extends Applet } }, AWTEvent.KEY_EVENT_MASK); + KeyboardFocusManager.setCurrentKeyboardFocusManager(new TestKFM()); + this.setLayout (new BorderLayout ()); f = new Frame("frame"); b = new Button("press"); - d = new TestDialog(f, "dialog", true, robotSema); + d = new Dialog(f, "dialog", true); ok = new Button("ok"); d.add(ok); d.pack(); @@ -170,6 +166,11 @@ public class TestDialogTypeAhead extends Applet } catch (InterruptedException ie) { throw new RuntimeException("Interrupted!"); } + if (!robotSema.getState()) { + throw new RuntimeException("robotSema hasn't been triggered"); + } + + System.err.println("typing ahead"); robot.keyPress(KeyEvent.VK_SPACE); robot.keyRelease(KeyEvent.VK_SPACE); waitForIdle(); @@ -278,65 +279,14 @@ public class TestDialogTypeAhead extends Applet } } - // Fix for 6446952. - // In the process of showing the dialog we have to catch peer.show() call - // so that to trigger key events just before it gets invoked. - // We base on the fact that a modal dialog sets type-ahead markers - // before it calls 'show' on the peer. - // Posting the key events before dialog.setVisible(true) would be actually not - // good because it would be Ok to dispatch them to the current focus owner, - // not to the dialog. - class TestDialog extends Dialog { - ComponentPeer origDialogPeer; - ComponentPeer proxyInstPeer; - Semaphore trigger; + class TestKFM extends DefaultKeyboardFocusManager { + protected synchronized void enqueueKeyEvents(long after, + Component untilFocused) + { + super.enqueueKeyEvents(after, untilFocused); - TestDialog(Frame owner, String title, boolean modal, Semaphore trigger) { - super(owner, title, modal); - this.trigger = trigger; - } - public ComponentPeer getPeer() { - ComponentPeer ret = super.getPeer(); - if (ret == proxyInstPeer) { - return origDialogPeer; - } else { - return ret; - } - } - - public void addNotify() { - super.addNotify(); - replacePeer(); - } - - void replacePeer() { - origDialogPeer = getPeer(); - - InvocationHandler handler = new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) { - if (method.getName() == "show") { - trigger.raise(); - } - - Object ret = null; - try { - ret = method.invoke(origDialogPeer, args); - } catch (IllegalAccessException iae) { - throw new Error("Test error.", iae); - } catch (InvocationTargetException ita) { - throw new Error("Test error.", ita); - } - return ret; - } - }; - - proxyInstPeer = (DialogPeer)Proxy.newProxyInstance( - DialogPeer.class.getClassLoader(), new Class[] {DialogPeer.class}, handler); - - try { - Util.getField(Component.class, "peer").set(d, proxyInstPeer); - } catch (IllegalAccessException iae) { - throw new Error("Test error.", iae); + if (untilFocused == TestDialogTypeAhead.this.ok) { + TestDialogTypeAhead.this.robotSema.raise(); } } } From 6e6324c6070e9acc2f4c75f04d9bd8cab3c66a26 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Wed, 2 Dec 2009 17:06:50 +0000 Subject: [PATCH 37/56] 6906510: Fix testcase for 6894643: Separate out dependency on Kerberos Reviewed-by: weijun --- jdk/test/sun/security/krb5/auto/SSL.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/sun/security/krb5/auto/SSL.java b/jdk/test/sun/security/krb5/auto/SSL.java index 44a80a60ae9..f66d7de13f0 100644 --- a/jdk/test/sun/security/krb5/auto/SSL.java +++ b/jdk/test/sun/security/krb5/auto/SSL.java @@ -48,7 +48,7 @@ public class SSL { KDC kdc = KDC.create(OneKDC.REALM); // Run this after KDC, so our own DNS service can be started try { - SERVER = InetAddress.getLocalHost().getHostName(); + SERVER = InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (java.net.UnknownHostException e) { SERVER = "localhost"; } From 709cc05d62eabe5bca4160e4bd448598d53c8c7d Mon Sep 17 00:00:00 2001 From: "J. Duke" Date: Wed, 5 Jul 2017 17:03:06 +0200 Subject: [PATCH 38/56] Added tag jdk7-b76 for changeset 09e0b33177af --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index af6c6de7c88..68872664ece 100644 --- a/.hgtags +++ b/.hgtags @@ -50,3 +50,4 @@ df4bcd06e1d0ab306efa5a44f24a409dc0c0c742 jdk7-b72 ce74bd35ce948d629a356e168797f44b593b1578 jdk7-b73 4e7661eaa211e186674f6cbefec4aef1144ac2a0 jdk7-b74 946518568340c4e511549318f19f47f06b7f5f9b jdk7-b75 +09e0b33177af2b98a03c9ca19eedf61440bd1cf6 jdk7-b76 From 0a842f22b7683517f7e5a827c923740a44458238 Mon Sep 17 00:00:00 2001 From: Michael Wilkerson Date: Thu, 3 Dec 2009 12:53:03 -0800 Subject: [PATCH 39/56] Added tag jdk7-b77 for changeset 78820074e4d5 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 09a0507f1d6..3d77e3c8b78 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -51,3 +51,4 @@ f708138c9aca4b389872838fe6773872fce3609e jdk7-b73 eacb36e30327e7ae33baa068e82ddccbd91eaae2 jdk7-b74 8885b22565077236a927e824ef450742e434a230 jdk7-b75 8fb602395be0f7d5af4e7e93b7df2d960faf9d17 jdk7-b76 +e6a5d095c356a547cf5b3c8885885aca5e91e09b jdk7-b77 From 5debca27af960b864d29a1cd671fa64d39411893 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Thu, 3 Dec 2009 21:30:27 +0000 Subject: [PATCH 40/56] 6906854: SSL/Krb5 testcase should not use a fixed port number Reviewed-by: alanb --- jdk/test/ProblemList.txt | 4 ---- jdk/test/sun/security/krb5/auto/SSL.java | 20 ++++++++++---------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index f145a246fc7..2edcfd4d595 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -893,10 +893,6 @@ java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java generic-all # jdk_security -# Fails on OpenSolaris, IOException: Attempt to obtain kerberos service ticket -# for host/`hostname`@RABBIT.HOLE failed! -sun/security/krb5/auto/SSL.java generic-all - # Run too slow on Solaris 10 sparc sun/security/ssl/com/sun/net/ssl/internal/ssl/InputRecord/SSLSocketTimeoutNulls.java solaris-sparc sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/ClientTimeout.java solaris-sparc diff --git a/jdk/test/sun/security/krb5/auto/SSL.java b/jdk/test/sun/security/krb5/auto/SSL.java index f66d7de13f0..d8e361a00e0 100644 --- a/jdk/test/sun/security/krb5/auto/SSL.java +++ b/jdk/test/sun/security/krb5/auto/SSL.java @@ -36,33 +36,32 @@ import sun.security.jgss.GSSUtil; public class SSL { private static final String KRB5_CIPHER = "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"; - private static final int PORT = 4569; private static final int LOOP_LIMIT = 1; private static final char[] PASS = "secret".toCharArray(); private static int loopCount = 0; - - private static String SERVER; + private static volatile String server; + private static volatile int port; public static void main(String[] args) throws Exception { KDC kdc = KDC.create(OneKDC.REALM); // Run this after KDC, so our own DNS service can be started try { - SERVER = InetAddress.getLocalHost().getHostName().toLowerCase(); + server = InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (java.net.UnknownHostException e) { - SERVER = "localhost"; + server = "localhost"; } kdc.addPrincipal(OneKDC.USER, OneKDC.PASS); kdc.addPrincipalRandKey("krbtgt/" + OneKDC.REALM); - kdc.addPrincipal("host/" + SERVER, PASS); + kdc.addPrincipal("host/" + server, PASS); KDC.saveConfig(OneKDC.KRB5_CONF, kdc); System.setProperty("java.security.krb5.conf", OneKDC.KRB5_CONF); final Context c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false); - final Context s = Context.fromUserPass("host/" + SERVER, PASS, true); + final Context s = Context.fromUserPass("host/" + server, PASS, true); - c.startAsClient("host/" + SERVER, GSSUtil.GSS_KRB5_MECH_OID); + c.startAsClient("host/" + server, GSSUtil.GSS_KRB5_MECH_OID); s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID); new Thread(new Runnable() { @@ -87,7 +86,7 @@ public class SSL { public byte[] run(Context s, byte[] input) throws Exception { SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) sslsf.createSocket(SERVER, PORT); + SSLSocket sslSocket = (SSLSocket) sslsf.createSocket(server, port); // Enable only a KRB5 cipher suite. String enabledSuites[] = {KRB5_CIPHER}; @@ -124,7 +123,8 @@ public class SSL { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(PORT); + (SSLServerSocket) sslssf.createServerSocket(0); // any port + port = sslServerSocket.getLocalPort(); // Enable only a KRB5 cipher suite. String enabledSuites[] = {KRB5_CIPHER}; From c40412f4f4231a0b24e9ab1e762b85f13d0fa4c2 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Thu, 3 Dec 2009 18:19:10 -0800 Subject: [PATCH 41/56] 6907177: Update jdk tests to remove unncessary -source and -target options Reviewed-by: ohair --- jdk/test/demo/jvmti/hprof/CpuOldTest.java | 2 +- jdk/test/demo/jvmti/hprof/CpuSamplesTest.java | 2 +- jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java | 2 +- jdk/test/demo/jvmti/hprof/CpuTimesTest.java | 2 +- jdk/test/demo/jvmti/hprof/HeapAllTest.java | 2 +- jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java | 2 +- jdk/test/demo/jvmti/hprof/HeapDumpTest.java | 2 +- jdk/test/demo/jvmti/hprof/HeapSitesTest.java | 2 +- jdk/test/demo/jvmti/hprof/OptionsTest.java | 2 +- jdk/test/java/io/Serializable/enum/array/Test.java | 3 --- jdk/test/java/io/Serializable/enum/badResolve/Write.java | 4 ++-- jdk/test/java/io/Serializable/enum/basic/Test.java | 3 --- jdk/test/java/io/Serializable/enum/classObject/Test.java | 3 --- .../java/io/Serializable/enum/constantSubclasses/Write.java | 4 ++-- .../io/Serializable/enum/ignoreSerializationFields/Test.java | 3 --- .../io/Serializable/enum/ignoreSerializationMethods/Test.java | 3 --- .../java/io/Serializable/enum/mismatchedTypecode/Test.java | 3 --- jdk/test/java/io/Serializable/enum/missingConstant/Write.java | 4 ++-- jdk/test/java/io/Serializable/enum/unshared/Test.java | 3 --- jdk/test/java/lang/Boolean/MakeBooleanComparable.java | 3 --- jdk/test/java/lang/Class/Cast.java | 3 --- jdk/test/java/lang/Class/IsEnum.java | 2 -- jdk/test/java/lang/Class/asSubclass/BasicUnit.java | 2 +- jdk/test/java/lang/ClassLoader/Assert.sh | 2 +- jdk/test/java/lang/Integer/BitTwiddle.java | 3 --- jdk/test/java/lang/Long/BitTwiddle.java | 3 --- jdk/test/java/lang/Math/Atan2Tests.java | 2 -- jdk/test/java/lang/Math/IeeeRecommendedTests.java | 2 -- jdk/test/java/lang/Math/PowTests.java | 2 -- jdk/test/java/lang/Math/TanTests.java | 2 -- jdk/test/java/lang/Runtime/exec/WinCommand.java | 3 --- jdk/test/java/lang/Thread/GenerifyStackTraces.java | 3 --- jdk/test/java/lang/Thread/UncaughtExceptions.sh | 2 +- jdk/test/java/lang/annotation/UnitTest.java | 2 -- jdk/test/java/lang/annotation/package-info.java | 2 +- .../CompositeData/MemoryNotifInfoCompositeData.java | 2 +- .../management/CompositeData/ThreadInfoCompositeData.java | 2 +- .../lang/management/ManagementFactory/MXBeanProxyTest.java | 3 --- .../management/ManagementFactory/PlatformMBeanServerTest.java | 3 --- .../lang/management/ManagementFactory/ProxyExceptions.java | 3 --- .../lang/management/ManagementFactory/ProxyTypeMapping.java | 2 +- .../lang/management/ManagementFactory/ValidateOpenTypes.java | 2 +- .../lang/management/RuntimeMXBean/GetSystemProperties.java | 3 --- .../java/lang/management/RuntimeMXBean/TestInputArgument.sh | 2 +- jdk/test/java/lang/reflect/Constructor/GenericStringTest.java | 2 -- jdk/test/java/lang/reflect/Field/GenericStringTest.java | 2 -- jdk/test/java/lang/reflect/Generics/StringsAndBounds.java | 2 -- jdk/test/java/lang/reflect/Generics/TestC1.java | 2 +- jdk/test/java/lang/reflect/Generics/TestC2.java | 2 +- jdk/test/java/lang/reflect/Generics/TestN1.java | 2 +- jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java | 2 -- jdk/test/java/lang/reflect/Generics/getAnnotationTest.java | 2 -- jdk/test/java/lang/reflect/Method/Equals.java | 2 +- jdk/test/java/lang/reflect/Method/GenericStringTest.java | 2 -- jdk/test/java/math/BigDecimal/DivideTests.java | 2 -- jdk/test/java/math/BigDecimal/IntegralDivisionTests.java | 2 -- jdk/test/java/math/BigDecimal/PowTests.java | 2 -- jdk/test/java/math/BigDecimal/ToPlainStringTests.java | 2 -- jdk/test/java/math/BigDecimal/ZeroScalingTests.java | 2 -- jdk/test/java/math/RoundingMode/RoundingModeTests.java | 2 -- jdk/test/java/net/ProxySelector/ProxyTest.java | 2 +- jdk/test/java/net/URL/PerConnectionProxy.java | 2 +- .../cert/PKIXBuilderParameters/InvalidParameters.java | 2 +- .../java/security/cert/PKIXParameters/InvalidParameters.java | 2 +- jdk/test/java/util/AbstractList/CheckForComodification.java | 2 -- jdk/test/java/util/Collections/AddAll.java | 3 --- jdk/test/java/util/Collections/Disjoint.java | 3 --- jdk/test/java/util/Collections/Frequency.java | 3 --- jdk/test/java/util/EnumMap/EnumMapBash.java | 3 --- jdk/test/java/util/EnumSet/AllOf.java | 3 --- jdk/test/java/util/EnumSet/ComplementOf.java | 3 --- jdk/test/java/util/EnumSet/EnumSetBash.java | 3 --- jdk/test/java/util/EnumSet/JumboRange.java | 3 --- jdk/test/java/util/EnumSet/Range.java | 3 --- jdk/test/java/util/Formattable/StockName.java | 4 +--- jdk/test/java/util/IdentityHashMap/ToString.java | 3 --- jdk/test/java/util/Locale/Bug4175998Test.java | 2 +- jdk/test/java/util/UUID/UUIDTest.java | 2 -- .../BlockingQueue/CancelledProducerConsumerLoops.java | 2 +- .../BlockingQueue/MultipleProducersSingleConsumerLoops.java | 2 +- .../util/concurrent/BlockingQueue/ProducerConsumerLoops.java | 2 +- .../BlockingQueue/SingleProducerMultipleConsumerLoops.java | 2 +- jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java | 2 +- jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java | 2 +- jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java | 2 +- .../ExecutorCompletionServiceLoops.java | 2 +- .../java/util/concurrent/FutureTask/CancelledFutureLoops.java | 2 +- jdk/test/java/util/concurrent/atomic/VMSupportsCS8.java | 2 -- .../concurrent/locks/ReentrantLock/CancelledLockLoops.java | 2 +- .../locks/ReentrantLock/LockOncePerThreadLoops.java | 2 +- .../locks/ReentrantLock/SimpleReentrantLockLoops.java | 2 +- .../util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java | 2 -- .../concurrent/locks/ReentrantReadWriteLock/MapLoops.java | 2 +- jdk/test/sun/management/AgentCheckTest.java | 3 --- jdk/test/sun/security/util/Oid/S11N.sh | 2 +- jdk/test/sun/tools/jconsole/ResourceCheckTest.sh | 2 +- 96 files changed, 49 insertions(+), 179 deletions(-) diff --git a/jdk/test/demo/jvmti/hprof/CpuOldTest.java b/jdk/test/demo/jvmti/hprof/CpuOldTest.java index 378083a2561..252aa05be16 100644 --- a/jdk/test/demo/jvmti/hprof/CpuOldTest.java +++ b/jdk/test/demo/jvmti/hprof/CpuOldTest.java @@ -26,7 +26,7 @@ * @bug 5012882 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g HelloWorld.java ../DemoRun.java + * @compile -g HelloWorld.java ../DemoRun.java * @build CpuOldTest * @run main CpuOldTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java b/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java index 0c5317184ec..d06d4cff332 100644 --- a/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java +++ b/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java @@ -26,7 +26,7 @@ * @bug 5012882 * @summary Test jvmti hprof * - * @compile -source 1.5 -g:lines HelloWorld.java ../DemoRun.java + * @compile -g:lines HelloWorld.java ../DemoRun.java * @build CpuSamplesTest * @run main CpuSamplesTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java b/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java index 5a1b7d08b37..63cfcb3e5c4 100644 --- a/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java +++ b/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java @@ -26,7 +26,7 @@ * @bug 5097131 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g HelloWorld.java DefineClass.java ../DemoRun.java + * @compile -g HelloWorld.java DefineClass.java ../DemoRun.java * @build CpuTimesDefineClassTest * @run main CpuTimesDefineClassTest DefineClass * diff --git a/jdk/test/demo/jvmti/hprof/CpuTimesTest.java b/jdk/test/demo/jvmti/hprof/CpuTimesTest.java index 7a9d10e8159..a99d384494b 100644 --- a/jdk/test/demo/jvmti/hprof/CpuTimesTest.java +++ b/jdk/test/demo/jvmti/hprof/CpuTimesTest.java @@ -26,7 +26,7 @@ * @bug 5012882 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g HelloWorld.java ../DemoRun.java + * @compile -g HelloWorld.java ../DemoRun.java * @build CpuTimesTest * @run main CpuTimesTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/HeapAllTest.java b/jdk/test/demo/jvmti/hprof/HeapAllTest.java index ce4431f5032..8de8714a02c 100644 --- a/jdk/test/demo/jvmti/hprof/HeapAllTest.java +++ b/jdk/test/demo/jvmti/hprof/HeapAllTest.java @@ -26,7 +26,7 @@ * @bug 5012882 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g HelloWorld.java ../DemoRun.java + * @compile -g HelloWorld.java ../DemoRun.java * @build HeapAllTest * @run main HeapAllTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java b/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java index 5f4f7b92b33..1d3366cfd9f 100644 --- a/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java +++ b/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java @@ -26,7 +26,7 @@ * @bug 4965057 6313381 * @summary Test jvmti hprof format=b * - * @compile -source 1.5 -g:source HelloWorld.java ../DemoRun.java + * @compile -g:source HelloWorld.java ../DemoRun.java * @build HeapBinaryFormatTest * @run main HeapBinaryFormatTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/HeapDumpTest.java b/jdk/test/demo/jvmti/hprof/HeapDumpTest.java index 1faca7ee6a9..01cce608313 100644 --- a/jdk/test/demo/jvmti/hprof/HeapDumpTest.java +++ b/jdk/test/demo/jvmti/hprof/HeapDumpTest.java @@ -26,7 +26,7 @@ * @bug 5012882 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g:source HelloWorld.java ../DemoRun.java + * @compile -g:source HelloWorld.java ../DemoRun.java * @build HeapDumpTest * @run main HeapDumpTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/HeapSitesTest.java b/jdk/test/demo/jvmti/hprof/HeapSitesTest.java index 31a3d7ef02d..c0205e23776 100644 --- a/jdk/test/demo/jvmti/hprof/HeapSitesTest.java +++ b/jdk/test/demo/jvmti/hprof/HeapSitesTest.java @@ -26,7 +26,7 @@ * @bug 5012882 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g:vars HelloWorld.java ../DemoRun.java + * @compile -g:vars HelloWorld.java ../DemoRun.java * @build HeapSitesTest * @run main HeapSitesTest HelloWorld */ diff --git a/jdk/test/demo/jvmti/hprof/OptionsTest.java b/jdk/test/demo/jvmti/hprof/OptionsTest.java index eae8276fcf5..e1cac9ccd56 100644 --- a/jdk/test/demo/jvmti/hprof/OptionsTest.java +++ b/jdk/test/demo/jvmti/hprof/OptionsTest.java @@ -26,7 +26,7 @@ * @bug 5083441 6299047 * @summary Test jvmti hprof * - * @compile -source 1.5 -g:lines HelloWorld.java ../DemoRun.java + * @compile -g:lines HelloWorld.java ../DemoRun.java * @build OptionsTest * @run main OptionsTest HelloWorld */ diff --git a/jdk/test/java/io/Serializable/enum/array/Test.java b/jdk/test/java/io/Serializable/enum/array/Test.java index 705de3a44df..95d9cac890d 100644 --- a/jdk/test/java/io/Serializable/enum/array/Test.java +++ b/jdk/test/java/io/Serializable/enum/array/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that serialization of enum constant arrays functions * properly. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/badResolve/Write.java b/jdk/test/java/io/Serializable/enum/badResolve/Write.java index 24e0242d5fa..dcdd5fa5aa6 100644 --- a/jdk/test/java/io/Serializable/enum/badResolve/Write.java +++ b/jdk/test/java/io/Serializable/enum/badResolve/Write.java @@ -26,10 +26,10 @@ * @summary Verify that enum classes present in a serialization stream cannot * be resolved by the receiver to non-enum classes, and vice-versa. * - * @compile -source 1.5 Write.java + * @compile Write.java * @run main Write * @clean Write - * @compile -source 1.5 Read.java + * @compile Read.java * @run main Read * @clean Read */ diff --git a/jdk/test/java/io/Serializable/enum/basic/Test.java b/jdk/test/java/io/Serializable/enum/basic/Test.java index b8677750bb9..5e8e8679c5a 100644 --- a/jdk/test/java/io/Serializable/enum/basic/Test.java +++ b/jdk/test/java/io/Serializable/enum/basic/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that basic serialization of non-specialized enum constants * functions properly. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/classObject/Test.java b/jdk/test/java/io/Serializable/enum/classObject/Test.java index e0f6ea2bd96..8d341c04470 100644 --- a/jdk/test/java/io/Serializable/enum/classObject/Test.java +++ b/jdk/test/java/io/Serializable/enum/classObject/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that serialization of Class objects for enum types works * properly. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/constantSubclasses/Write.java b/jdk/test/java/io/Serializable/enum/constantSubclasses/Write.java index 18dcfb56854..349125cc9e5 100644 --- a/jdk/test/java/io/Serializable/enum/constantSubclasses/Write.java +++ b/jdk/test/java/io/Serializable/enum/constantSubclasses/Write.java @@ -26,10 +26,10 @@ * @summary Verify that serialization of enum constants that are instances of * constant-specific subclasses functions properly. * - * @compile -source 1.5 Write.java + * @compile Write.java * @run main Write * @clean Write - * @compile -source 1.5 Read.java + * @compile Read.java * @run main Read * @clean Read */ diff --git a/jdk/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java b/jdk/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java index 2780a283e57..d5326af0d2e 100644 --- a/jdk/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java +++ b/jdk/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that serialVersionUID and serialPersistentFields * declarations made by enum types and constants are ignored. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java b/jdk/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java index 39bde6e255b..a1f9bbc6c74 100644 --- a/jdk/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java +++ b/jdk/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that custom serialization methods defined by enum types are * not invoked during serialization or deserialization. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/mismatchedTypecode/Test.java b/jdk/test/java/io/Serializable/enum/mismatchedTypecode/Test.java index f050cd964de..7197581700b 100644 --- a/jdk/test/java/io/Serializable/enum/mismatchedTypecode/Test.java +++ b/jdk/test/java/io/Serializable/enum/mismatchedTypecode/Test.java @@ -26,9 +26,6 @@ * @summary Verify that TC_OBJECT followed by a class descriptor for an enum * class results in an InvalidClassException, as does TC_ENUM followed * by a class descriptor for a non-enum class. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/enum/missingConstant/Write.java b/jdk/test/java/io/Serializable/enum/missingConstant/Write.java index 2939520636a..fb66b4ce4da 100644 --- a/jdk/test/java/io/Serializable/enum/missingConstant/Write.java +++ b/jdk/test/java/io/Serializable/enum/missingConstant/Write.java @@ -26,10 +26,10 @@ * @summary Verify that deserialization of an enum constant that does not exist * on the receiving side results in an InvalidObjectException. * - * @compile -source 1.5 Write.java + * @compile Write.java * @run main Write * @clean Write - * @compile -source 1.5 Read.java + * @compile Read.java * @run main Read * @clean Read */ diff --git a/jdk/test/java/io/Serializable/enum/unshared/Test.java b/jdk/test/java/io/Serializable/enum/unshared/Test.java index c4bdde9bc01..036e6e8b8ac 100644 --- a/jdk/test/java/io/Serializable/enum/unshared/Test.java +++ b/jdk/test/java/io/Serializable/enum/unshared/Test.java @@ -25,9 +25,6 @@ * @bug 4838379 * @summary Verify that unshared write and read operations work properly with * enum constants. - * - * @compile -source 1.5 Test.java - * @run main Test */ import java.io.*; diff --git a/jdk/test/java/lang/Boolean/MakeBooleanComparable.java b/jdk/test/java/lang/Boolean/MakeBooleanComparable.java index b84a4a27f59..21840de3924 100644 --- a/jdk/test/java/lang/Boolean/MakeBooleanComparable.java +++ b/jdk/test/java/lang/Boolean/MakeBooleanComparable.java @@ -26,9 +26,6 @@ * @bug 4329937 * @summary Basic test for making Boolean implement Comparable * @author Josh Bloch - * - * @compile -source 1.5 MakeBooleanComparable.java - * @run main MakeBooleanComparable */ import java.util.*; diff --git a/jdk/test/java/lang/Class/Cast.java b/jdk/test/java/lang/Class/Cast.java index 0f57c221c46..ec413f044e5 100644 --- a/jdk/test/java/lang/Class/Cast.java +++ b/jdk/test/java/lang/Class/Cast.java @@ -25,9 +25,6 @@ * @test * @bug 4881275 * @summary (reflect) Class.cast() - typesafe cast desired - * - * @compile -source 1.5 Cast.java - * @run main Cast */ public class Cast { diff --git a/jdk/test/java/lang/Class/IsEnum.java b/jdk/test/java/lang/Class/IsEnum.java index 1b4ccb70511..08d1e58d78b 100644 --- a/jdk/test/java/lang/Class/IsEnum.java +++ b/jdk/test/java/lang/Class/IsEnum.java @@ -26,8 +26,6 @@ * @bug 4891872 4989735 4990789 5020490 * @summary Check isEnum() method * @author Joseph D. Darcy - * @compile -source 1.5 IsEnum.java - * @run main IsEnum */ import java.lang.annotation.*; diff --git a/jdk/test/java/lang/Class/asSubclass/BasicUnit.java b/jdk/test/java/lang/Class/asSubclass/BasicUnit.java index 68cf1c36bfd..e9e8b68e853 100644 --- a/jdk/test/java/lang/Class/asSubclass/BasicUnit.java +++ b/jdk/test/java/lang/Class/asSubclass/BasicUnit.java @@ -27,7 +27,7 @@ * @summary please add a typesafe cast for Class types * @author gafter * - * @compile -Xlint:unchecked -Werror -source 1.5 BasicUnit.java + * @compile -Xlint:unchecked -Werror BasicUnit.java * @run main BasicUnit */ diff --git a/jdk/test/java/lang/ClassLoader/Assert.sh b/jdk/test/java/lang/ClassLoader/Assert.sh index 4744defce37..95dd51f1465 100644 --- a/jdk/test/java/lang/ClassLoader/Assert.sh +++ b/jdk/test/java/lang/ClassLoader/Assert.sh @@ -47,7 +47,7 @@ cp ${TESTSRC}/Assert.java . cp -R ${TESTSRC}/package1 . cp -R ${TESTSRC}/package2 . -${TESTJAVA}/bin/javac -source 1.4 Assert.java +${TESTJAVA}/bin/javac Assert.java ${TESTJAVA}/bin/java Assert diff --git a/jdk/test/java/lang/Integer/BitTwiddle.java b/jdk/test/java/lang/Integer/BitTwiddle.java index 4904ea5aa3d..35d61efd3a5 100644 --- a/jdk/test/java/lang/Integer/BitTwiddle.java +++ b/jdk/test/java/lang/Integer/BitTwiddle.java @@ -26,9 +26,6 @@ * @bug 4495754 * @summary Basic test for int bit twiddling * @author Josh Bloch - * - * @compile -source 1.5 BitTwiddle.java - * @run main BitTwiddle */ import java.util.Random; diff --git a/jdk/test/java/lang/Long/BitTwiddle.java b/jdk/test/java/lang/Long/BitTwiddle.java index fb1affd41dd..eefa9e83282 100644 --- a/jdk/test/java/lang/Long/BitTwiddle.java +++ b/jdk/test/java/lang/Long/BitTwiddle.java @@ -26,9 +26,6 @@ * @bug 4495754 * @summary Basic test for long bit twiddling * @author Josh Bloch - * - * @compile -source 1.5 BitTwiddle.java - * @run main BitTwiddle */ import java.util.Random; diff --git a/jdk/test/java/lang/Math/Atan2Tests.java b/jdk/test/java/lang/Math/Atan2Tests.java index 0660ff3744c..ed81283b36d 100644 --- a/jdk/test/java/lang/Math/Atan2Tests.java +++ b/jdk/test/java/lang/Math/Atan2Tests.java @@ -25,8 +25,6 @@ * @test * @bug 4984407 * @summary Tests for {Math, StrictMath}.atan2 - * @compile -source 1.5 Atan2Tests.java - * @run main Atan2Tests * @author Joseph D. Darcy */ diff --git a/jdk/test/java/lang/Math/IeeeRecommendedTests.java b/jdk/test/java/lang/Math/IeeeRecommendedTests.java index 4123451ed5d..f35d76ef3b8 100644 --- a/jdk/test/java/lang/Math/IeeeRecommendedTests.java +++ b/jdk/test/java/lang/Math/IeeeRecommendedTests.java @@ -26,8 +26,6 @@ * @bug 4860891 4826732 4780454 4939441 4826652 * @summary Tests for IEEE 754[R] recommended functions and similar methods * @author Joseph D. Darcy - * @compile -source 1.5 IeeeRecommendedTests.java - * @run main IeeeRecommendedTests */ import sun.misc.FpUtils; diff --git a/jdk/test/java/lang/Math/PowTests.java b/jdk/test/java/lang/Math/PowTests.java index 79764765e33..872de407d13 100644 --- a/jdk/test/java/lang/Math/PowTests.java +++ b/jdk/test/java/lang/Math/PowTests.java @@ -25,8 +25,6 @@ * @test * @bug 4984407 5033578 * @summary Tests for {Math, StrictMath}.pow - * @compile -source 1.5 PowTests.java - * @run main PowTests * @author Joseph D. Darcy */ diff --git a/jdk/test/java/lang/Math/TanTests.java b/jdk/test/java/lang/Math/TanTests.java index f603fb872a0..75d44631cd2 100644 --- a/jdk/test/java/lang/Math/TanTests.java +++ b/jdk/test/java/lang/Math/TanTests.java @@ -25,8 +25,6 @@ * @test * @bug 5033578 * @summary Tests for {Math, StrictMath}.tan - * @compile -source 1.5 TanTests.java - * @run main TanTests * @author Joseph D. Darcy */ diff --git a/jdk/test/java/lang/Runtime/exec/WinCommand.java b/jdk/test/java/lang/Runtime/exec/WinCommand.java index 37e17a1f316..b51489b76ad 100644 --- a/jdk/test/java/lang/Runtime/exec/WinCommand.java +++ b/jdk/test/java/lang/Runtime/exec/WinCommand.java @@ -25,9 +25,6 @@ * @bug 5006520 * @summary Check many different ways to run Windows programs * @author Martin Buchholz - * - * @compile -source 1.5 WinCommand.java - * @run main WinCommand */ import java.io.*; diff --git a/jdk/test/java/lang/Thread/GenerifyStackTraces.java b/jdk/test/java/lang/Thread/GenerifyStackTraces.java index e10080c004f..632228cf82c 100644 --- a/jdk/test/java/lang/Thread/GenerifyStackTraces.java +++ b/jdk/test/java/lang/Thread/GenerifyStackTraces.java @@ -26,9 +26,6 @@ * @bug 4919105 * @summary Generified basic unit test of Thread.getAllStackTraces() * @author Mandy Chung - * - * @compile -source 1.5 GenerifyStackTraces.java - * @run main GenerifyStackTraces */ import java.util.*; diff --git a/jdk/test/java/lang/Thread/UncaughtExceptions.sh b/jdk/test/java/lang/Thread/UncaughtExceptions.sh index 43b56c8e6fe..51aa0c58935 100644 --- a/jdk/test/java/lang/Thread/UncaughtExceptions.sh +++ b/jdk/test/java/lang/Thread/UncaughtExceptions.sh @@ -121,7 +121,7 @@ public class Seppuku extends Thread implements Runnable { } EOJAVA - Sys "$javac" "-source" "1.5" "Seppuku.java" + Sys "$javac" "Seppuku.java" CheckCommandResults "$expectedRC" "$expectedOut" "$expectedErr" \ "$java" "Seppuku" Cleanup diff --git a/jdk/test/java/lang/annotation/UnitTest.java b/jdk/test/java/lang/annotation/UnitTest.java index ed8b05c3cc0..160ebe683a7 100644 --- a/jdk/test/java/lang/annotation/UnitTest.java +++ b/jdk/test/java/lang/annotation/UnitTest.java @@ -26,8 +26,6 @@ * @bug 4906359 4963461 4965058 4965039 4986770 * @summary Unit test for annotation reading * @author Josh Bloch - * @compile -source 1.5 UnitTest.java - * @run main UnitTest */ import static java.lang.annotation.RetentionPolicy.RUNTIME; diff --git a/jdk/test/java/lang/annotation/package-info.java b/jdk/test/java/lang/annotation/package-info.java index 78afb3f6c0a..d2bef02dde0 100644 --- a/jdk/test/java/lang/annotation/package-info.java +++ b/jdk/test/java/lang/annotation/package-info.java @@ -27,7 +27,7 @@ * @summary Package annotations * @author gafter * - * @compile -source 1.5 package-info.java PackageMain.java + * @compile package-info.java PackageMain.java * @run main PackageMain */ diff --git a/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java b/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java index d833e5eb9ab..8002188024a 100644 --- a/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java +++ b/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java @@ -29,7 +29,7 @@ * the input CompositeData is invalid. * @author Mandy Chung * - * @compile -source 1.5 OpenTypeConverter.java + * @compile OpenTypeConverter.java * @build MemoryNotifInfoCompositeData * @run main MemoryNotifInfoCompositeData */ diff --git a/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java b/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java index 6c3cb0d044a..31be3a1596a 100644 --- a/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java +++ b/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java @@ -29,7 +29,7 @@ * the input CompositeData is invalid. * @author Mandy Chung * - * @compile -source 1.5 OpenTypeConverter.java + * @compile OpenTypeConverter.java * @build ThreadInfoCompositeData * @run main ThreadInfoCompositeData */ diff --git a/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java b/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java index afd6618e62a..4a829fe76de 100644 --- a/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java +++ b/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java @@ -26,9 +26,6 @@ * @bug 5024531 * @summary Basic Test for ManagementFactory.newPlatformMXBean(). * @author Mandy Chung - * - * @compile -source 1.5 MXBeanProxyTest.java - * @run main MXBeanProxyTest */ import javax.management.*; import java.lang.management.ClassLoadingMXBean; diff --git a/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java b/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java index 7deb892569a..939ac86a764 100644 --- a/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java +++ b/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java @@ -26,9 +26,6 @@ * @bug 4947536 * @summary Basic unit test of ManagementFactory.getPlatformMBeanServer() * @author Mandy Chung - * - * @compile -source 1.5 PlatformMBeanServerTest.java - * @run main PlatformMBeanServerTest */ import java.lang.management.*; diff --git a/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java b/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java index 5be25106827..1feba9e13f6 100644 --- a/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java +++ b/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java @@ -27,9 +27,6 @@ * @summary Test type mapping of the platform MXBean proxy * returned from Management.newPlatformMXBeanProxy(). * @author Mandy Chung - * - * @compile -source 1.5 ProxyExceptions.java - * @run main ProxyExceptions */ import java.lang.management.*; import javax.management.*; diff --git a/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java b/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java index eb48825736c..a4111b2e6ef 100644 --- a/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java +++ b/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java @@ -28,7 +28,7 @@ * returned from Management.newPlatformMXBeanProxy(). * @author Mandy Chung * - * @compile -source 1.5 ProxyTypeMapping.java + * @compile ProxyTypeMapping.java * @run main/othervm -verbose:gc ProxyTypeMapping */ import java.lang.management.*; diff --git a/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java b/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java index 68d5304b91c..d4fd4ea4a94 100644 --- a/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java +++ b/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java @@ -28,7 +28,7 @@ * MBeanServer. * @author Mandy Chung * - * @compile -source 1.5 ValidateOpenTypes.java + * @compile ValidateOpenTypes.java * @run main/othervm -verbose:gc ValidateOpenTypes */ import java.lang.management.*; diff --git a/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java b/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java index 5a655378462..c411192f080 100644 --- a/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java +++ b/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java @@ -26,9 +26,6 @@ * @bug 4990512 * @summary Basic Test for RuntimeMXBean.getSystemProperties(). * @author Mandy Chung - * - * @compile -source 1.5 GetSystemProperties.java - * @run main GetSystemProperties */ import java.lang.management.ManagementFactory; diff --git a/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh b/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh index f1fb705f377..e38817ec3fc 100644 --- a/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh +++ b/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh @@ -27,7 +27,7 @@ # @summary # @author Mandy Chung # -# @run compile -source 1.5 InputArgument.java +# @run compile InputArgument.java # @run shell TestInputArgument.sh # diff --git a/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java b/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java index 49709884f56..59ed2dbfa95 100644 --- a/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java +++ b/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java @@ -26,8 +26,6 @@ * @bug 5033583 6316717 6470106 * @summary Check toGenericString() and toString() methods * @author Joseph D. Darcy - * @compile -source 1.5 GenericStringTest.java - * @run main GenericStringTest */ import java.lang.reflect.*; diff --git a/jdk/test/java/lang/reflect/Field/GenericStringTest.java b/jdk/test/java/lang/reflect/Field/GenericStringTest.java index f25a6ca36f2..148e69a7068 100644 --- a/jdk/test/java/lang/reflect/Field/GenericStringTest.java +++ b/jdk/test/java/lang/reflect/Field/GenericStringTest.java @@ -26,8 +26,6 @@ * @bug 5033583 * @summary Check toGenericString() method * @author Joseph D. Darcy - * @compile -source 1.5 GenericStringTest.java - * @run main GenericStringTest */ import java.lang.reflect.*; diff --git a/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java b/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java index d49a5ea628e..dac18fb7cb2 100644 --- a/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java +++ b/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java @@ -26,8 +26,6 @@ * @bug 5015676 4987888 4997464 * @summary Testing upper bounds and availability of toString methods * @author Joseph D. Darcy - * @compile -source 1.5 StringsAndBounds.java - * @run main StringsAndBounds */ import java.lang.reflect.*; diff --git a/jdk/test/java/lang/reflect/Generics/TestC1.java b/jdk/test/java/lang/reflect/Generics/TestC1.java index 756a4c63ec2..8a9fbe37031 100644 --- a/jdk/test/java/lang/reflect/Generics/TestC1.java +++ b/jdk/test/java/lang/reflect/Generics/TestC1.java @@ -26,7 +26,7 @@ * @bug 4891872 * @summary Some tests for the generic core reflection api. * @author Gilad Bracha -* @compile -source 1.5 TestC1.java +* @compile TestC1.java * @run main/othervm -ea TestC1 */ diff --git a/jdk/test/java/lang/reflect/Generics/TestC2.java b/jdk/test/java/lang/reflect/Generics/TestC2.java index d42671b3d3d..c2e574a2fa5 100644 --- a/jdk/test/java/lang/reflect/Generics/TestC2.java +++ b/jdk/test/java/lang/reflect/Generics/TestC2.java @@ -26,7 +26,7 @@ * @bug 4891872 * @summary Some tests for the generic core reflection api. * @author Gilad Bracha -* @compile -source 1.5 TestC2.java +* @compile TestC2.java * @run main/othervm -ea TestC2 */ diff --git a/jdk/test/java/lang/reflect/Generics/TestN1.java b/jdk/test/java/lang/reflect/Generics/TestN1.java index d2dc8b253f7..014a09f956d 100644 --- a/jdk/test/java/lang/reflect/Generics/TestN1.java +++ b/jdk/test/java/lang/reflect/Generics/TestN1.java @@ -26,7 +26,7 @@ * @bug 4891872 * @summary Some tests for the generic core reflection api. * @author Gilad Bracha -* @compile -source 1.5 TestN1.java +* @compile TestN1.java * @run main/othervm -ea TestN1 */ diff --git a/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java b/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java index 1427563f85e..77a71013fbf 100644 --- a/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java +++ b/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java @@ -26,8 +26,6 @@ * @bug 4981727 * @summary * @author Joseph D. Darcy - * @compile -source 1.5 exceptionCauseTest.java - * @run main exceptionCauseTest */ import java.io.PrintStream; diff --git a/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java b/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java index d7f5d6de7da..f7a60f26d69 100644 --- a/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java +++ b/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java @@ -26,8 +26,6 @@ * @bug 4979440 * @summary Test for signature parsing corner case * @author Joseph D. Darcy - * @compile -source 1.5 getAnnotationTest.java - * @run main getAnnotationTest */ import java.lang.reflect.*; diff --git a/jdk/test/java/lang/reflect/Method/Equals.java b/jdk/test/java/lang/reflect/Method/Equals.java index 2bcb4ecf4e3..7f7bd70f32f 100644 --- a/jdk/test/java/lang/reflect/Method/Equals.java +++ b/jdk/test/java/lang/reflect/Method/Equals.java @@ -27,7 +27,7 @@ * @summary Generic framework to test Method.equals. * * @clean A - * @compile -source 1.5 Equals.java + * @compile Equals.java * @run main Equals */ diff --git a/jdk/test/java/lang/reflect/Method/GenericStringTest.java b/jdk/test/java/lang/reflect/Method/GenericStringTest.java index 361e3db8c7a..3894252a52f 100644 --- a/jdk/test/java/lang/reflect/Method/GenericStringTest.java +++ b/jdk/test/java/lang/reflect/Method/GenericStringTest.java @@ -26,8 +26,6 @@ * @bug 5033583 6316717 6470106 * @summary Check toGenericString() and toString() methods * @author Joseph D. Darcy - * @compile -source 1.5 GenericStringTest.java - * @run main GenericStringTest */ import java.lang.reflect.*; diff --git a/jdk/test/java/math/BigDecimal/DivideTests.java b/jdk/test/java/math/BigDecimal/DivideTests.java index 7d04a60ca4b..5265f6d32f8 100644 --- a/jdk/test/java/math/BigDecimal/DivideTests.java +++ b/jdk/test/java/math/BigDecimal/DivideTests.java @@ -26,8 +26,6 @@ * @bug 4851776 4907265 6177836 6876282 * @summary Some tests for the divide methods. * @author Joseph D. Darcy - * @compile -source 1.5 DivideTests.java - * @run main DivideTests */ import java.math.*; diff --git a/jdk/test/java/math/BigDecimal/IntegralDivisionTests.java b/jdk/test/java/math/BigDecimal/IntegralDivisionTests.java index 100eca40cce..6ce5a900453 100644 --- a/jdk/test/java/math/BigDecimal/IntegralDivisionTests.java +++ b/jdk/test/java/math/BigDecimal/IntegralDivisionTests.java @@ -25,8 +25,6 @@ * @bug 4904082 4917089 6337226 * @summary Tests that integral division and related methods return the proper result and scale. * @author Joseph D. Darcy - * @compile -source 1.5 IntegralDivisionTests.java - * @run main IntegralDivisionTests */ import java.math.*; public class IntegralDivisionTests { diff --git a/jdk/test/java/math/BigDecimal/PowTests.java b/jdk/test/java/math/BigDecimal/PowTests.java index 9623b70bc11..78b3b6a5702 100644 --- a/jdk/test/java/math/BigDecimal/PowTests.java +++ b/jdk/test/java/math/BigDecimal/PowTests.java @@ -26,8 +26,6 @@ * @bug 4916097 * @summary Some exponent over/undeflow tests for the pow method * @author Joseph D. Darcy - * @compile -source 1.5 PowTests.java - * @run main PowTests */ import java.math.*; diff --git a/jdk/test/java/math/BigDecimal/ToPlainStringTests.java b/jdk/test/java/math/BigDecimal/ToPlainStringTests.java index aca745b7e4b..9343b0dbab1 100644 --- a/jdk/test/java/math/BigDecimal/ToPlainStringTests.java +++ b/jdk/test/java/math/BigDecimal/ToPlainStringTests.java @@ -26,8 +26,6 @@ * @bug 4984872 * @summary Basic tests of toPlainString method * @author Joseph D. Darcy - * @compile -source 1.5 ToPlainStringTests.java - * @run main ToPlainStringTests */ import java.math.*; diff --git a/jdk/test/java/math/BigDecimal/ZeroScalingTests.java b/jdk/test/java/math/BigDecimal/ZeroScalingTests.java index a48e005a4b1..abd5451e068 100644 --- a/jdk/test/java/math/BigDecimal/ZeroScalingTests.java +++ b/jdk/test/java/math/BigDecimal/ZeroScalingTests.java @@ -26,8 +26,6 @@ * @bug 4902952 4905407 4916149 * @summary Tests that the scale of zero is propagated properly and has the proper effect. * @author Joseph D. Darcy - * @compile -source 1.5 ZeroScalingTests.java - * @run main ZeroScalingTests */ import java.math.*; diff --git a/jdk/test/java/math/RoundingMode/RoundingModeTests.java b/jdk/test/java/math/RoundingMode/RoundingModeTests.java index 03fd5e7ac80..8a7cd1aa0c9 100644 --- a/jdk/test/java/math/RoundingMode/RoundingModeTests.java +++ b/jdk/test/java/math/RoundingMode/RoundingModeTests.java @@ -26,8 +26,6 @@ * @bug 4851776 4891522 4905335 * @summary Basic tests for the RoundingMode class. * @author Joseph D. Darcy - * @compile -source 1.5 RoundingModeTests.java - * @run main RoundingModeTests */ import java.math.RoundingMode; diff --git a/jdk/test/java/net/ProxySelector/ProxyTest.java b/jdk/test/java/net/ProxySelector/ProxyTest.java index 869eb3fab27..18be010f619 100644 --- a/jdk/test/java/net/ProxySelector/ProxyTest.java +++ b/jdk/test/java/net/ProxySelector/ProxyTest.java @@ -27,7 +27,7 @@ * @summary HTTP client: Improve proxy server configuration and selection * @library ../../../sun/net/www/httptest/ * @build ClosedChannelList HttpServer HttpTransaction HttpCallback - * @compile -source 1.5 ProxyTest.java + * @compile ProxyTest.java * @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 ProxyTest */ diff --git a/jdk/test/java/net/URL/PerConnectionProxy.java b/jdk/test/java/net/URL/PerConnectionProxy.java index 0640ec4bb87..9a8cdf2616f 100644 --- a/jdk/test/java/net/URL/PerConnectionProxy.java +++ b/jdk/test/java/net/URL/PerConnectionProxy.java @@ -26,7 +26,7 @@ * @summary Needs per connection proxy support for URLs * @library ../../../sun/net/www/httptest/ * @build ClosedChannelList HttpServer HttpTransaction HttpCallback - * @compile -source 1.5 PerConnectionProxy.java + * @compile PerConnectionProxy.java * @run main/othervm -Dhttp.proxyHost=inexistant -Dhttp.proxyPort=8080 PerConnectionProxy */ diff --git a/jdk/test/java/security/cert/PKIXBuilderParameters/InvalidParameters.java b/jdk/test/java/security/cert/PKIXBuilderParameters/InvalidParameters.java index 14b8b0698eb..b9f172fb2f6 100644 --- a/jdk/test/java/security/cert/PKIXBuilderParameters/InvalidParameters.java +++ b/jdk/test/java/security/cert/PKIXBuilderParameters/InvalidParameters.java @@ -24,7 +24,7 @@ /** * @test * @test 4422738 - * @compile -source 1.4 -target 1.4 InvalidParameters.java + * @compile -source 1.4 InvalidParameters.java * @run main InvalidParameters * @summary Make sure PKIXBuilderParameters(Set) detects invalid * parameters and throws correct exceptions diff --git a/jdk/test/java/security/cert/PKIXParameters/InvalidParameters.java b/jdk/test/java/security/cert/PKIXParameters/InvalidParameters.java index d3e3c5ab786..01946d6e2e0 100644 --- a/jdk/test/java/security/cert/PKIXParameters/InvalidParameters.java +++ b/jdk/test/java/security/cert/PKIXParameters/InvalidParameters.java @@ -24,7 +24,7 @@ /** * @test * @test 4422738 - * @compile -source 1.4 -target 1.4 InvalidParameters.java + * @compile -source 1.4 InvalidParameters.java * @run main InvalidParameters * @summary Make sure PKIXParameters(Set) and setTrustAnchors() detects invalid * parameters and throws correct exceptions diff --git a/jdk/test/java/util/AbstractList/CheckForComodification.java b/jdk/test/java/util/AbstractList/CheckForComodification.java index 156c7898270..790a4bb6c4e 100644 --- a/jdk/test/java/util/AbstractList/CheckForComodification.java +++ b/jdk/test/java/util/AbstractList/CheckForComodification.java @@ -28,8 +28,6 @@ * @author Josh Bloch * * @ignore Bug fix temporarily removed as it uncovered other bugs (4992226) - * @compile -source 1.5 CheckForComodification.java - * @run main CheckForComodification */ import java.util.*; diff --git a/jdk/test/java/util/Collections/AddAll.java b/jdk/test/java/util/Collections/AddAll.java index ef66b007591..48bbc799a5d 100644 --- a/jdk/test/java/util/Collections/AddAll.java +++ b/jdk/test/java/util/Collections/AddAll.java @@ -26,9 +26,6 @@ * @bug 4822887 * @summary Basic test for Collections.addAll * @author Josh Bloch - * - * @compile -source 1.5 AddAll.java - * @run main AddAll */ import java.util.*; diff --git a/jdk/test/java/util/Collections/Disjoint.java b/jdk/test/java/util/Collections/Disjoint.java index 8d820f10015..ada965efa6a 100644 --- a/jdk/test/java/util/Collections/Disjoint.java +++ b/jdk/test/java/util/Collections/Disjoint.java @@ -26,9 +26,6 @@ * @bug 4339792 * @summary Basic test for Collections.disjoint * @author Josh Bloch - * - * @compile -source 1.5 Disjoint.java - * @run main Disjoint */ import java.util.*; diff --git a/jdk/test/java/util/Collections/Frequency.java b/jdk/test/java/util/Collections/Frequency.java index a21265720f3..71938c561cf 100644 --- a/jdk/test/java/util/Collections/Frequency.java +++ b/jdk/test/java/util/Collections/Frequency.java @@ -26,9 +26,6 @@ * @bug 4193200 * @summary Basic test for Collections.frequency * @author Josh Bloch - * - * @compile -source 1.5 Frequency.java - * @run main Frequency */ import java.util.*; diff --git a/jdk/test/java/util/EnumMap/EnumMapBash.java b/jdk/test/java/util/EnumMap/EnumMapBash.java index 4dd51b13327..1182bf6c446 100644 --- a/jdk/test/java/util/EnumMap/EnumMapBash.java +++ b/jdk/test/java/util/EnumMap/EnumMapBash.java @@ -27,9 +27,6 @@ * @summary Unit test for EnumMap * @author Josh Bloch * @author Yo Yo Ma - * - * @compile -source 1.5 EnumMapBash.java - * @run main EnumMapBash */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/AllOf.java b/jdk/test/java/util/EnumSet/AllOf.java index 712fbc37719..28e471b0bfe 100644 --- a/jdk/test/java/util/EnumSet/AllOf.java +++ b/jdk/test/java/util/EnumSet/AllOf.java @@ -26,9 +26,6 @@ * @bug 4946090 * @summary AllOf static factory is broken in Regular and Jumbo enum set * @author Josh Bloch - * - * @compile -source 1.5 AllOf.java - * @run main AllOf */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/ComplementOf.java b/jdk/test/java/util/EnumSet/ComplementOf.java index 35251792eed..3a9fe377a4e 100644 --- a/jdk/test/java/util/EnumSet/ComplementOf.java +++ b/jdk/test/java/util/EnumSet/ComplementOf.java @@ -26,9 +26,6 @@ * @bug 4946096 * @summary ComplementOf static factory is broken in Regular and Jumbo enum set * @author Josh Bloch - * - * @compile -source 1.5 ComplementOf.java - * @run main ComplementOf */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/EnumSetBash.java b/jdk/test/java/util/EnumSet/EnumSetBash.java index fd61f119755..51dd8cbfef6 100644 --- a/jdk/test/java/util/EnumSet/EnumSetBash.java +++ b/jdk/test/java/util/EnumSet/EnumSetBash.java @@ -28,9 +28,6 @@ * @author Josh Bloch * @author Neal Gafter * @author Yo Ma Ma - * - * @compile -source 1.5 EnumSetBash.java - * @run main EnumSetBash */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/JumboRange.java b/jdk/test/java/util/EnumSet/JumboRange.java index eec95657234..55be9784dc6 100644 --- a/jdk/test/java/util/EnumSet/JumboRange.java +++ b/jdk/test/java/util/EnumSet/JumboRange.java @@ -26,9 +26,6 @@ * @bug 4958003 * @summary Range static factory fails to compute size in Jumbo enum set * @author Josh Bloch - * - * @compile -source 1.5 JumboRange.java - * @run main JumboRange */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/Range.java b/jdk/test/java/util/EnumSet/Range.java index 2a0301b68bc..ad4ab959c3f 100644 --- a/jdk/test/java/util/EnumSet/Range.java +++ b/jdk/test/java/util/EnumSet/Range.java @@ -26,9 +26,6 @@ * @bug 4952736 * @summary Range static factory is broken in Regular and Jumbo enum set * @author Josh Bloch - * - * @compile -source 1.5 Range.java - * @run main Range */ import java.util.*; diff --git a/jdk/test/java/util/Formattable/StockName.java b/jdk/test/java/util/Formattable/StockName.java index 30a06da8217..d4b092e802a 100644 --- a/jdk/test/java/util/Formattable/StockName.java +++ b/jdk/test/java/util/Formattable/StockName.java @@ -21,11 +21,9 @@ * have any questions. */ -/** +/* * @test * @bug 4965770 4992540 5030716 - * @compile -source 1.5 StockName.java - * @run main StockName */ import java.nio.CharBuffer; diff --git a/jdk/test/java/util/IdentityHashMap/ToString.java b/jdk/test/java/util/IdentityHashMap/ToString.java index 794ccb9982b..8b22e3013f3 100644 --- a/jdk/test/java/util/IdentityHashMap/ToString.java +++ b/jdk/test/java/util/IdentityHashMap/ToString.java @@ -26,9 +26,6 @@ * @bug 4973432 * @summary Test that toString on entrySet Iterator/Entry behaves reasonably * @author Josh Bloch - * - * @compile -source 1.5 ToString.java - * @run main ToString */ diff --git a/jdk/test/java/util/Locale/Bug4175998Test.java b/jdk/test/java/util/Locale/Bug4175998Test.java index 96335255d0f..37ebee4860e 100644 --- a/jdk/test/java/util/Locale/Bug4175998Test.java +++ b/jdk/test/java/util/Locale/Bug4175998Test.java @@ -23,7 +23,7 @@ /* @test @summary test ISO639-2 language codes - @compile -encoding ascii -source 1.4 -target 1.4 Bug4175998Test.java + @compile -encoding ascii -source 5 Bug4175998Test.java @run main Bug4175998Test @bug 4175998 */ diff --git a/jdk/test/java/util/UUID/UUIDTest.java b/jdk/test/java/util/UUID/UUIDTest.java index c71f6a41062..2dde63c655c 100644 --- a/jdk/test/java/util/UUID/UUIDTest.java +++ b/jdk/test/java/util/UUID/UUIDTest.java @@ -23,8 +23,6 @@ /* @test * @bug 4173528 5068772 - * @compile -source 1.4 -target 1.4 UUIDTest.java - * @run main UUIDTest * @summary Unit tests for java.util.UUID */ diff --git a/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java b/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java index 98ac5d744e2..b704bb12c35 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/CancelledProducerConsumerLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 CancelledProducerConsumerLoops.java + * @compile CancelledProducerConsumerLoops.java * @run main/timeout=7000 CancelledProducerConsumerLoops * @summary Checks for responsiveness of blocking queues to cancellation. * Runs under the assumption that ITERS computations require more than diff --git a/jdk/test/java/util/concurrent/BlockingQueue/MultipleProducersSingleConsumerLoops.java b/jdk/test/java/util/concurrent/BlockingQueue/MultipleProducersSingleConsumerLoops.java index 8b7db5a945d..31db3a1dde1 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/MultipleProducersSingleConsumerLoops.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/MultipleProducersSingleConsumerLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 MultipleProducersSingleConsumerLoops.java + * @compile MultipleProducersSingleConsumerLoops.java * @run main/timeout=3600 MultipleProducersSingleConsumerLoops * @summary multiple producers and single consumer using blocking queues */ diff --git a/jdk/test/java/util/concurrent/BlockingQueue/ProducerConsumerLoops.java b/jdk/test/java/util/concurrent/BlockingQueue/ProducerConsumerLoops.java index 761990d3a92..c6ca42e9ffc 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/ProducerConsumerLoops.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/ProducerConsumerLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 ProducerConsumerLoops.java + * @compile ProducerConsumerLoops.java * @run main/timeout=3600 ProducerConsumerLoops * @summary multiple producers and consumers using blocking queues */ diff --git a/jdk/test/java/util/concurrent/BlockingQueue/SingleProducerMultipleConsumerLoops.java b/jdk/test/java/util/concurrent/BlockingQueue/SingleProducerMultipleConsumerLoops.java index c99a664b787..f365dea71a6 100644 --- a/jdk/test/java/util/concurrent/BlockingQueue/SingleProducerMultipleConsumerLoops.java +++ b/jdk/test/java/util/concurrent/BlockingQueue/SingleProducerMultipleConsumerLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 SingleProducerMultipleConsumerLoops.java + * @compile SingleProducerMultipleConsumerLoops.java * @run main/timeout=600 SingleProducerMultipleConsumerLoops * @summary check ordering for blocking queues with 1 producer and multiple consumers */ diff --git a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java index 1c77f5bb166..9a476194362 100644 --- a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java +++ b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 MapCheck.java + * @compile MapCheck.java * @run main/timeout=240 MapCheck * @summary Times and checks basic map operations */ diff --git a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java index e6c310ff157..f7aeab10f81 100644 --- a/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java +++ b/jdk/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 MapLoops.java + * @compile MapLoops.java * @run main/timeout=1600 MapLoops * @summary Exercise multithreaded maps, by default ConcurrentHashMap. * Multithreaded hash table test. Each thread does a random walk diff --git a/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java b/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java index 53f987381cc..43763426a0a 100644 --- a/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java +++ b/jdk/test/java/util/concurrent/Exchanger/ExchangeLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 ExchangeLoops.java + * @compile ExchangeLoops.java * @run main/timeout=720 ExchangeLoops * @summary checks to make sure a pipeline of exchangers passes data. */ diff --git a/jdk/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java b/jdk/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java index fe713fe0791..35e183395aa 100644 --- a/jdk/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java +++ b/jdk/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4965960 - * @compile -source 1.5 ExecutorCompletionServiceLoops.java + * @compile ExecutorCompletionServiceLoops.java * @run main/timeout=3600 ExecutorCompletionServiceLoops * @summary Exercise ExecutorCompletionServiceLoops */ diff --git a/jdk/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java b/jdk/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java index a3d1536d11d..c05dd0bcda0 100644 --- a/jdk/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java +++ b/jdk/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 CancelledFutureLoops.java + * @compile CancelledFutureLoops.java * @run main/timeout=2000 CancelledFutureLoops * @summary Checks for responsiveness of futures to cancellation. * Runs under the assumption that ITERS computations require more than diff --git a/jdk/test/java/util/concurrent/atomic/VMSupportsCS8.java b/jdk/test/java/util/concurrent/atomic/VMSupportsCS8.java index 42a7587dbe2..055d0259dc3 100644 --- a/jdk/test/java/util/concurrent/atomic/VMSupportsCS8.java +++ b/jdk/test/java/util/concurrent/atomic/VMSupportsCS8.java @@ -24,8 +24,6 @@ /* * @test * @bug 4992443 4994819 - * @compile -source 1.5 VMSupportsCS8.java - * @run main VMSupportsCS8 * @summary Checks that the value of VMSupportsCS8 matches system properties. */ diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java index fb1c7b5b5ca..fc98478117b 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 CancelledLockLoops.java + * @compile CancelledLockLoops.java * @run main/timeout=2800 CancelledLockLoops * @summary tests lockInterruptibly. * Checks for responsiveness of locks to interrupts. Runs under that diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java index 444c55e82f8..361ea1a372d 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 LockOncePerThreadLoops.java + * @compile LockOncePerThreadLoops.java * @run main/timeout=15000 LockOncePerThreadLoops * @summary Checks for missed signals by locking and unlocking each of an array of locks once per thread */ diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java index ead5c960f15..37641686ef0 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 SimpleReentrantLockLoops.java + * @compile SimpleReentrantLockLoops.java * @run main/timeout=4500 SimpleReentrantLockLoops * @summary multiple threads using a single lock */ diff --git a/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java index d1edcc911d0..d0df653fb8f 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java @@ -34,8 +34,6 @@ /* * @test * @bug 4486658 5031862 - * @compile -source 1.5 TimeoutLockLoops.java - * @run main TimeoutLockLoops * @summary Checks for responsiveness of locks to timeouts. * Runs under the assumption that ITERS computations require more than * TIMEOUT msecs to complete, which seems to be a safe assumption for diff --git a/jdk/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java b/jdk/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java index a6e710b0b28..6596ed5a7dc 100644 --- a/jdk/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java +++ b/jdk/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile -source 1.5 MapLoops.java + * @compile MapLoops.java * @run main/timeout=4700 MapLoops * @summary Exercise multithreaded maps, by default ConcurrentHashMap. * Multithreaded hash table test. Each thread does a random walk diff --git a/jdk/test/sun/management/AgentCheckTest.java b/jdk/test/sun/management/AgentCheckTest.java index 8d3f17edd9a..d480f5b0226 100644 --- a/jdk/test/sun/management/AgentCheckTest.java +++ b/jdk/test/sun/management/AgentCheckTest.java @@ -27,9 +27,6 @@ * @summary Localize log messages from the management agents * * @author Tim Bell - * - * @run compile -source 1.5 -g AgentCheckTest.java - * @run main AgentCheckTest */ import sun.management.Agent; diff --git a/jdk/test/sun/security/util/Oid/S11N.sh b/jdk/test/sun/security/util/Oid/S11N.sh index 77341e8a91b..081cd52298f 100644 --- a/jdk/test/sun/security/util/Oid/S11N.sh +++ b/jdk/test/sun/security/util/Oid/S11N.sh @@ -99,7 +99,7 @@ esac # the test code -${TESTJAVA}${FS}bin${FS}javac -source 1.3 -target 1.3 -d . ${TESTSRC}${FS}SerialTest.java || exit 10 +${TESTJAVA}${FS}bin${FS}javac -d . ${TESTSRC}${FS}SerialTest.java || exit 10 OLDJAVA=" /java/re/j2se/1.6.0/latest/binaries/${PF} diff --git a/jdk/test/sun/tools/jconsole/ResourceCheckTest.sh b/jdk/test/sun/tools/jconsole/ResourceCheckTest.sh index d2a34bb2a89..a5d211d5141 100644 --- a/jdk/test/sun/tools/jconsole/ResourceCheckTest.sh +++ b/jdk/test/sun/tools/jconsole/ResourceCheckTest.sh @@ -98,7 +98,7 @@ env set -vx # #Compile. jconsole.jar is required on the classpath. -${TESTJAVA}/bin/javac -source 1.5 -d "${TESTCLASSES}" ${CP} -g \ +${TESTJAVA}/bin/javac -d "${TESTCLASSES}" ${CP} -g \ "${TESTSRC}"/"${TARGETCLASS}".java # #Run the test class, again with the classpath we need: From 7eb100548df6e4614823e9c6f8973d5bc9b774a5 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Fri, 4 Dec 2009 15:07:15 +0300 Subject: [PATCH 42/56] 6903354: deadlock involving Component.show & SunToolkit.getImageFromHash Reviewed-by: art, bae --- jdk/src/share/classes/sun/awt/SunToolkit.java | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index 3c7f16dff27..0b1e7aab48d 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -800,9 +800,9 @@ public abstract class SunToolkit extends Toolkit } - static SoftCache imgCache = new SoftCache(); + static final SoftCache imgCache = new SoftCache(); - static synchronized Image getImageFromHash(Toolkit tk, URL url) { + static Image getImageFromHash(Toolkit tk, URL url) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { @@ -830,32 +830,36 @@ public abstract class SunToolkit extends Toolkit sm.checkConnect(url.getHost(), url.getPort()); } } - Image img = (Image)imgCache.get(url); - if (img == null) { - try { - img = tk.createImage(new URLImageSource(url)); - imgCache.put(url, img); - } catch (Exception e) { + synchronized (imgCache) { + Image img = (Image)imgCache.get(url); + if (img == null) { + try { + img = tk.createImage(new URLImageSource(url)); + imgCache.put(url, img); + } catch (Exception e) { + } } + return img; } - return img; } - static synchronized Image getImageFromHash(Toolkit tk, + static Image getImageFromHash(Toolkit tk, String filename) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(filename); } - Image img = (Image)imgCache.get(filename); - if (img == null) { - try { - img = tk.createImage(new FileImageSource(filename)); - imgCache.put(filename, img); - } catch (Exception e) { + synchronized (imgCache) { + Image img = (Image)imgCache.get(filename); + if (img == null) { + try { + img = tk.createImage(new FileImageSource(filename)); + imgCache.put(filename, img); + } catch (Exception e) { + } } + return img; } - return img; } public Image getImage(String filename) { From 19061b3584422fc1e0016bfc6cdb66be38228f36 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Mon, 7 Dec 2009 15:27:29 +0800 Subject: [PATCH 43/56] 6879540: enable empty password for kerberos 5 Reviewed-by: valeriep, wetmore --- .../com/sun/crypto/provider/HmacCore.java | 4 +- .../sun/crypto/provider/PBKDF2KeyImpl.java | 39 +++++++++++++++---- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/jdk/src/share/classes/com/sun/crypto/provider/HmacCore.java b/jdk/src/share/classes/com/sun/crypto/provider/HmacCore.java index 87d9e04bc0e..5592a3e2a55 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/HmacCore.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/HmacCore.java @@ -36,7 +36,7 @@ import java.security.spec.*; /** * This class constitutes the core of HMAC- algorithms, where - * can be SHA1 or MD5, etc. + * can be SHA1 or MD5, etc. See RFC 2104 for spec. * * It also contains the implementation classes for the SHA-256, * SHA-384, and SHA-512 HMACs. @@ -116,7 +116,7 @@ final class HmacCore implements Cloneable { } byte[] secret = key.getEncoded(); - if (secret == null || secret.length == 0) { + if (secret == null) { throw new InvalidKeyException("Missing key data"); } diff --git a/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java b/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java index 2613a025e40..90ed410b831 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/PBKDF2KeyImpl.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 @@ -25,21 +25,19 @@ package com.sun.crypto.provider; -import java.io.*; +import java.io.ObjectStreamException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.security.KeyRep; import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.spec.InvalidKeySpecException; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; /** * This class represents a PBE key derived using PBKDF2 defined @@ -123,7 +121,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength); } - private static byte[] deriveKey(Mac prf, byte[] password, byte[] salt, + private static byte[] deriveKey(final Mac prf, final byte[] password, byte[] salt, int iterCount, int keyLengthInBit) { int keyLength = keyLengthInBit/8; byte[] key = new byte[keyLength]; @@ -133,7 +131,34 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { int intR = keyLength - (intL - 1)*hlen; // residue byte[] ui = new byte[hlen]; byte[] ti = new byte[hlen]; - SecretKey macKey = new SecretKeySpec(password, prf.getAlgorithm()); + // SecretKeySpec cannot be used, since password can be empty here. + SecretKey macKey = new SecretKey() { + @Override + public String getAlgorithm() { + return prf.getAlgorithm(); + } + @Override + public String getFormat() { + return "RAW"; + } + @Override + public byte[] getEncoded() { + return password; + } + @Override + public int hashCode() { + return Arrays.hashCode(password) * 41 + + prf.getAlgorithm().toLowerCase().hashCode(); + } + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (this.getClass() != obj.getClass()) return false; + SecretKey sk = (SecretKey)obj; + return prf.getAlgorithm().equalsIgnoreCase(sk.getAlgorithm()) && + Arrays.equals(password, sk.getEncoded()); + } + }; prf.init(macKey); byte[] ibytes = new byte[4]; @@ -230,7 +255,7 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { * @throws ObjectStreamException if a new object representing * this PBE key could not be created */ - private Object writeReplace() throws java.io.ObjectStreamException { + private Object writeReplace() throws ObjectStreamException { return new KeyRep(KeyRep.Type.SECRET, getAlgorithm(), getFormat(), getEncoded()); } From 45eee34489ddf0e78c1b813603229dfdc8e7197f Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Mon, 7 Dec 2009 15:29:44 +0800 Subject: [PATCH 44/56] 6886058: JNDI LDAP InitialLdapContext SECURITY_CREDENTIALS byte[] can be corrupted, then LDAP referral fails Reviewed-by: vinnie, xuelei --- jdk/src/share/classes/javax/naming/InitialContext.java | 4 +++- .../classes/javax/naming/directory/InitialDirContext.java | 4 +++- .../share/classes/javax/naming/ldap/InitialLdapContext.java | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/classes/javax/naming/InitialContext.java b/jdk/src/share/classes/javax/naming/InitialContext.java index 0e105d0f840..b9cc6e545dc 100644 --- a/jdk/src/share/classes/javax/naming/InitialContext.java +++ b/jdk/src/share/classes/javax/naming/InitialContext.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2005 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 @@ -198,6 +198,8 @@ public class InitialContext implements Context { * *

    This constructor will not modify environment * or save a reference to it, but may save a clone. + * Caller should not modify mutable keys and values in + * environment after it has been passed to the constructor. * * @param environment * environment used to create the initial context. diff --git a/jdk/src/share/classes/javax/naming/directory/InitialDirContext.java b/jdk/src/share/classes/javax/naming/directory/InitialDirContext.java index d96643acf4b..1a3aac6407e 100644 --- a/jdk/src/share/classes/javax/naming/directory/InitialDirContext.java +++ b/jdk/src/share/classes/javax/naming/directory/InitialDirContext.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2004 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 @@ -86,6 +86,8 @@ public class InitialDirContext extends InitialContext implements DirContext { * *

    This constructor will not modify environment * or save a reference to it, but may save a clone. + * Caller should not modify mutable keys and values in + * environment after it has been passed to the constructor. * * @param environment * environment used to create the initial DirContext. diff --git a/jdk/src/share/classes/javax/naming/ldap/InitialLdapContext.java b/jdk/src/share/classes/javax/naming/ldap/InitialLdapContext.java index 896cae8ccaf..757d29e7f78 100644 --- a/jdk/src/share/classes/javax/naming/ldap/InitialLdapContext.java +++ b/jdk/src/share/classes/javax/naming/ldap/InitialLdapContext.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2004 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 @@ -110,6 +110,8 @@ public class InitialLdapContext extends InitialDirContext implements LdapContext * *

    This constructor will not modify its parameters or * save references to them, but may save a clone or copy. + * Caller should not modify mutable keys and values in + * environment after it has been passed to the constructor. * *

    connCtls is used as the underlying context instance's * connection request controls. See the class description From 0974e6c1f357d0f6eb604ce7edc844f5d5136b96 Mon Sep 17 00:00:00 2001 From: Yuri Nesterenko Date: Mon, 7 Dec 2009 13:32:50 +0300 Subject: [PATCH 45/56] 5099725: AWT doesn't seem to handle MappingNotify events under X11 5036807: Pressing action keys "STOP/AGAIN/COMPOSE" generates keycode of F11/F12 keys 4787377: VK_STOP key on Solaris generates wrong Key Code Added an event processing lumped with similar native code for similar bugs. Reviewed-by: art --- jdk/make/sun/xawt/mapfile-vers | 3 + .../classes/sun/awt/X11/XEmbedHelper.java | 7 ++- .../solaris/classes/sun/awt/X11/XKeysym.java | 33 +++++++++-- .../solaris/classes/sun/awt/X11/XToolkit.java | 42 ++++++++++++++ .../classes/sun/awt/X11/XlibWrapper.java | 5 +- .../solaris/classes/sun/awt/X11/keysym2ucs.h | 33 +++++++++-- jdk/src/solaris/native/sun/xawt/XlibWrapper.c | 55 +++++++++++++++++++ 7 files changed, 168 insertions(+), 10 deletions(-) diff --git a/jdk/make/sun/xawt/mapfile-vers b/jdk/make/sun/xawt/mapfile-vers index d880ebb4f77..82fe94f63ec 100644 --- a/jdk/make/sun/xawt/mapfile-vers +++ b/jdk/make/sun/xawt/mapfile-vers @@ -126,6 +126,8 @@ SUNWprivate_1.1 { Java_sun_awt_X11_XlibWrapper_ServerVendor; Java_sun_awt_X11_XlibWrapper_VendorRelease; Java_sun_awt_X11_XlibWrapper_IsXsunKPBehavior; + Java_sun_awt_X11_XlibWrapper_IsSunKeyboard; + Java_sun_awt_X11_XlibWrapper_IsKanaKeyboard; Java_sun_awt_X11_XlibWrapper_SetToolkitErrorHandler; Java_sun_awt_X11_XlibWrapper_XSetErrorHandler; Java_sun_awt_X11_XlibWrapper_CallErrorHandler; @@ -306,6 +308,7 @@ SUNWprivate_1.1 { Java_sun_awt_X11_XlibWrapper_XkbTranslateKeyCode; Java_sun_awt_X11_XlibWrapper_XGetModifierMapping; Java_sun_awt_X11_XlibWrapper_XFreeModifiermap; + Java_sun_awt_X11_XlibWrapper_XRefreshKeyboardMapping; Java_sun_awt_X11_XlibWrapper_XChangeActivePointerGrab; Java_sun_awt_X11_XlibWrapper_XNextSecondaryLoopEvent; Java_sun_awt_X11_XlibWrapper_ExitSecondaryLoop; diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java index 57267039bd1..c60b4a53092 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java @@ -216,7 +216,12 @@ public class XEmbedHelper { XToolkit.awtLock(); try { - keycode = XWindow.getAWTKeyCodeForKeySym((int)keysym); + XKeysym.Keysym2JavaKeycode kc = XKeysym.getJavaKeycode( keysym ); + if(kc == null) { + keycode = java.awt.event.KeyEvent.VK_UNDEFINED; + }else{ + keycode = kc.getJavaKeycode(); + } } finally { XToolkit.awtUnlock(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XKeysym.java b/jdk/src/solaris/classes/sun/awt/X11/XKeysym.java index abf3c65c547..e81c6ce323e 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XKeysym.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XKeysym.java @@ -69,6 +69,8 @@ public class XKeysym { static Hashtable javaKeycode2KeysymHash = new Hashtable(); static long keysym_lowercase = unsafe.allocateMemory(Native.getLongSize()); static long keysym_uppercase = unsafe.allocateMemory(Native.getLongSize()); + static Keysym2JavaKeycode kanaLock = new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_KANA_LOCK, + java.awt.event.KeyEvent.KEY_LOCATION_STANDARD); private static PlatformLogger keyEventLog = PlatformLogger.getLogger("sun.awt.X11.kye.XKeysym"); public static char convertKeysym( long ks, int state ) { @@ -214,12 +216,35 @@ public class XKeysym { } return keysym; } + + /** + Return java.awt.KeyEvent constant meaning (Java) keycode, derived from X keysym. + Some keysyms maps to more than one keycode, these would require extra processing. + */ + static Keysym2JavaKeycode getJavaKeycode( long keysym ) { + if(keysym == XKeySymConstants.XK_Mode_switch){ + /* XK_Mode_switch on solaris maps either to VK_ALT_GRAPH (default) or VK_KANA_LOCK */ + if( XToolkit.isKanaKeyboard() ) { + return kanaLock; + } + }else if(keysym == XKeySymConstants.XK_L1){ + /* if it is Sun keyboard, trick hash to return VK_STOP else VK_F11 (default) */ + if( XToolkit.isSunKeyboard() ) { + keysym = XKeySymConstants.SunXK_Stop; + } + }else if(keysym == XKeySymConstants.XK_L2) { + /* if it is Sun keyboard, trick hash to return VK_AGAIN else VK_F12 (default) */ + if( XToolkit.isSunKeyboard() ) { + keysym = XKeySymConstants.SunXK_Again; + } + } + + return keysym2JavaKeycodeHash.get( keysym ); + } /** Return java.awt.KeyEvent constant meaning (Java) keycode, derived from X Window KeyEvent. Algorithm is, extract via XKeycodeToKeysym a proper keysym according to Xlib spec rules and err exceptions, then search a java keycode in a table. - Some keysyms maps to more than one keycode, these would require extra processing. If someone - points me to such a keysym. */ static Keysym2JavaKeycode getJavaKeycode( XKeyEvent ev ) { // get from keysym2JavaKeycodeHash. @@ -234,7 +259,7 @@ public class XKeysym { keysym = xkeycode2keysym(ev, ndx); } - Keysym2JavaKeycode jkc = keysym2JavaKeycodeHash.get( keysym ); + Keysym2JavaKeycode jkc = getJavaKeycode( keysym ); return jkc; } static int getJavaKeycodeOnly( XKeyEvent ev ) { @@ -259,7 +284,7 @@ public class XKeysym { ndx = 0; keysym = xkeycode2keysym_noxkb(ev, ndx); } - Keysym2JavaKeycode jkc = keysym2JavaKeycodeHash.get( keysym ); + Keysym2JavaKeycode jkc = getJavaKeycode( keysym ); return jkc == null ? java.awt.event.KeyEvent.VK_UNDEFINED : jkc.getJavaKeycode(); } static long javaKeycode2Keysym( int jkey ) { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java index f1ec8004264..b260a329cf7 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -533,6 +533,16 @@ public final class XToolkit extends UNIXToolkit implements Runnable { processGlobalMotionEvent(ev); } + if( ev.get_type() == XConstants.MappingNotify ) { + // The 'window' field in this event is unused. + // This application itself does nothing to initiate such an event + // (no calls of XChangeKeyboardMapping etc.). + // SunRay server sends this event to the application once on every + // keyboard (not just layout) change which means, quite seldom. + XlibWrapper.XRefreshKeyboardMapping(ev.pData); + resetKeyboardSniffer(); + setupModifierMap(); + } XBaseWindow.dispatchToWindow(ev); Collection dispatchers = null; @@ -2112,6 +2122,11 @@ public final class XToolkit extends UNIXToolkit implements Runnable { static final int XSUN_KP_BEHAVIOR = 1; static final int XORG_KP_BEHAVIOR = 2; + static final int IS_SUN_KEYBOARD = 1; + static final int IS_NONSUN_KEYBOARD = 2; + static final int IS_KANA_KEYBOARD = 1; + static final int IS_NONKANA_KEYBOARD = 2; + static int awt_IsXsunKPBehavior = 0; static boolean awt_UseXKB = false; @@ -2141,6 +2156,33 @@ public final class XToolkit extends UNIXToolkit implements Runnable { awtUnlock(); } } + + static int sunOrNotKeyboard = 0; + static int kanaOrNotKeyboard = 0; + static void resetKeyboardSniffer() { + sunOrNotKeyboard = 0; + kanaOrNotKeyboard = 0; + } + static boolean isSunKeyboard() { + if( sunOrNotKeyboard == 0 ) { + if( XlibWrapper.IsSunKeyboard( getDisplay() )) { + sunOrNotKeyboard = IS_SUN_KEYBOARD; + }else{ + sunOrNotKeyboard = IS_NONSUN_KEYBOARD; + } + } + return (sunOrNotKeyboard == IS_SUN_KEYBOARD); + } + static boolean isKanaKeyboard() { + if( kanaOrNotKeyboard == 0 ) { + if( XlibWrapper.IsKanaKeyboard( getDisplay() )) { + kanaOrNotKeyboard = IS_KANA_KEYBOARD; + }else{ + kanaOrNotKeyboard = IS_NONKANA_KEYBOARD; + } + } + return (kanaOrNotKeyboard == IS_KANA_KEYBOARD); + } static boolean isXKBenabled() { awtLock(); try { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java b/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java index 3ef2f69ae85..551e256427c 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java @@ -353,6 +353,8 @@ static native String XSetLocaleModifiers(String modifier_list); static native String ServerVendor(long display); static native int VendorRelease(long display); static native boolean IsXsunKPBehavior(long display); + static native boolean IsSunKeyboard(long display); + static native boolean IsKanaKeyboard(long display); static native void XBell(long display, int percent); @@ -513,8 +515,9 @@ static native String XSetLocaleModifiers(String modifier_list); long keysym_uppercase); static native long XGetModifierMapping(long display); - static native void XFreeModifiermap(long keymap); + static native void XRefreshKeyboardMapping(long event); + static native void XChangeActivePointerGrab(long display, int mask, long cursor, long time); diff --git a/jdk/src/solaris/classes/sun/awt/X11/keysym2ucs.h b/jdk/src/solaris/classes/sun/awt/X11/keysym2ucs.h index 32ecd66c987..e7c2c40b9a4 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/keysym2ucs.h +++ b/jdk/src/solaris/classes/sun/awt/X11/keysym2ucs.h @@ -107,6 +107,8 @@ tojava // Another use for reverse lookup: query keyboard state, for some key tojava static Hashtable javaKeycode2KeysymHash = new Hashtable(); tojava static long keysym_lowercase = unsafe.allocateMemory(Native.getLongSize()); tojava static long keysym_uppercase = unsafe.allocateMemory(Native.getLongSize()); +tojava static Keysym2JavaKeycode kanaLock = new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_KANA_LOCK, +tojava java.awt.event.KeyEvent.KEY_LOCATION_STANDARD); tojava private static PlatformLogger keyEventLog = PlatformLogger.getLogger("sun.awt.X11.kye.XKeysym"); tojava public static char convertKeysym( long ks, int state ) { tojava @@ -252,12 +254,35 @@ tojava } tojava } tojava return keysym; tojava } +tojava +tojava /** +tojava Return java.awt.KeyEvent constant meaning (Java) keycode, derived from X keysym. +tojava Some keysyms maps to more than one keycode, these would require extra processing. +tojava */ +tojava static Keysym2JavaKeycode getJavaKeycode( long keysym ) { +tojava if(keysym == XKeySymConstants.XK_Mode_switch){ +tojava /* XK_Mode_switch on solaris maps either to VK_ALT_GRAPH (default) or VK_KANA_LOCK */ +tojava if( XToolkit.isKanaKeyboard() ) { +tojava return kanaLock; +tojava } +tojava }else if(keysym == XKeySymConstants.XK_L1){ +tojava /* if it is Sun keyboard, trick hash to return VK_STOP else VK_F11 (default) */ +tojava if( XToolkit.isSunKeyboard() ) { +tojava keysym = XKeySymConstants.SunXK_Stop; +tojava } +tojava }else if(keysym == XKeySymConstants.XK_L2) { +tojava /* if it is Sun keyboard, trick hash to return VK_AGAIN else VK_F12 (default) */ +tojava if( XToolkit.isSunKeyboard() ) { +tojava keysym = XKeySymConstants.SunXK_Again; +tojava } +tojava } +tojava +tojava return keysym2JavaKeycodeHash.get( keysym ); +tojava } tojava /** tojava Return java.awt.KeyEvent constant meaning (Java) keycode, derived from X Window KeyEvent. tojava Algorithm is, extract via XKeycodeToKeysym a proper keysym according to Xlib spec rules and tojava err exceptions, then search a java keycode in a table. -tojava Some keysyms maps to more than one keycode, these would require extra processing. If someone -tojava points me to such a keysym. tojava */ tojava static Keysym2JavaKeycode getJavaKeycode( XKeyEvent ev ) { tojava // get from keysym2JavaKeycodeHash. @@ -272,7 +297,7 @@ tojava ndx = 0; tojava keysym = xkeycode2keysym(ev, ndx); tojava } tojava -tojava Keysym2JavaKeycode jkc = keysym2JavaKeycodeHash.get( keysym ); +tojava Keysym2JavaKeycode jkc = getJavaKeycode( keysym ); tojava return jkc; tojava } tojava static int getJavaKeycodeOnly( XKeyEvent ev ) { @@ -297,7 +322,7 @@ tojava // we only need primary-layer keysym to derive a java keycode tojava ndx = 0; tojava keysym = xkeycode2keysym_noxkb(ev, ndx); tojava } -tojava Keysym2JavaKeycode jkc = keysym2JavaKeycodeHash.get( keysym ); +tojava Keysym2JavaKeycode jkc = getJavaKeycode( keysym ); tojava return jkc == null ? java.awt.event.KeyEvent.VK_UNDEFINED : jkc.getJavaKeycode(); tojava } tojava static long javaKeycode2Keysym( int jkey ) { diff --git a/jdk/src/solaris/native/sun/xawt/XlibWrapper.c b/jdk/src/solaris/native/sun/xawt/XlibWrapper.c index 93fc0971c46..9607b6022d5 100644 --- a/jdk/src/solaris/native/sun/xawt/XlibWrapper.c +++ b/jdk/src/solaris/native/sun/xawt/XlibWrapper.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -1214,6 +1215,48 @@ JNIEXPORT jboolean JNICALL Java_sun_awt_X11_XlibWrapper_IsXsunKPBehavior } } + +JNIEXPORT jboolean JNICALL Java_sun_awt_X11_XlibWrapper_IsSunKeyboard +(JNIEnv *env, jclass clazz, jlong display) +{ + int xx; + AWT_CHECK_HAVE_LOCK(); + xx = XKeysymToKeycode((Display*)jlong_to_ptr(display), SunXK_F37); + return (!xx) ? JNI_FALSE : JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_sun_awt_X11_XlibWrapper_IsKanaKeyboard +(JNIEnv *env, jclass clazz, jlong display) +{ + int xx; + AWT_CHECK_HAVE_LOCK(); + static jboolean result = JNI_FALSE; + + int32_t minKeyCode, maxKeyCode, keySymsPerKeyCode; + KeySym *keySyms, *keySymsStart, keySym; + int32_t i; + int32_t kanaCount = 0; + + // There's no direct way to determine whether the keyboard has + // a kana lock key. From available keyboard mapping tables, it looks + // like only keyboards with the kana lock key can produce keysyms + // for kana characters. So, as an indirect test, we check for those. + XDisplayKeycodes((Display*)jlong_to_ptr(display), &minKeyCode, &maxKeyCode); + keySyms = XGetKeyboardMapping((Display*)jlong_to_ptr(display), minKeyCode, maxKeyCode - minKeyCode + 1, &keySymsPerKeyCode); + keySymsStart = keySyms; + for (i = 0; i < (maxKeyCode - minKeyCode + 1) * keySymsPerKeyCode; i++) { + keySym = *keySyms++; + if ((keySym & 0xff00) == 0x0400) { + kanaCount++; + } + } + XFree(keySymsStart); + + // use a (somewhat arbitrary) minimum so we don't get confused by a stray function key + result = kanaCount > 10; + return result ? JNI_TRUE : JNI_FALSE; +} + JavaVM* jvm = NULL; static int ToolkitErrorHandler(Display * dpy, XErrorEvent * event) { if (jvm != NULL) { @@ -1261,6 +1304,7 @@ JNIEXPORT jint JNICALL Java_sun_awt_X11_XlibWrapper_CallErrorHandler return (*(XErrorHandler)jlong_to_ptr(handler))((Display*) jlong_to_ptr(display), (XErrorEvent*) jlong_to_ptr(event_ptr)); } + /* * Class: sun_awt_X11_XlibWrapper * Method: PrintXErrorEvent @@ -1853,6 +1897,17 @@ Java_sun_awt_X11_XlibWrapper_XFreeModifiermap(JNIEnv *env, jclass clazz, AWT_CHECK_HAVE_LOCK(); XFreeModifiermap((XModifierKeymap*) jlong_to_ptr(keymap)); } +/* + * Class: sun_awt_X11_XlibWrapper + * Method: XRefreshKeyboardMapping + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_sun_awt_X11_XlibWrapper_XRefreshKeyboardMapping +(JNIEnv *env, jclass clazz, jlong event_ptr) +{ + AWT_CHECK_HAVE_LOCK(); + XRefreshKeyboardMapping((XMappingEvent*) jlong_to_ptr(event_ptr)); +} JNIEXPORT void JNICALL Java_sun_awt_X11_XlibWrapper_XChangeActivePointerGrab(JNIEnv *env, jclass clazz, From f4e991689854d90ded517be24c8d9894f6e0f5ba Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Mon, 7 Dec 2009 13:43:04 +0300 Subject: [PATCH 46/56] 6823138: Need to replace ComponentAccessor with AWTAccessor Reviewed-by: art, anthony --- jdk/src/share/classes/java/awt/Component.java | 69 ++- jdk/src/share/classes/java/awt/Window.java | 12 + .../share/classes/sun/awt/AWTAccessor.java | 124 ++++- .../classes/sun/awt/ComponentAccessor.java | 483 ------------------ .../classes/sun/awt/GlobalCursorManager.java | 4 +- jdk/src/share/classes/sun/awt/SunToolkit.java | 12 + .../share/classes/sun/awt/WindowAccessor.java | 96 ---- .../classes/sun/awt/X11/XComponentPeer.java | 34 +- .../classes/sun/awt/X11/XContentWindow.java | 5 +- .../classes/sun/awt/X11/XDecoratedPeer.java | 32 +- .../classes/sun/awt/X11/XDialogPeer.java | 6 +- .../sun/awt/X11/XDragSourceContextPeer.java | 5 +- .../classes/sun/awt/X11/XEmbedChildProxy.java | 7 +- .../sun/awt/X11/XGlobalCursorManager.java | 35 +- .../classes/sun/awt/X11/XTextAreaPeer.java | 19 +- .../classes/sun/awt/X11/XTextFieldPeer.java | 15 +- .../solaris/classes/sun/awt/X11/XToolkit.java | 2 +- .../classes/sun/awt/X11/XTrayIconPeer.java | 2 +- .../solaris/classes/sun/awt/X11/XWindow.java | 15 +- .../classes/sun/awt/X11/XWindowPeer.java | 31 +- .../classes/sun/awt/windows/WCanvasPeer.java | 2 - .../sun/awt/windows/WComponentPeer.java | 4 +- .../classes/sun/awt/windows/WDialogPeer.java | 2 +- .../sun/awt/windows/WFileDialogPeer.java | 4 +- .../sun/awt/windows/WPrintDialogPeer.java | 4 +- 25 files changed, 314 insertions(+), 710 deletions(-) delete mode 100644 jdk/src/share/classes/sun/awt/ComponentAccessor.java delete mode 100644 jdk/src/share/classes/sun/awt/WindowAccessor.java diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 6a942e9ec5d..702d81b8f9b 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -871,7 +871,7 @@ public abstract class Component implements ImageObserver, MenuContainer, return comp.canBeFocusOwner(); } - public boolean isVisible_NoClientCode(Component comp) { + public boolean isVisible(Component comp) { return comp.isVisible_NoClientCode(); } public void setRequestFocusController @@ -885,6 +885,71 @@ public abstract class Component implements ImageObserver, MenuContainer, public void setAppContext(Component comp, AppContext appContext) { comp.appContext = appContext; } + public Container getParent(Component comp) { + return comp.getParent_NoClientCode(); + } + public void setParent(Component comp, Container parent) { + comp.parent = parent; + } + public void setSize(Component comp, int width, int height) { + comp.width = width; + comp.height = height; + } + public Point getLocation(Component comp) { + return comp.location_NoClientCode(); + } + public void setLocation(Component comp, int x, int y) { + comp.x = x; + comp.y = y; + } + public boolean isEnabled(Component comp) { + return comp.isEnabledImpl(); + } + public boolean isDisplayable(Component comp) { + return comp.peer != null; + } + public Cursor getCursor(Component comp) { + return comp.getCursor_NoClientCode(); + } + public ComponentPeer getPeer(Component comp) { + return comp.peer; + } + public void setPeer(Component comp, ComponentPeer peer) { + comp.peer = peer; + } + public boolean isLightweight(Component comp) { + return (comp.peer instanceof LightweightPeer); + } + public boolean getIgnoreRepaint(Component comp) { + return comp.ignoreRepaint; + } + public int getWidth(Component comp) { + return comp.width; + } + public int getHeight(Component comp) { + return comp.height; + } + public int getX(Component comp) { + return comp.x; + } + public int getY(Component comp) { + return comp.y; + } + public Color getForeground(Component comp) { + return comp.foreground; + } + public Color getBackground(Component comp) { + return comp.background; + } + public void setBackground(Component comp, Color background) { + comp.background = background; + } + public Font getFont(Component comp) { + return comp.getFont_NoClientCode(); + } + public void processEvent(Component comp, AWTEvent e) { + comp.processEvent(e); + } }); } @@ -8021,7 +8086,7 @@ public abstract class Component implements ImageObserver, MenuContainer, Container getNativeContainer() { Container p = parent; while (p != null && p.peer instanceof LightweightPeer) { - p = p.getParent(); + p = p.getParent_NoClientCode(); } return p; } diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index 88a196918ed..a1882030cd2 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -3964,6 +3964,18 @@ public class Window extends Container implements Accessible { public void setLWRequestStatus(Window changed, boolean status) { changed.syncLWRequests = status; } + + public boolean isAutoRequestFocus(Window w) { + return w.autoRequestFocus; + } + + public boolean isTrayIconWindow(Window w) { + return w.isTrayIconWindow; + } + + public void setTrayIconWindow(Window w, boolean isTrayIconWindow) { + w.isTrayIconWindow = isTrayIconWindow; + } }); // WindowAccessor } // static diff --git a/jdk/src/share/classes/sun/awt/AWTAccessor.java b/jdk/src/share/classes/sun/awt/AWTAccessor.java index 67eb051003d..964e3e0e7ec 100644 --- a/jdk/src/share/classes/sun/awt/AWTAccessor.java +++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java @@ -98,7 +98,7 @@ public final class AWTAccessor { * Returns whether the component is visible without invoking * any client code. */ - boolean isVisible_NoClientCode(Component comp); + boolean isVisible(Component comp); /** * Sets the RequestFocusController. @@ -114,6 +114,112 @@ public final class AWTAccessor { * Sets the appContext of the component. */ void setAppContext(Component comp, AppContext appContext); + + /** + * Returns the parent of the component. + */ + Container getParent(Component comp); + + /** + * Sets the parent of the component to the specified parent. + */ + void setParent(Component comp, Container parent); + + /** + * Resizes the component to the specified width and height. + */ + void setSize(Component comp, int width, int height); + + /** + * Returns the location of the component. + */ + Point getLocation(Component comp); + + /** + * Moves the component to the new location. + */ + void setLocation(Component comp, int x, int y); + + /** + * Determines whether this component is enabled. + */ + boolean isEnabled(Component comp); + + /** + * Determines whether this component is displayable. + */ + boolean isDisplayable(Component comp); + + /** + * Gets the cursor set in the component. + */ + Cursor getCursor(Component comp); + + /** + * Returns the peer of the component. + */ + ComponentPeer getPeer(Component comp); + + /** + * Sets the peer of the component to the specified peer. + */ + void setPeer(Component comp, ComponentPeer peer); + + /** + * Determines whether this component is lightweight. + */ + boolean isLightweight(Component comp); + + /** + * Returns whether or not paint messages received from + * the operating system should be ignored. + */ + boolean getIgnoreRepaint(Component comp); + + /** + * Returns the width of the component. + */ + int getWidth(Component comp); + + /** + * Returns the height of the component. + */ + int getHeight(Component comp); + + /** + * Returns the x coordinate of the component. + */ + int getX(Component comp); + + /** + * Returns the y coordinate of the component. + */ + int getY(Component comp); + + /** + * Gets the foreground color of this component. + */ + Color getForeground(Component comp); + + /** + * Gets the background color of this component. + */ + Color getBackground(Component comp); + + /** + * Sets the background of this component to the specified color. + */ + void setBackground(Component comp, Color background); + + /** + * Gets the font of the component. + */ + Font getFont(Component comp); + + /** + * Processes events occurring on this component. + */ + void processEvent(Component comp, AWTEvent e); } /* @@ -169,6 +275,22 @@ public final class AWTAccessor { * components in the specified window to the specified value. */ void setLWRequestStatus(Window changed, boolean status); + + /** + * Indicates whether this window should receive focus on subsequently + * being shown, or being moved to the front. + */ + boolean isAutoRequestFocus(Window w); + + /** + * Indicates whether the specified window is an utility window for TrayIcon. + */ + boolean isTrayIconWindow(Window w); + + /** + * Marks the specified window as an utility window for TrayIcon. + */ + void setTrayIconWindow(Window w, boolean isTrayIconWindow); } /* diff --git a/jdk/src/share/classes/sun/awt/ComponentAccessor.java b/jdk/src/share/classes/sun/awt/ComponentAccessor.java deleted file mode 100644 index d186363e51b..00000000000 --- a/jdk/src/share/classes/sun/awt/ComponentAccessor.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright 2002-2007 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.awt; - -import java.awt.Component; -import java.awt.Container; -import java.awt.AWTEvent; -import java.awt.Font; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Point; - -import java.awt.peer.ComponentPeer; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - -import sun.util.logging.PlatformLogger; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -/** - * A collection of methods for modifying package private fields in AWT components. - * This class is meant to be used by Peer code only. Previously peer code - * got around this problem by modifying fields from native code. However - * as we move away from native code to Pure-java peers we need this class. - * - * @author Bino George - */ - - -public class ComponentAccessor -{ - private static Class componentClass; - private static Field fieldX; - private static Field fieldY; - private static Field fieldWidth; - private static Field fieldHeight; - private static Method methodGetParentNoClientCode; - private static Method methodGetFontNoClientCode; - private static Method methodProcessEvent; - private static Method methodEnableEvents; - private static Field fieldParent; - private static Field fieldBackground; - private static Field fieldForeground; - private static Field fieldFont; - private static Field fieldPacked; - private static Field fieldIgnoreRepaint; - private static Field fieldPeer; - private static Field fieldVisible; - private static Method methodIsEnabledImpl; - private static Method methodGetCursorNoClientCode; - private static Method methodLocationNoClientCode; - - private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.ComponentAccessor"); - - private ComponentAccessor() { - } - - static { - AccessController.doPrivileged( new PrivilegedAction() { - public Object run() { - try { - componentClass = Class.forName("java.awt.Component"); - fieldX = componentClass.getDeclaredField("x"); - fieldX.setAccessible(true); - fieldY = componentClass.getDeclaredField("y"); - fieldY.setAccessible(true); - fieldWidth = componentClass.getDeclaredField("width"); - fieldWidth.setAccessible(true); - fieldHeight = componentClass.getDeclaredField("height"); - fieldHeight.setAccessible(true); - fieldForeground = componentClass.getDeclaredField("foreground"); - fieldForeground.setAccessible(true); - fieldBackground = componentClass.getDeclaredField("background"); - fieldBackground.setAccessible(true); - fieldFont = componentClass.getDeclaredField("font"); - fieldFont.setAccessible(true); - methodGetParentNoClientCode = componentClass.getDeclaredMethod("getParent_NoClientCode", (Class[]) null); - methodGetParentNoClientCode.setAccessible(true); - methodGetFontNoClientCode = componentClass.getDeclaredMethod("getFont_NoClientCode", (Class[]) null); - methodGetFontNoClientCode.setAccessible(true); - Class[] argTypes = { AWTEvent.class }; - methodProcessEvent = componentClass.getDeclaredMethod("processEvent",argTypes); - methodProcessEvent.setAccessible(true); - Class[] argTypesForMethodEnableEvents = { Long.TYPE }; - methodEnableEvents = componentClass.getDeclaredMethod("enableEvents",argTypesForMethodEnableEvents); - methodEnableEvents.setAccessible(true); - - fieldParent = componentClass.getDeclaredField("parent"); - fieldParent.setAccessible(true); - fieldPacked = componentClass.getDeclaredField("isPacked"); - fieldPacked.setAccessible(true); - fieldIgnoreRepaint = componentClass.getDeclaredField("ignoreRepaint"); - fieldIgnoreRepaint.setAccessible(true); - - fieldPeer = componentClass.getDeclaredField("peer"); - fieldPeer.setAccessible(true); - - fieldVisible = componentClass.getDeclaredField("visible"); - fieldVisible.setAccessible(true); - - methodIsEnabledImpl = componentClass.getDeclaredMethod("isEnabledImpl", (Class[]) null); - methodIsEnabledImpl.setAccessible(true); - - methodGetCursorNoClientCode = componentClass.getDeclaredMethod("getCursor_NoClientCode", (Class[]) null); - methodGetCursorNoClientCode.setAccessible(true); - - methodLocationNoClientCode = componentClass.getDeclaredMethod("location_NoClientCode", (Class[]) null); - methodLocationNoClientCode.setAccessible(true); - } - catch (NoSuchFieldException e) { - log.fine("Unable to initialize ComponentAccessor", e); - } - catch (ClassNotFoundException e) { - log.fine("Unable to initialize ComponentAccessor", e); - } - catch (NoSuchMethodException e) { - log.fine("Unable to initialize ComponentAccessor", e); - } - // to please javac - return null; - } - }); - } - - public static void setX(Component c, int x) - { - try { - fieldX.setInt(c,x); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static void setY(Component c, int y) - { - try { - fieldY.setInt(c,y); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static void setWidth(Component c, int width) - { - try { - fieldWidth.setInt(c,width); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static void setHeight(Component c, int height) - { - try { - fieldHeight.setInt(c,height); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static void setBounds(Component c, int x, int y, int width, int height) - { - try { - fieldX.setInt(c,x); - fieldY.setInt(c,y); - fieldWidth.setInt(c,width); - fieldHeight.setInt(c,height); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static int getX(Component c) { - try { - return fieldX.getInt(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return 0; - } - - public static int getY(Component c) { - try { - return fieldY.getInt(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return 0; - } - - public static int getWidth(Component c) { - try { - return fieldWidth.getInt(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return 0; - } - - public static int getHeight(Component c) { - try { - return fieldHeight.getInt(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return 0; - } - - public static boolean getIsPacked(Component c) { - try { - return fieldPacked.getBoolean(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return false; - } - - public static Container getParent_NoClientCode(Component c) { - Container parent=null; - - try { - parent = (Container) methodGetParentNoClientCode.invoke(c, (Object[]) null); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - - return parent; - } - - public static Font getFont_NoClientCode(Component c) { - Font font=null; - - try { - font = (Font) methodGetFontNoClientCode.invoke(c, (Object[]) null); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - - return font; - } - - public static void processEvent(Component c, AWTEvent event) { - Font font=null; - - try { - Object[] args = new Object[1]; - args[0] = event; - methodProcessEvent.invoke(c,args); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - } - - public static void enableEvents(Component c, long event_mask) { - try { - Object[] args = new Object[1]; - args[0] = Long.valueOf(event_mask); - methodEnableEvents.invoke(c,args); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - } - - public static void setParent(Component c, Container parent) - { - try { - fieldParent.set(c,parent); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static Color getForeground(Component c) - { - Color color = null; - try { - color = (Color) fieldForeground.get(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return color; - } - - public static Color getBackground(Component c) - { - Color color = null; - try { - color = (Color) fieldBackground.get(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return color; - } - - public static void setBackground(Component c, Color color) { - try { - fieldBackground.set(c, color); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static Font getFont(Component c) - { - Font f = null; - try { - f = (Font) fieldFont.get(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return f; - } - - public static ComponentPeer getPeer(Component c) { - ComponentPeer peer = null; - try { - peer = (ComponentPeer)fieldPeer.get(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return peer; - } - - public static void setPeer(Component c, ComponentPeer peer) { - try { - fieldPeer.set(c, peer); - } catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - } - - public static boolean getIgnoreRepaint(Component comp) { - try { - return fieldIgnoreRepaint.getBoolean(comp); - } - catch (IllegalAccessException e) { - log.fine("Unable to access the Component object", e); - } - - return false; - } - - public static boolean getVisible(Component c) { - try { - return fieldVisible.getBoolean(c); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - return false; - } - - public static boolean isEnabledImpl(Component c) { - boolean enabled = true; - try { - enabled = (Boolean) methodIsEnabledImpl.invoke(c, (Object[]) null); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - return enabled; - } - - public static Cursor getCursor_NoClientCode(Component c) { - Cursor cursor = null; - - try { - cursor = (Cursor) methodGetCursorNoClientCode.invoke(c, (Object[]) null); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - - return cursor; - } - - public static Point getLocation_NoClientCode(Component c) { - Point loc = null; - - try { - loc = (Point) methodLocationNoClientCode.invoke(c, (Object[]) null); - } - catch (IllegalAccessException e) - { - log.fine("Unable to access the Component object", e); - } - catch (InvocationTargetException e) { - log.fine("Unable to invoke on the Component object", e); - } - - return loc; - } - -} diff --git a/jdk/src/share/classes/sun/awt/GlobalCursorManager.java b/jdk/src/share/classes/sun/awt/GlobalCursorManager.java index ae54c2b014a..8a0eb4dd476 100644 --- a/jdk/src/share/classes/sun/awt/GlobalCursorManager.java +++ b/jdk/src/share/classes/sun/awt/GlobalCursorManager.java @@ -183,7 +183,7 @@ public abstract class GlobalCursorManager { } if (comp instanceof Window) { - p = ComponentAccessor.getLocation_NoClientCode(comp); + p = AWTAccessor.getComponentAccessor().getLocation(comp); } else if (comp instanceof Container) { p = getLocationOnScreen(comp); } @@ -202,7 +202,7 @@ public abstract class GlobalCursorManager { } } - setCursor(comp, ComponentAccessor.getCursor_NoClientCode(comp), useCache); + setCursor(comp, AWTAccessor.getComponentAccessor().getCursor(comp), useCache); } catch (IllegalComponentStateException e) { // Shouldn't happen, but if it does, abort. diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java index 0b1e7aab48d..31f577bd1ea 100644 --- a/jdk/src/share/classes/sun/awt/SunToolkit.java +++ b/jdk/src/share/classes/sun/awt/SunToolkit.java @@ -1118,6 +1118,18 @@ public abstract class SunToolkit extends Toolkit return Toolkit.getNativeContainer(c); } + /** + * Gives native peers the ability to query the closest HW component. + * If the given component is heavyweight, then it returns this. Otherwise, + * it goes one level up in the hierarchy and tests next component. + */ + public static Component getHeavyweightComponent(Component c) { + while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) { + c = AWTAccessor.getComponentAccessor().getParent(c); + } + return c; + } + /** * Returns a new input method window, with behavior as specified in * {@link java.awt.im.spi.InputMethodContext#createInputMethodWindow}. diff --git a/jdk/src/share/classes/sun/awt/WindowAccessor.java b/jdk/src/share/classes/sun/awt/WindowAccessor.java deleted file mode 100644 index e1fb7c4fc64..00000000000 --- a/jdk/src/share/classes/sun/awt/WindowAccessor.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2007 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.awt; - -import java.awt.Window; - -import java.lang.reflect.Field; - -import sun.util.logging.PlatformLogger; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -public class WindowAccessor { - - private static Class windowClass; - private static Field fieldIsAutoRequestFocus; - private static Field fieldIsTrayIconWindow; - - private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.WindowAccessor"); - - private WindowAccessor() { - } - - static { - AccessController.doPrivileged( new PrivilegedAction() { - public Object run() { - try { - windowClass = Class.forName("java.awt.Window"); - fieldIsAutoRequestFocus = windowClass.getDeclaredField("autoRequestFocus"); - fieldIsAutoRequestFocus.setAccessible(true); - fieldIsTrayIconWindow = windowClass.getDeclaredField("isTrayIconWindow"); - fieldIsTrayIconWindow.setAccessible(true); - - } catch (NoSuchFieldException e) { - log.fine("Unable to initialize WindowAccessor: ", e); - } catch (ClassNotFoundException e) { - log.fine("Unable to initialize WindowAccessor: ", e); - } - return null; - } - }); - } - - public static boolean isAutoRequestFocus(Window w) { - try { - return fieldIsAutoRequestFocus.getBoolean(w); - - } catch (IllegalAccessException e) { - log.fine("Unable to access the Window object", e); - } - return true; - } - - public static boolean isTrayIconWindow(Window w) { - try { - return fieldIsTrayIconWindow.getBoolean(w); - - } catch (IllegalAccessException e) { - log.fine("Unable to access the Window object", e); - } - return false; - } - - public static void setTrayIconWindow(Window w, boolean isTrayIconWindow) { - try { - fieldIsTrayIconWindow.set(w, isTrayIconWindow); - - } catch (IllegalAccessException e) { - log.fine("Unable to access the Window object", e); - } - } -} diff --git a/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java index a0ca6efb43d..78bc4e02c16 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java @@ -212,27 +212,6 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget return true; } - static XComponentPeer getNativeContainer(Component comp) { - if (comp == null) { - return null; - } - - synchronized(comp.getTreeLock()) { - while (comp != null && (ComponentAccessor.getPeer(comp) instanceof LightweightPeer)) { - comp = ComponentAccessor.getParent_NoClientCode(comp); - } - - if (comp != null) { - ComponentPeer peer = ComponentAccessor.getPeer(comp); - if (peer != null && peer instanceof XComponentPeer) { - return (XComponentPeer)peer; - } - } - } - - return null; - } - /************************************************* * FOCUS STUFF *************************************************/ @@ -508,13 +487,14 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget } XWindowPeer getParentTopLevel() { - Container parent = (target instanceof Container) ? ((Container)target) : (ComponentAccessor.getParent_NoClientCode(target)); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + Container parent = (target instanceof Container) ? ((Container)target) : (compAccessor.getParent(target)); // Search for parent window while (parent != null && !(parent instanceof Window)) { - parent = ComponentAccessor.getParent_NoClientCode(parent); + parent = compAccessor.getParent(parent); } if (parent != null) { - return (XWindowPeer)ComponentAccessor.getPeer(parent); + return (XWindowPeer)compAccessor.getPeer(parent); } else { return null; } @@ -828,7 +808,7 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget public void endLayout() { if (!paintPending && !paintArea.isEmpty() - && !ComponentAccessor.getIgnoreRepaint(target)) + && !AWTAccessor.getComponentAccessor().getIgnoreRepaint(target)) { // if not waiting for native painting repaint damaged area postEvent(new PaintEvent(target, PaintEvent.PAINT, @@ -1239,11 +1219,11 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget // End of multi-buffering public void notifyTextComponentChange(boolean add){ - Container parent = ComponentAccessor.getParent_NoClientCode(target); + Container parent = AWTAccessor.getComponentAccessor().getParent(target); while(!(parent == null || parent instanceof java.awt.Frame || parent instanceof java.awt.Dialog)) { - parent = ComponentAccessor.getParent_NoClientCode(parent); + parent = AWTAccessor.getComponentAccessor().getParent(parent); } /* FIX ME - FIX ME need to implement InputMethods diff --git a/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java index 0c4cf626e0f..d55dc42b0bc 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java @@ -32,7 +32,7 @@ import java.awt.event.ComponentEvent; import sun.util.logging.PlatformLogger; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; /** * This class implements window which serves as content window for decorated frames. @@ -135,8 +135,7 @@ public final class XContentWindow extends XWindow { // NOTE: This method may be called by privileged threads. // DO NOT INVOKE CLIENT CODE ON THIS THREAD! public void handleResize(Rectangle bounds) { - ComponentAccessor.setWidth((Component)target, bounds.width); - ComponentAccessor.setHeight((Component)target, bounds.height); + AWTAccessor.getComponentAccessor().setSize((Component)target, bounds.width, bounds.height); postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED)); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java index be9599ce332..50d50dd02de 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java @@ -32,7 +32,7 @@ import java.awt.event.WindowEvent; import sun.util.logging.PlatformLogger; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; import sun.awt.SunToolkit; abstract class XDecoratedPeer extends XWindowPeer { @@ -167,10 +167,11 @@ abstract class XDecoratedPeer extends XWindowPeer { } public Graphics getGraphics() { + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); return getGraphics(content.surfaceData, - ComponentAccessor.getForeground(target), - ComponentAccessor.getBackground(target), - ComponentAccessor.getFont_NoClientCode(target)); + compAccessor.getForeground(target), + compAccessor.getBackground(target), + compAccessor.getFont(target)); } public void setTitle(String title) { @@ -404,8 +405,7 @@ abstract class XDecoratedPeer extends XWindowPeer { public void handleMoved(WindowDimensions dims) { Point loc = dims.getLocation(); - ComponentAccessor.setX((Component)target, loc.x); - ComponentAccessor.setY((Component)target, loc.y); + AWTAccessor.getComponentAccessor().setLocation((Component)target, loc.x, loc.y); postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED)); } @@ -511,8 +511,8 @@ abstract class XDecoratedPeer extends XWindowPeer { // its location changes. Point oldLocation = getLocation(); - Point newLocation = new Point(ComponentAccessor.getX((Component)target), - ComponentAccessor.getY((Component)target)); + Point newLocation = new Point(AWTAccessor.getComponentAccessor().getX((Component)target), + AWTAccessor.getComponentAccessor().getY((Component)target)); if (!newLocation.equals(oldLocation)) { handleMoved(newDimensions); @@ -710,10 +710,7 @@ abstract class XDecoratedPeer extends XWindowPeer { updateChildrenSizes(); // Bounds of the window - Rectangle targetBounds = new Rectangle(ComponentAccessor.getX((Component)target), - ComponentAccessor.getY((Component)target), - ComponentAccessor.getWidth((Component)target), - ComponentAccessor.getHeight((Component)target)); + Rectangle targetBounds = AWTAccessor.getComponentAccessor().getBounds((Component)target); Point newLocation = targetBounds.getLocation(); if (xe.get_send_event() || runningWM == XWM.NO_WM || XWM.isNonReparentingWM()) { @@ -1042,10 +1039,11 @@ abstract class XDecoratedPeer extends XWindowPeer { } final void dumpTarget() { - int getWidth = ComponentAccessor.getWidth((Component)target); - int getHeight = ComponentAccessor.getHeight((Component)target); - int getTargetX = ComponentAccessor.getX((Component)target); - int getTargetY = ComponentAccessor.getY((Component)target); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + int getWidth = compAccessor.getWidth((Component)target); + int getHeight = compAccessor.getHeight((Component)target); + int getTargetX = compAccessor.getX((Component)target); + int getTargetY = compAccessor.getY((Component)target); System.err.println(">>> Target: " + getTargetX + ", " + getTargetY + ", " + getWidth + ", " + getHeight); } @@ -1208,7 +1206,7 @@ abstract class XDecoratedPeer extends XWindowPeer { Window owner = XWindowPeer.getDecoratedOwner(actualFocusedWindow); if (owner != null && owner == target) { - setActualFocusedWindow((XWindowPeer) ComponentAccessor.getPeer(actualFocusedWindow)); + setActualFocusedWindow((XWindowPeer) AWTAccessor.getComponentAccessor().getPeer(actualFocusedWindow)); } } super.handleWindowFocusOut(oppositeWindow, serial); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java index ef7bfdaa03c..6b1da251044 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java @@ -28,7 +28,7 @@ import java.util.*; import java.awt.*; import java.awt.peer.*; import java.awt.event.*; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; import sun.awt.*; @@ -117,7 +117,7 @@ class XDialogPeer extends XDecoratedPeer implements DialogPeer { try { javaToplevels = XWindowPeer.collectJavaToplevels(); for (Window w : toBlock) { - XWindowPeer wp = (XWindowPeer)ComponentAccessor.getPeer(w); + XWindowPeer wp = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w); if (wp != null) { wp.setModalBlocked((Dialog)target, true, javaToplevels); } @@ -139,7 +139,7 @@ class XDialogPeer extends XDecoratedPeer implements DialogPeer { XWindowPeer focusedWindowPeer = null; if (focusedWindow != null) { - focusedWindowPeer = (XWindowPeer)ComponentAccessor.getPeer(focusedWindow); + focusedWindowPeer = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(focusedWindow); } else { /* * For the case when a potential blocked window is not yet focused diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java index 5188fe7169b..da84049febb 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java @@ -39,11 +39,10 @@ import java.util.*; import sun.util.logging.PlatformLogger; -import sun.awt.ComponentAccessor; - import sun.awt.dnd.SunDragSourceContextPeer; import sun.awt.dnd.SunDropTargetContextPeer; import sun.awt.SunToolkit; +import sun.awt.AWTAccessor; /** * The XDragSourceContextPeer class is the class responsible for handling @@ -117,7 +116,7 @@ public final class XDragSourceContextPeer XWindowPeer wpeer = null; for (c = component; c != null && !(c instanceof Window); - c = ComponentAccessor.getParent_NoClientCode(c)); + c = AWTAccessor.getComponentAccessor().getParent(c)); if (c instanceof Window) { wpeer = (XWindowPeer)c.getPeer(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxy.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxy.java index 47b4da501e0..baf3a14f075 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxy.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxy.java @@ -27,7 +27,7 @@ package sun.awt.X11; import java.awt.Component; import java.awt.Toolkit; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; public class XEmbedChildProxy extends Component { long handle; @@ -39,8 +39,9 @@ public class XEmbedChildProxy extends Component { public void addNotify() { synchronized(getTreeLock()) { - if (ComponentAccessor.getPeer(this) == null) { - ComponentAccessor.setPeer(this, ((XToolkit)Toolkit.getDefaultToolkit()).createEmbedProxy(this)); + if (AWTAccessor.getComponentAccessor().getPeer(this) == null) { + AWTAccessor.getComponentAccessor(). + setPeer(this,((XToolkit)Toolkit.getDefaultToolkit()).createEmbedProxy(this)); } super.addNotify(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java b/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java index 43ae1f89004..244c0ac6aff 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java @@ -31,7 +31,7 @@ import java.awt.peer.LightweightPeer; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; import sun.awt.GlobalCursorManager; import sun.awt.SunToolkit; @@ -94,11 +94,11 @@ public final class XGlobalCursorManager extends GlobalCursorManager { nc = nativeContainer.get(); } } else { - nc = getNativeContainer(comp); + nc = SunToolkit.getHeavyweightComponent(comp); } if (nc != null) { - ComponentPeer nc_peer = ComponentAccessor.getPeer(nc); + ComponentPeer nc_peer = AWTAccessor.getComponentAccessor().getPeer(nc); if (nc_peer instanceof XComponentPeer) { synchronized (this) { nativeContainer = new WeakReference(nc); @@ -133,13 +133,6 @@ public final class XGlobalCursorManager extends GlobalCursorManager { updateGrabbedCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - private Component getNativeContainer(Component comp) { - while (comp != null && ComponentAccessor.getPeer(comp) instanceof LightweightPeer) { - comp = ComponentAccessor.getParent_NoClientCode(comp); - } - return comp; - } - protected void getCursorPos(Point p) { if (!((XToolkit)Toolkit.getDefaultToolkit()).getLastCursorPos(p)) { @@ -186,27 +179,29 @@ public final class XGlobalCursorManager extends GlobalCursorManager { } private Cursor getCapableCursor(Component comp) { + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + Component c = comp; while ((c != null) && !(c instanceof Window) - && ComponentAccessor.isEnabledImpl(c) - && ComponentAccessor.getVisible(c) - && ComponentAccessor.getPeer(c) != null) + && compAccessor.isEnabled(c) + && compAccessor.isVisible(c) + && compAccessor.isDisplayable(c)) { - c = ComponentAccessor.getParent_NoClientCode(c); + c = compAccessor.getParent(c); } if (c instanceof Window) { - return (ComponentAccessor.isEnabledImpl(c) - && ComponentAccessor.getVisible(c) - && (ComponentAccessor.getPeer(c) != null) - && ComponentAccessor.isEnabledImpl(comp)) + return (compAccessor.isEnabled(c) + && compAccessor.isVisible(c) + && compAccessor.isDisplayable(c) + && compAccessor.isEnabled(comp)) ? - ComponentAccessor.getCursor_NoClientCode(comp) + compAccessor.getCursor(comp) : Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); } else if (c == null) { return null; } - return getCapableCursor(ComponentAccessor.getParent_NoClientCode(c)); + return getCapableCursor(compAccessor.getParent(c)); } /* This methods needs to be called from within XToolkit.awtLock / XToolkit.awtUnlock section. */ diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTextAreaPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTextAreaPeer.java index d0b2da84d06..51cc74ce6d8 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTextAreaPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTextAreaPeer.java @@ -60,7 +60,7 @@ import javax.swing.text.JTextComponent; import javax.swing.plaf.BorderUIResource; import java.awt.im.InputMethodRequests; import sun.awt.CausedFocusEvent; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { @@ -119,13 +119,14 @@ class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { textPane.setVisible(true); textPane.validate(); - foreground = ComponentAccessor.getForeground(target); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + foreground = compAccessor.getForeground(target); if (foreground == null) { foreground = SystemColor.textText; } setForeground(foreground); - background = ComponentAccessor.getBackground(target); + background = compAccessor.getBackground(target); if (background == null) { if (target.isEditable()) background = SystemColor.text; else background = SystemColor.control; @@ -134,8 +135,8 @@ class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { if (!target.isBackgroundSet()) { // This is a way to set the background color of the TextArea - // without calling setBackground - go through reflection - ComponentAccessor.setBackground(target, background); + // without calling setBackground - go through accessor + compAccessor.setBackground(target, background); } if (!target.isForegroundSet()) { target.setForeground(SystemColor.textText); @@ -311,13 +312,13 @@ class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { } void handleJavaKeyEvent(KeyEvent e) { - ComponentAccessor.processEvent(jtext,e); + AWTAccessor.getComponentAccessor().processEvent(jtext,e); } public boolean handlesWheelScrolling() { return true; } void handleJavaMouseWheelEvent(MouseWheelEvent e) { - ComponentAccessor.processEvent(textPane,e); + AWTAccessor.getComponentAccessor().processEvent(textPane,e); } public void handleJavaMouseEvent( MouseEvent e ) { @@ -1111,7 +1112,7 @@ class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { this.xwin = xwin; setDoubleBuffered(true); jt.addFocusListener(this); - ComponentAccessor.setParent(this,parent); + AWTAccessor.getComponentAccessor().setParent(this,parent); setViewportBorder(new BevelBorder(false,SystemColor.controlDkShadow,SystemColor.controlLtHighlight) ); this.jtext = jt; setFocusable(false); @@ -1308,7 +1309,7 @@ class XTextAreaPeer extends XComponentPeer implements TextAreaPeer { c = current.getButton(); p = toLocalSpace( c, p ); } - ComponentAccessor.processEvent( c, newMouseEvent( c, p, event ) ); + AWTAccessor.getComponentAccessor().processEvent( c, newMouseEvent( c, p, event ) ); break; } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java index 981478fd789..f8726e41899 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java @@ -55,7 +55,7 @@ import java.awt.im.InputMethodRequests; import sun.util.logging.PlatformLogger; import sun.awt.CausedFocusEvent; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; public class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XTextField"); @@ -115,13 +115,14 @@ public class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { setBounds(x, y, width, height, SET_BOUNDS); - foreground = ComponentAccessor.getForeground(target); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + foreground = compAccessor.getForeground(target); if (foreground == null) foreground = SystemColor.textText; setForeground(foreground); - background = ComponentAccessor.getBackground(target); + background = compAccessor.getBackground(target); if (background == null) { if (((TextField)target).isEditable()) background = SystemColor.text; else background = SystemColor.control; @@ -130,8 +131,8 @@ public class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { if (!target.isBackgroundSet()) { // This is a way to set the background color of the TextArea - // without calling setBackground - go through reflection - ComponentAccessor.setBackground(target, background); + // without calling setBackground - go through accessor + compAccessor.setBackground(target, background); } if (!target.isForegroundSet()) { target.setForeground(SystemColor.textText); @@ -392,7 +393,7 @@ public class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { } void handleJavaKeyEvent(KeyEvent e) { - ComponentAccessor.processEvent(xtext,e); + AWTAccessor.getComponentAccessor().processEvent(xtext,e); } @@ -620,7 +621,7 @@ public class XTextFieldPeer extends XComponentPeer implements TextFieldPeer { this.peer = peer; setDoubleBuffered(true); setFocusable(false); - ComponentAccessor.setParent(this,parent); + AWTAccessor.getComponentAccessor().setParent(this,parent); setBackground(peer.getPeerBackground()); setForeground(peer.getPeerForeground()); setFont(peer.getPeerFont()); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java index f1ec8004264..7ad6980e5f8 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -626,7 +626,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable { Component owner = XKeyboardFocusManagerPeer.getCurrentNativeFocusOwner(); if (owner != null) { - XWindow ownerWindow = (XWindow) ComponentAccessor.getPeer(owner); + XWindow ownerWindow = (XWindow) AWTAccessor.getComponentAccessor().getPeer(owner); if (ownerWindow != null) { w = ownerWindow.getContentWindow(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java index 64ab4c268b0..f4b29f7d52a 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java @@ -295,7 +295,7 @@ public class XTrayIconPeer implements TrayIconPeer, } public static void suppressWarningString(Window w) { - WindowAccessor.setTrayIconWindow(w, true); + AWTAccessor.getWindowAccessor().setTrayIconWindow(w, true); } public void setToolTip(String tooltip) { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java index 58d1fe8bd7c..e482d69aad8 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java @@ -325,9 +325,9 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { if (!(target instanceof Container) || win == null || win.getTarget() == null) { return false; } - Container parent = ComponentAccessor.getParent_NoClientCode(win.target); + Container parent = AWTAccessor.getComponentAccessor().getParent(win.target); while (parent != null && parent != target) { - parent = ComponentAccessor.getParent_NoClientCode(parent); + parent = AWTAccessor.getComponentAccessor().getParent(parent); } return (parent == target); } @@ -560,10 +560,11 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { int h = xe.get_height(); Component target = (Component)getEventSource(); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); - if (!ComponentAccessor.getIgnoreRepaint(target) - && ComponentAccessor.getWidth(target) != 0 - && ComponentAccessor.getHeight(target) != 0) + if (!compAccessor.getIgnoreRepaint(target) + && compAccessor.getWidth(target) != 0 + && compAccessor.getHeight(target) != 0) { handleExposeEvent(target, x, y, w, h); } @@ -950,7 +951,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { XAwtState.setComponentMouseEntered(null); } } else { - ((XComponentPeer) ComponentAccessor.getPeer(target)) + ((XComponentPeer) AWTAccessor.getComponentAccessor().getPeer(target)) .pSetCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } @@ -1387,7 +1388,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { Component comp = target; while (comp != null && !(comp instanceof Window)) { - comp = ComponentAccessor.getParent_NoClientCode(comp); + comp = AWTAccessor.getComponentAccessor().getParent(comp); } // applets, embedded, etc - translate directly diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java index b7957dd8f92..30d93365b6e 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java @@ -51,8 +51,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import sun.util.logging.PlatformLogger; import sun.awt.AWTAccessor; -import sun.awt.ComponentAccessor; -import sun.awt.WindowAccessor; import sun.awt.DisplayChangedListener; import sun.awt.SunToolkit; import sun.awt.X11GraphicsDevice; @@ -254,7 +252,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (((Window)target).getWarningString() != null) { // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip // and TrayIcon balloon windows without a warning window. - if (!WindowAccessor.isTrayIconWindow((Window)target)) { + if (!AWTAccessor.getWindowAccessor().isTrayIconWindow((Window)target)) { warningWindow = new XWarningWindow((Window)target, getWindow(), this); } } @@ -546,7 +544,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, boolean isAutoRequestFocus() { if (XToolkit.isToolkitThread()) { - return WindowAccessor.isAutoRequestFocus((Window)target); + return AWTAccessor.getWindowAccessor().isAutoRequestFocus((Window)target); } else { return ((Window)target).isAutoRequestFocus(); } @@ -1086,10 +1084,11 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (warningWindow != null) { // We can't use the coordinates stored in the XBaseWindow since // they are zeros for decorated frames. - int x = ComponentAccessor.getX(target); - int y = ComponentAccessor.getY(target); - int width = ComponentAccessor.getWidth(target); - int height = ComponentAccessor.getHeight(target); + AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor(); + int x = compAccessor.getX(target); + int y = compAccessor.getY(target); + int width = compAccessor.getWidth(target); + int height = compAccessor.getHeight(target); warningWindow.reposition(x, y, width, height); } } @@ -1172,7 +1171,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (isSimpleWindow()) { if (target == XKeyboardFocusManagerPeer.getCurrentNativeFocusedWindow()) { Window owner = getDecoratedOwner((Window)target); - ((XWindowPeer)ComponentAccessor.getPeer(owner)).requestWindowFocus(); + ((XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(owner)).requestWindowFocus(); } } } @@ -1399,7 +1398,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, XToolkit.awtLock(); try { if (isReparented() && delayedModalBlocking) { - addToTransientFors((XDialogPeer) ComponentAccessor.getPeer(modalBlocker)); + addToTransientFors((XDialogPeer) AWTAccessor.getComponentAccessor().getPeer(modalBlocker)); delayedModalBlocking = false; } } finally { @@ -1483,7 +1482,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, try { // State lock should always be after awtLock synchronized(getStateLock()) { - XDialogPeer blockerPeer = (XDialogPeer) ComponentAccessor.getPeer(d); + XDialogPeer blockerPeer = (XDialogPeer) AWTAccessor.getComponentAccessor().getPeer(d); if (blocked) { log.fine("{0} is blocked by {1}", this, blockerPeer); modalBlocker = d; @@ -1763,7 +1762,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, // current chain iterator in the order from next to prev XWindowPeer chainToSplit = prevTransientFor; while (chainToSplit != null) { - XWindowPeer blocker = (XWindowPeer) ComponentAccessor.getPeer(chainToSplit.modalBlocker); + XWindowPeer blocker = (XWindowPeer) AWTAccessor.getComponentAccessor().getPeer(chainToSplit.modalBlocker); if (thisChainBlockers.contains(blocker)) { // add to this dialog's chain setToplevelTransientFor(thisChain, chainToSplit, true, false); @@ -1791,7 +1790,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, static Window getDecoratedOwner(Window window) { while ((null != window) && !(window instanceof Frame || window instanceof Dialog)) { - window = (Window) ComponentAccessor.getParent_NoClientCode(window); + window = (Window) AWTAccessor.getComponentAccessor().getParent(window); } return window; } @@ -1824,7 +1823,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, } focusLog.fine("Parent window is not active"); - XDecoratedPeer wpeer = (XDecoratedPeer)ComponentAccessor.getPeer(ownerWindow); + XDecoratedPeer wpeer = (XDecoratedPeer)AWTAccessor.getComponentAccessor().getPeer(ownerWindow); if (wpeer != null && wpeer.requestWindowFocus(this, time, timeProvided)) { focusLog.fine("Parent window accepted focus request - generating focus for this window"); return true; @@ -2154,9 +2153,9 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (toplevel != null) { Window w = (Window)toplevel.target; while (w != null && toplevel != this && !(toplevel instanceof XDialogPeer)) { - w = (Window) ComponentAccessor.getParent_NoClientCode(w); + w = (Window) AWTAccessor.getComponentAccessor().getParent(w); if (w != null) { - toplevel = (XWindowPeer) ComponentAccessor.getPeer(w); + toplevel = (XWindowPeer) AWTAccessor.getComponentAccessor().getPeer(w); } } if (w == null || (w != this.target && w instanceof Dialog)) { diff --git a/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java b/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java index fc5fc107643..6682ffa85d3 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WCanvasPeer.java @@ -28,8 +28,6 @@ import java.awt.*; import java.awt.peer.*; import java.lang.ref.WeakReference; import java.lang.reflect.Method; -import sun.awt.AWTAccessor; -import sun.awt.ComponentAccessor; import sun.awt.SunToolkit; import sun.awt.Win32GraphicsDevice; import sun.awt.PaintEventDispatcher; diff --git a/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java b/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java index e5c51d7b77f..f508d5d9a88 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java @@ -57,7 +57,7 @@ import sun.awt.event.IgnorePaintEvent; import java.awt.dnd.DropTarget; import java.awt.dnd.peer.DropTargetPeer; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; import sun.util.logging.PlatformLogger; @@ -817,7 +817,7 @@ public abstract class WComponentPeer extends WObjectPeer } private void postPaintIfNecessary(int x, int y, int w, int h) { - if ( !ComponentAccessor.getIgnoreRepaint( (Component) target) ) { + if ( !AWTAccessor.getComponentAccessor().getIgnoreRepaint( (Component) target) ) { PaintEvent event = PaintEventDispatcher.getPaintEventDispatcher(). createPaintEvent((Component)target, x, y, w, h); if (event != null) { diff --git a/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java b/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java index 703edd0fdc5..918cd035e47 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WDialogPeer.java @@ -98,7 +98,7 @@ class WDialogPeer extends WWindowPeer implements DialogPeer { public void blockWindows(java.util.List toBlock) { for (Window w : toBlock) { - WWindowPeer wp = (WWindowPeer)ComponentAccessor.getPeer(w); + WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w); if (wp != null) { wp.setModalBlocked((Dialog)target, true); } diff --git a/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java b/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java index 9575b2475d6..bc4e8470f4c 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WFileDialogPeer.java @@ -35,7 +35,7 @@ import java.util.ResourceBundle; import java.util.MissingResourceException; import java.util.Vector; import sun.awt.AppContext; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; public class WFileDialogPeer extends WWindowPeer implements FileDialogPeer { @@ -187,7 +187,7 @@ public class WFileDialogPeer extends WWindowPeer implements FileDialogPeer { public void blockWindows(java.util.List toBlock) { for (Window w : toBlock) { - WWindowPeer wp = (WWindowPeer)ComponentAccessor.getPeer(w); + WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w); if (wp != null) { blockWindow(wp); } diff --git a/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java b/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java index d4ec57302fa..f507ce19568 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WPrintDialogPeer.java @@ -31,7 +31,7 @@ import java.awt.peer.ComponentPeer; import java.awt.dnd.DropTarget; import java.util.Vector; import sun.awt.AppContext; -import sun.awt.ComponentAccessor; +import sun.awt.AWTAccessor; public class WPrintDialogPeer extends WWindowPeer implements DialogPeer { @@ -103,7 +103,7 @@ public class WPrintDialogPeer extends WWindowPeer implements DialogPeer { public void blockWindows(java.util.List toBlock) { for (Window w : toBlock) { - WWindowPeer wp = (WWindowPeer)ComponentAccessor.getPeer(w); + WWindowPeer wp = (WWindowPeer)AWTAccessor.getComponentAccessor().getPeer(w); if (wp != null) { blockWindow(wp); } From 76e3aaa436623c5cf13865fb12e6556243f7c619 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Mon, 7 Dec 2009 12:24:57 +0000 Subject: [PATCH 47/56] 6903753: (se) Selector should implement Closeable Reviewed-by: chegar, forax --- jdk/src/share/classes/java/nio/channels/Selector.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/java/nio/channels/Selector.java b/jdk/src/share/classes/java/nio/channels/Selector.java index 46709d16fe1..e31555c122d 100644 --- a/jdk/src/share/classes/java/nio/channels/Selector.java +++ b/jdk/src/share/classes/java/nio/channels/Selector.java @@ -25,6 +25,7 @@ package java.nio.channels; +import java.io.Closeable; import java.io.IOException; import java.nio.channels.spi.SelectorProvider; import java.util.Set; @@ -202,7 +203,7 @@ import java.util.Set; * @see SelectionKey */ -public abstract class Selector { +public abstract class Selector implements Closeable { /** * Initializes a new instance of this class. From 21d2a75a1623b7e876e0734d101206663728c3d2 Mon Sep 17 00:00:00 2001 From: Alan Bateman Date: Mon, 7 Dec 2009 12:29:14 +0000 Subject: [PATCH 48/56] 6902010: (cl) Delay initialization of ClassLoader.parallelLoaders Reviewed-by: forax, mchung, valeriep --- .../share/classes/java/lang/ClassLoader.java | 75 ++++++++++++------- 1 file changed, 48 insertions(+), 27 deletions(-) diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java index 323240b395c..bb4ea98694b 100644 --- a/jdk/src/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/share/classes/java/lang/ClassLoader.java @@ -175,15 +175,8 @@ import sun.security.util.SecurityConstants; public abstract class ClassLoader { private static native void registerNatives(); - - // Set of classes which are registered as parallel capable class loaders - private static final Set> parallelLoaders - = Collections.newSetFromMap(Collections.synchronizedMap - (new WeakHashMap, Boolean>())); - static { registerNatives(); - parallelLoaders.add(ClassLoader.class); } // The parent class loader for delegation @@ -191,6 +184,52 @@ public abstract class ClassLoader { // must be added *after* it. private final ClassLoader parent; + /** + * Encapsulates the set of parallel capable loader types. + */ + private static class ParallelLoaders { + private ParallelLoaders() {} + + // the set of parallel capable loader types + private static final Set> loaderTypes = + Collections.newSetFromMap( + new WeakHashMap, Boolean>()); + static { + synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); } + } + + /** + * Registers the given class loader type as parallel capabale. + * Returns {@code true} is successfully registered; {@code false} if + * loader's super class is not registered. + */ + static boolean register(Class c) { + synchronized (loaderTypes) { + if (loaderTypes.contains(c.getSuperclass())) { + // register the class loader as parallel capable + // if and only if all of its super classes are. + // Note: given current classloading sequence, if + // the immediate super class is parallel capable, + // all the super classes higher up must be too. + loaderTypes.add(c); + return true; + } else { + return false; + } + } + } + + /** + * Returns {@code true} if the given class loader type is + * registered as parallel capable. + */ + static boolean isRegistered(Class c) { + synchronized (loaderTypes) { + return loaderTypes.contains(c); + } + } + } + // Maps class name to the corresponding lock object when the current // class loader is parallel capable. // Note: VM also uses this field to decide if the current class loader @@ -237,7 +276,7 @@ public abstract class ClassLoader { private ClassLoader(Void unused, ClassLoader parent) { this.parent = parent; - if (parallelLoaders.contains(this.getClass())) { + if (ParallelLoaders.isRegistered(this.getClass())) { parallelLockMap = new ConcurrentHashMap(); package2certs = new ConcurrentHashMap(); domains = @@ -1194,24 +1233,7 @@ public abstract class ClassLoader { * @since 1.7 */ protected static boolean registerAsParallelCapable() { - Class caller = getCaller(1); - Class superCls = caller.getSuperclass(); - boolean result = false; - // Explicit synchronization needed for composite action - synchronized (parallelLoaders) { - if (!parallelLoaders.contains(caller)) { - if (parallelLoaders.contains(superCls)) { - // register the immediate caller as parallel capable - // if and only if all of its super classes are. - // Note: given current classloading sequence, if - // the immediate super class is parallel capable, - // all the super classes higher up must be too. - result = true; - parallelLoaders.add(caller); - } - } else result = true; - } - return result; + return ParallelLoaders.register(getCaller(1)); } /** @@ -2174,4 +2196,3 @@ class SystemClassLoaderAction return sys; } } - From 45c70cd97e03eb35abbf6355bccbf9f53a53bb55 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Mon, 7 Dec 2009 16:38:44 +0300 Subject: [PATCH 49/56] 6903890: SWT_AWT focus issues when a dialog is shown/disposed, on X11 Reviewed-by: art, dcherepanov --- jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java index f79de9cf927..0874502db1f 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java @@ -133,7 +133,7 @@ public class XEmbedClientHelper extends XEmbedHelper implements XEventDispatcher } void handleFocusIn(int detail) { if (embedded.focusAllowedFor()) { - embedded.handleWindowFocusInSync(0); + embedded.handleWindowFocusIn(0); } switch(detail) { case XEMBED_FOCUS_CURRENT: @@ -205,7 +205,7 @@ public class XEmbedClientHelper extends XEmbedHelper implements XEventDispatcher // embedded is an active window before sending WINDOW_LOST_FOCUS // to shared code if (XKeyboardFocusManagerPeer.getCurrentNativeFocusedWindow() == embedded.target) { - embedded.handleWindowFocusOutSync(null, 0); + embedded.handleWindowFocusOut(null, 0); } } From 5c20a6292f15f92fecaca684c25f87398d5c9389 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Mon, 7 Dec 2009 17:06:59 +0000 Subject: [PATCH 50/56] 6876158: Remove dependencies on Signer, Certificate, Identity, IdentityScope classes from java.security pkg Reviewed-by: alanb, mullan --- .../com/sun/security/auth/PolicyFile.java | 7 +- .../classes/sun/security/pkcs/PKCS10.java | 21 +- .../security/provider/IdentityDatabase.java | 427 --------- .../sun/security/provider/PolicyFile.java | 81 +- .../sun/security/provider/SystemIdentity.java | 107 --- .../sun/security/provider/SystemSigner.java | 115 --- .../classes/sun/security/tools/JarSigner.java | 10 - .../classes/sun/security/tools/KeyTool.java | 90 +- .../sun/security/x509/CertAndKeyGen.java | 59 +- .../classes/sun/security/x509/X500Signer.java | 115 --- .../classes/sun/security/x509/X509Cert.java | 892 ------------------ .../sun/tools/jar/JarVerifierStream.java | 295 ------ 12 files changed, 28 insertions(+), 2191 deletions(-) delete mode 100644 jdk/src/share/classes/sun/security/provider/IdentityDatabase.java delete mode 100644 jdk/src/share/classes/sun/security/provider/SystemIdentity.java delete mode 100644 jdk/src/share/classes/sun/security/provider/SystemSigner.java delete mode 100644 jdk/src/share/classes/sun/security/x509/X500Signer.java delete mode 100644 jdk/src/share/classes/sun/security/x509/X509Cert.java delete mode 100644 jdk/src/share/classes/sun/tools/jar/JarVerifierStream.java diff --git a/jdk/src/share/classes/com/sun/security/auth/PolicyFile.java b/jdk/src/share/classes/com/sun/security/auth/PolicyFile.java index a4075ba0974..9d3e6765134 100644 --- a/jdk/src/share/classes/com/sun/security/auth/PolicyFile.java +++ b/jdk/src/share/classes/com/sun/security/auth/PolicyFile.java @@ -34,8 +34,6 @@ import java.util.*; import java.security.AccessController; import java.security.CodeSource; -import java.security.Identity; -import java.security.IdentityScope; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Permission; @@ -267,7 +265,7 @@ public class PolicyFile extends javax.security.auth.Policy { private boolean initialized = false; private boolean expandProperties = true; - private boolean ignoreIdentityScope = false; + private boolean ignoreIdentityScope = true; // for use with the reflection API @@ -459,9 +457,6 @@ public class PolicyFile extends javax.security.auth.Policy { } } - /** the scope to check */ - private static IdentityScope scope = null; - /** * Checks public key. If it is marked as trusted in * the identity database, add it to the policy diff --git a/jdk/src/share/classes/sun/security/pkcs/PKCS10.java b/jdk/src/share/classes/sun/security/pkcs/PKCS10.java index 595eed7c6af..ef51273e9b2 100644 --- a/jdk/src/share/classes/sun/security/pkcs/PKCS10.java +++ b/jdk/src/share/classes/sun/security/pkcs/PKCS10.java @@ -44,7 +44,6 @@ import sun.security.util.*; import sun.security.x509.AlgorithmId; import sun.security.x509.X509Key; import sun.security.x509.X500Name; -import sun.security.x509.X500Signer; /** * A PKCS #10 certificate request is created and sent to a Certificate @@ -183,13 +182,13 @@ public class PKCS10 { * Create the signed certificate request. This will later be * retrieved in either string or binary format. * - * @param requester identifies the signer (by X.500 name) - * and provides the private key used to sign. + * @param subject identifies the signer (by X.500 name). + * @param signature private key and signing algorithm to use. * @exception IOException on errors. * @exception CertificateException on certificate handling errors. * @exception SignatureException on signature handling errors. */ - public void encodeAndSign(X500Signer requester) + public void encodeAndSign(X500Name subject, Signature signature) throws CertificateException, IOException, SignatureException { DerOutputStream out, scratch; byte[] certificateRequestInfo; @@ -198,7 +197,7 @@ public class PKCS10 { if (encoded != null) throw new SignatureException("request is already signed"); - subject = requester.getSigner(); + this.subject = subject; /* * Encode cert request info, wrap in a sequence for signing @@ -217,14 +216,20 @@ public class PKCS10 { /* * Sign it ... */ - requester.update(certificateRequestInfo, 0, + signature.update(certificateRequestInfo, 0, certificateRequestInfo.length); - sig = requester.sign(); + sig = signature.sign(); /* * Build guts of SIGNED macro */ - requester.getAlgorithmId().encode(scratch); // sig algorithm + AlgorithmId algId = null; + try { + algId = AlgorithmId.getAlgorithmId(signature.getAlgorithm()); + } catch (NoSuchAlgorithmException nsae) { + throw new SignatureException(nsae); + } + algId.encode(scratch); // sig algorithm scratch.putBitString(sig); // sig /* diff --git a/jdk/src/share/classes/sun/security/provider/IdentityDatabase.java b/jdk/src/share/classes/sun/security/provider/IdentityDatabase.java deleted file mode 100644 index 0c118161c8a..00000000000 --- a/jdk/src/share/classes/sun/security/provider/IdentityDatabase.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 1996-2006 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.security.provider; - -import java.io.*; -import java.util.*; -import java.security.*; - -/** - * An implementation of IdentityScope as a persistent identity - * database. - * - * @see Identity - * @see Key - * - * @author Benjamin Renaud - */ -public -class IdentityDatabase extends IdentityScope implements Serializable { - - /** use serialVersionUID from JDK 1.1. for interoperability */ - private static final long serialVersionUID = 4923799573357658384L; - - /* Are we debugging? */ - private static final boolean debug = false; - - /* Are we printing out error messages? */ - private static final boolean error = true; - - /* The source file, if any, for this database.*/ - File sourceFile; - - /* The private representation of the database.*/ - Hashtable identities; - - IdentityDatabase() throws InvalidParameterException { - this("restoring..."); - } - - /** - * Construct a new, empty database with a specified source file. - * - * @param file the source file. - */ - public IdentityDatabase(File file) throws InvalidParameterException { - this(file.getName()); - sourceFile = file; - } - - /** - * Construct a new, empty database. - */ - public IdentityDatabase(String name) throws InvalidParameterException { - super(name); - identities = new Hashtable(); - } - - /** - * Initialize an identity database from a stream. The stream should - * contain data to initialized a serialized IdentityDatabase - * object. - * - * @param is the input stream from which to restore the database. - * - * @exception IOException if a stream IO exception occurs - */ - public static IdentityDatabase fromStream(InputStream is) - throws IOException { - IdentityDatabase db = null; - try { - ObjectInputStream ois = new ObjectInputStream(is); - db = (IdentityDatabase)ois.readObject(); - } catch (ClassNotFoundException e) { - // this can't happen. - debug("This should not be happening.", e); - error( - "The version of the database is obsolete. Cannot initialize."); - - } catch (InvalidClassException e) { - // this may happen in developers workspaces happen. - debug("This should not be happening.", e); - error("Unable to initialize system identity scope: " + - " InvalidClassException. \nThis is most likely due to " + - "a serialization versioning problem: a class used in " + - "key management was obsoleted"); - - } catch (StreamCorruptedException e) { - debug("The serialization stream is corrupted. Unable to load.", e); - error("Unable to initialize system identity scope." + - " StreamCorruptedException."); - } - - if (db == null) { - db = new IdentityDatabase("uninitialized"); - } - - return db; - } - - /** - * Initialize an IdentityDatabase from file. - * - * @param f the filename where the identity database is stored. - * - * @exception IOException a file-related exception occurs (e.g. - * the directory of the file passed does not exists, etc. - * - * @IOException if a file IO exception occurs. - */ - public static IdentityDatabase fromFile(File f) throws IOException { - FileInputStream fis = new FileInputStream(f); - IdentityDatabase edb = fromStream(fis); - edb.sourceFile = f; - return edb; - } - - - - /** - * @return the number of identities in the database. - */ - public int size() { - return identities.size(); - } - - - /** - * @param name the name of the identity to be retrieved. - * - * @return the identity named name, or null if there are - * no identities named name in the database. - */ - public Identity getIdentity(String name) { - Identity id = identities.get(name); - if (id instanceof Signer) { - localCheck("get.signer"); - } - return id; - } - - /** - * Get an identity by key. - * - * @param name the key of the identity to be retrieved. - * - * @return the identity with a given key, or null if there are no - * identities with that key in the database. - */ - public Identity getIdentity(PublicKey key) { - if (key == null) { - return null; - } - Enumeration e = identities(); - while (e.hasMoreElements()) { - Identity i = e.nextElement(); - PublicKey k = i.getPublicKey(); - if (k != null && keyEqual(k, key)) { - if (i instanceof Signer) { - localCheck("get.signer"); - } - return i; - } - } - return null; - } - - private boolean keyEqual(Key key1, Key key2) { - if (key1 == key2) { - return true; - } else { - return MessageDigest.isEqual(key1.getEncoded(), key2.getEncoded()); - } - } - - /** - * Adds an identity to the database. - * - * @param identity the identity to be added. - * - * @exception KeyManagementException if a name or key clash - * occurs, or if another exception occurs. - */ - public void addIdentity(Identity identity) - throws KeyManagementException { - localCheck("add.identity"); - Identity byName = getIdentity(identity.getName()); - Identity byKey = getIdentity(identity.getPublicKey()); - String msg = null; - - if (byName != null) { - msg = "name conflict"; - } - if (byKey != null) { - msg = "key conflict"; - } - if (msg != null) { - throw new KeyManagementException(msg); - } - identities.put(identity.getName(), identity); - } - - /** - * Removes an identity to the database. - */ - public void removeIdentity(Identity identity) - throws KeyManagementException { - localCheck("remove.identity"); - String name = identity.getName(); - if (identities.get(name) == null) { - throw new KeyManagementException("there is no identity named " + - name + " in " + this); - } - identities.remove(name); - } - - /** - * @return an enumeration of all identities in the database. - */ - public Enumeration identities() { - return identities.elements(); - } - - /** - * Set the source file for this database. - */ - void setSourceFile(File f) { - sourceFile = f; - } - - /** - * @return the source file for this database. - */ - File getSourceFile() { - return sourceFile; - } - - /** - * Save the database in its current state to an output stream. - * - * @param os the output stream to which the database should be serialized. - * - * @exception IOException if an IO exception is raised by stream - * operations. - */ - public void save(OutputStream os) throws IOException { - try { - ObjectOutputStream oos = new ObjectOutputStream(os); - oos.writeObject(this); - oos.flush(); - } catch (InvalidClassException e) { - debug("This should not be happening.", e); - return; - } - } - - /** - * Save the database to a file. - * - * @exception IOException if an IO exception is raised by stream - * operations. - */ - void save(File f) throws IOException { - setSourceFile(f); - FileOutputStream fos = new FileOutputStream(f); - save(fos); - } - - /** - * Saves the database to the default source file. - * - * @exception KeyManagementException when there is no default source - * file specified for this database. - */ - public void save() throws IOException { - if (sourceFile == null) { - throw new IOException("this database has no source file"); - } - save(sourceFile); - } - - /** - * This method returns the file from which to initialize the - * system database. - */ - private static File systemDatabaseFile() { - - // First figure out where the identity database is hiding, if anywhere. - String dbPath = Security.getProperty("identity.database"); - // if nowhere, it's the canonical place. - if (dbPath == null) { - dbPath = System.getProperty("user.home") + File.separatorChar + - "identitydb.obj"; - } - return new File(dbPath); - } - - - /* This block initializes the system database, if there is one. */ - static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - initializeSystem(); - return null; - } - }); - } - - /** - * This method initializes the system's identity database. The - * canonical location is - * /identitydatabase.obj. This is settable through - * the identity.database property. */ - private static void initializeSystem() { - - IdentityDatabase systemDatabase; - File dbFile = systemDatabaseFile(); - - // Second figure out if it's there, and if it isn't, create one. - try { - if (dbFile.exists()) { - debug("loading system database from file: " + dbFile); - systemDatabase = fromFile(dbFile); - } else { - systemDatabase = new IdentityDatabase(dbFile); - } - IdentityScope.setSystemScope(systemDatabase); - debug("System database initialized: " + systemDatabase); - } catch (IOException e) { - debug("Error initializing identity database: " + dbFile, e); - return; - } catch (InvalidParameterException e) { - debug("Error trying to instantiate a system identities db in " + - dbFile, e); - return; - } - } - - /* - private static File securityPropFile(String filename) { - // maybe check for a system property which will specify where to - // look. - String sep = File.separator; - return new File(System.getProperty("java.home") + - sep + "lib" + sep + "security" + - sep + filename); - } - */ - - public String toString() { - return "sun.security.provider.IdentityDatabase, source file: " + - sourceFile; - } - - - private static void debug(String s) { - if (debug) { - System.err.println(s); - } - } - - private static void debug(String s, Throwable t) { - if (debug) { - t.printStackTrace(); - System.err.println(s); - } - } - - private static void error(String s) { - if (error) { - System.err.println(s); - } - } - - void localCheck(String directive) { - SecurityManager security = System.getSecurityManager(); - if (security != null) { - directive = this.getClass().getName() + "." + - directive + "." + localFullName(); - security.checkSecurityAccess(directive); - } - } - - /** - * Returns a parsable name for identity: identityName.scopeName - */ - String localFullName() { - String parsable = getName(); - if (getScope() != null) { - parsable += "." +getScope().getName(); - } - return parsable; - } - - /** - * Serialization write. - */ - private synchronized void writeObject (java.io.ObjectOutputStream stream) - throws IOException { - localCheck("serialize.identity.database"); - stream.writeObject(identities); - stream.writeObject(sourceFile); - } -} diff --git a/jdk/src/share/classes/sun/security/provider/PolicyFile.java b/jdk/src/share/classes/sun/security/provider/PolicyFile.java index ed4757d3cff..c5ae8316d10 100644 --- a/jdk/src/share/classes/sun/security/provider/PolicyFile.java +++ b/jdk/src/share/classes/sun/security/provider/PolicyFile.java @@ -295,16 +295,13 @@ public class PolicyFile extends java.security.Policy { private static final int DEFAULT_CACHE_SIZE = 1; - /** the scope to check */ - private static IdentityScope scope = null; - // contains the policy grant entries, PD cache, and alias mapping private AtomicReference policyInfo = new AtomicReference(); private boolean constructed = false; private boolean expandProperties = true; - private boolean ignoreIdentityScope = false; + private boolean ignoreIdentityScope = true; private boolean allowSystemProperties = true; private boolean notUtf8 = false; private URL url; @@ -2024,85 +2021,9 @@ public class PolicyFile extends java.security.Policy { private boolean checkForTrustedIdentity(final Certificate cert, PolicyInfo myInfo) { - if (cert == null) - return false; - - // see if we are ignoring the identity scope or not - if (ignoreIdentityScope) - return false; - - // try to initialize scope - synchronized(PolicyFile.class) { - if (scope == null) { - IdentityScope is = IdentityScope.getSystemScope(); - - if (is instanceof sun.security.provider.IdentityDatabase) { - scope = is; - } else { - // leave scope null - } - } - } - - if (scope == null) { - ignoreIdentityScope = true; - return false; - } - - // need privileged block for getIdentity in case we are trying - // to get a signer - final Identity id = AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Identity run() { - return scope.getIdentity(cert.getPublicKey()); - } - }); - - if (isTrusted(id)) { - if (debug != null) { - debug.println("Adding policy entry for trusted Identity: "); - //needed for identity toString! - AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - debug.println(" identity = " + id); - return null; - } - }); - debug.println(""); - } - - // add it to the policy for future reference - Certificate certs[] = new Certificate[] {cert}; - PolicyEntry pe = new PolicyEntry(new CodeSource(null, certs)); - pe.add(SecurityConstants.ALL_PERMISSION); - - myInfo.identityPolicyEntries.add(pe); - - // add it to the mapping as well so - // we don't have to go through this again - myInfo.aliasMapping.put(cert, id.getName()); - - return true; - } return false; } - private static boolean isTrusted(Identity id) { - if (id instanceof SystemIdentity) { - SystemIdentity sysid = (SystemIdentity)id; - if (sysid.isTrusted()) { - return true; - } - } else if (id instanceof SystemSigner) { - SystemSigner sysid = (SystemSigner)id; - if (sysid.isTrusted()) { - return true; - } - } - return false; - } - /** * Each entry in the policy configuration file is represented by a * PolicyEntry object.

    diff --git a/jdk/src/share/classes/sun/security/provider/SystemIdentity.java b/jdk/src/share/classes/sun/security/provider/SystemIdentity.java deleted file mode 100644 index 7759bbca9aa..00000000000 --- a/jdk/src/share/classes/sun/security/provider/SystemIdentity.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 1996-2000 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.security.provider; - -import java.io.Serializable; -import java.util.Enumeration; -import java.security.*; - -/** - * An identity with a very simple trust mechanism. - * - * @author Benjamin Renaud - */ - -public class SystemIdentity extends Identity implements Serializable { - - /** use serialVersionUID from JDK 1.1. for interoperability */ - private static final long serialVersionUID = 9060648952088498478L; - - /* This should be changed to ACL */ - boolean trusted = false; - - /* Free form additional information about this identity. */ - private String info; - - public SystemIdentity(String name, IdentityScope scope) - throws InvalidParameterException, KeyManagementException { - super(name, scope); - } - - /** - * Is this identity trusted by sun.* facilities? - */ - public boolean isTrusted() { - return trusted; - } - - /** - * Set the trust status of this identity. - */ - protected void setTrusted(boolean trusted) { - this.trusted = trusted; - } - - void setIdentityInfo(String info) { - super.setInfo(info); - } - - String getIndentityInfo() { - return super.getInfo(); - } - - /** - * Call back method into a protected method for package friends. - */ - void setIdentityPublicKey(PublicKey key) throws KeyManagementException { - setPublicKey(key); - } - - /** - * Call back method into a protected method for package friends. - */ - void addIdentityCertificate(Certificate cert) - throws KeyManagementException { - addCertificate(cert); - } - - void clearCertificates() throws KeyManagementException { - Certificate[] certs = certificates(); - for (int i = 0; i < certs.length; i++) { - removeCertificate(certs[i]); - } - } - - public String toString() { - String trustedString = "not trusted"; - if (trusted) { - trustedString = "trusted"; - } - return super.toString() + "[" + trustedString + "]"; - } - - -} diff --git a/jdk/src/share/classes/sun/security/provider/SystemSigner.java b/jdk/src/share/classes/sun/security/provider/SystemSigner.java deleted file mode 100644 index 4bd2ee8db23..00000000000 --- a/jdk/src/share/classes/sun/security/provider/SystemSigner.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 1996-2000 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.security.provider; - -import java.util.*; -import java.security.*; - -/** - * SunSecurity signer. Like SystemIdentity, it has a trust bit, which - * can be set by SunSecurity classes, and a set of accessors for other - * classes in sun.security.*. - * - * @author Benjamin Renaud - */ - -public class SystemSigner extends Signer { - - /** use serialVersionUID from JDK 1.1. for interoperability */ - private static final long serialVersionUID = -2127743304301557711L; - - /* Is this signer trusted */ - private boolean trusted = false; - - /** - * Construct a signer with a given name. - */ - public SystemSigner(String name) { - super(name); - } - - /** - * Construct a signer with a name and a scope. - * - * @param name the signer's name. - * - * @param scope the scope for this signer. - */ - public SystemSigner(String name, IdentityScope scope) - throws KeyManagementException { - - super(name, scope); - } - - /* Set the trust status of this signer */ - void setTrusted(boolean trusted) { - this.trusted = trusted; - } - - /** - * Returns true if this signer is trusted. - */ - public boolean isTrusted() { - return trusted; - } - - /* friendly callback for set keys */ - void setSignerKeyPair(KeyPair pair) - throws InvalidParameterException, KeyException { - setKeyPair(pair); - } - - /* friendly callback for getting private keys */ - PrivateKey getSignerPrivateKey() { - return getPrivateKey(); - } - - void setSignerInfo(String s) { - setInfo(s); - } - - /** - * Call back method into a protected method for package friends. - */ - void addSignerCertificate(Certificate cert) throws KeyManagementException { - addCertificate(cert); - } - - void clearCertificates() throws KeyManagementException { - Certificate[] certs = certificates(); - for (int i = 0; i < certs.length; i++) { - removeCertificate(certs[i]); - } - } - - public String toString() { - String trustedString = "not trusted"; - if (trusted) { - trustedString = "trusted"; - } - return super.toString() + "[" + trustedString + "]"; - } -} diff --git a/jdk/src/share/classes/sun/security/tools/JarSigner.java b/jdk/src/share/classes/sun/security/tools/JarSigner.java index 005d8aa1bfd..5c824c5712f 100644 --- a/jdk/src/share/classes/sun/security/tools/JarSigner.java +++ b/jdk/src/share/classes/sun/security/tools/JarSigner.java @@ -118,8 +118,6 @@ public class JarSigner { KeyStore store; // the keystore specified by -keystore // or the default keystore, never null - IdentityScope scope; - String keystore; // key store file boolean nullStream = false; // null keystore input stream (NONE) boolean token = false; // token-based keystore @@ -212,7 +210,6 @@ public class JarSigner { if (verify) { try { loadKeyStore(keystore, false); - scope = IdentityScope.getSystemScope(); } catch (Exception e) { if ((keystore != null) || (storepass != null)) { System.out.println(rb.getString("jarsigner error: ") + @@ -984,13 +981,6 @@ public class JarSigner { result |= IN_KEYSTORE; } } - if (!found && (scope != null)) { - Identity id = scope.getIdentity(c.getPublicKey()); - if (id != null) { - result |= IN_SCOPE; - storeHash.put(c, "[" + id.getName() + "]"); - } - } if (ckaliases.contains(alias)) { result |= SIGNED_BY_ALIAS; } diff --git a/jdk/src/share/classes/sun/security/tools/KeyTool.java b/jdk/src/share/classes/sun/security/tools/KeyTool.java index b3b0f7365ab..cacdbe83496 100644 --- a/jdk/src/share/classes/sun/security/tools/KeyTool.java +++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java @@ -40,7 +40,6 @@ import java.security.UnrecoverableEntryException; import java.security.UnrecoverableKeyException; import java.security.Principal; import java.security.Provider; -import java.security.Identity; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -57,9 +56,6 @@ import java.net.URLClassLoader; import sun.misc.BASE64Encoder; import sun.security.util.ObjectIdentifier; import sun.security.pkcs.PKCS10; -import sun.security.provider.IdentityDatabase; -import sun.security.provider.SystemSigner; -import sun.security.provider.SystemIdentity; import sun.security.provider.X509Factory; import sun.security.util.DerOutputStream; import sun.security.util.Password; @@ -1163,18 +1159,16 @@ public final class KeyTool { Signature signature = Signature.getInstance(sigAlgName); signature.initSign(privateKey); - X500Signer signer = new X500Signer(signature, issuer); - X509CertInfo info = new X509CertInfo(); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( new java.util.Random().nextInt() & 0x7fffffff)); info.set(X509CertInfo.VERSION, - new CertificateVersion(CertificateVersion.V3)); + new CertificateVersion(CertificateVersion.V3)); info.set(X509CertInfo.ALGORITHM_ID, - new CertificateAlgorithmId(signer.getAlgorithmId())); - info.set(X509CertInfo.ISSUER, - new CertificateIssuerName(signer.getSigner())); + new CertificateAlgorithmId( + AlgorithmId.getAlgorithmId(sigAlgName))); + info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer)); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); boolean canRead = false; @@ -1249,7 +1243,7 @@ public final class KeyTool { request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS, new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext)); - // Construct an X500Signer object, so that we can sign the request + // Construct a Signature object, so that we can sign the request if (sigAlgName == null) { sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm()); } @@ -1259,10 +1253,9 @@ public final class KeyTool { 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 - request.encodeAndSign(signer); + request.encodeAndSign(subject, signature); request.print(out); } @@ -1564,75 +1557,8 @@ public final class KeyTool { private void doImportIdentityDatabase(InputStream in) throws Exception { - byte[] encoded; - ByteArrayInputStream bais; - java.security.cert.X509Certificate newCert; - java.security.cert.Certificate[] chain = null; - PrivateKey privKey; - boolean modified = false; - - IdentityDatabase idb = IdentityDatabase.fromStream(in); - for (Enumeration enum_ = idb.identities(); - enum_.hasMoreElements();) { - Identity id = enum_.nextElement(); - newCert = null; - // only store trusted identities in keystore - if ((id instanceof SystemSigner && ((SystemSigner)id).isTrusted()) - || (id instanceof SystemIdentity - && ((SystemIdentity)id).isTrusted())) { - // ignore if keystore entry with same alias name already exists - if (keyStore.containsAlias(id.getName())) { - MessageFormat form = new MessageFormat - (rb.getString("Keystore entry for already exists")); - Object[] source = {id.getName()}; - System.err.println(form.format(source)); - continue; - } - java.security.Certificate[] certs = id.certificates(); - if (certs!=null && certs.length>0) { - // we can only store one user cert per identity. - // convert old-style to new-style cert via the encoding - DerOutputStream dos = new DerOutputStream(); - certs[0].encode(dos); - encoded = dos.toByteArray(); - bais = new ByteArrayInputStream(encoded); - newCert = (X509Certificate)cf.generateCertificate(bais); - bais.close(); - - // if certificate is self-signed, make sure it verifies - if (isSelfSigned(newCert)) { - PublicKey pubKey = newCert.getPublicKey(); - try { - newCert.verify(pubKey); - } catch (Exception e) { - // ignore this cert - continue; - } - } - - if (id instanceof SystemSigner) { - MessageFormat form = new MessageFormat(rb.getString - ("Creating keystore entry for ...")); - Object[] source = {id.getName()}; - System.err.println(form.format(source)); - if (chain==null) { - chain = new java.security.cert.Certificate[1]; - } - chain[0] = newCert; - privKey = ((SystemSigner)id).getPrivateKey(); - keyStore.setKeyEntry(id.getName(), privKey, storePass, - chain); - } else { - keyStore.setCertificateEntry(id.getName(), newCert); - } - kssave = true; - } - } - } - if (!kssave) { - System.err.println(rb.getString - ("No entries from identity database added")); - } + System.err.println(rb.getString + ("No entries from identity database added")); } /** diff --git a/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java b/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java index 2cf34c871ec..feeaf4cf3eb 100644 --- a/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java +++ b/jdk/src/share/classes/sun/security/x509/CertAndKeyGen.java @@ -189,41 +189,6 @@ public final class CertAndKeyGen { } - /** - * Returns a self-signed X.509v1 certificate for the public key. - * The certificate is immediately valid. - * - *

    Such certificates normally are used to identify a "Certificate - * Authority" (CA). Accordingly, they will not always be accepted by - * other parties. However, such certificates are also useful when - * you are bootstrapping your security infrastructure, or deploying - * system prototypes. - * - * @deprecated Use the new - * - * @param myname X.500 name of the subject (who is also the issuer) - * @param validity how long the certificate should be valid, in seconds - */ - @Deprecated - public X509Cert getSelfCert (X500Name myname, long validity) - throws InvalidKeyException, SignatureException, NoSuchAlgorithmException - { - X509Certificate cert; - - try { - cert = getSelfCertificate(myname, validity); - return new X509Cert(cert.getEncoded()); - } catch (CertificateException e) { - throw new SignatureException(e.getMessage()); - } catch (NoSuchProviderException e) { - throw new NoSuchAlgorithmException(e.getMessage()); - } catch (IOException e) { - throw new SignatureException(e.getMessage()); - } - } - - /** * Returns a self-signed X.509v3 certificate for the public key. * The certificate is immediately valid. No extensions. @@ -248,13 +213,10 @@ public final class CertAndKeyGen { throws CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException { - X500Signer issuer; X509CertImpl cert; Date lastDate; try { - issuer = getSigner (myname); - lastDate = new Date (); lastDate.setTime (firstDate.getTime () + validity * 1000); @@ -267,14 +229,13 @@ public final class CertAndKeyGen { new CertificateVersion(CertificateVersion.V3)); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( new java.util.Random().nextInt() & 0x7fffffff)); - AlgorithmId algID = issuer.getAlgorithmId(); + AlgorithmId algID = AlgorithmId.getAlgorithmId(sigAlg); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algID)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(myname)); info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey)); info.set(X509CertInfo.VALIDITY, interval); - info.set(X509CertInfo.ISSUER, - new CertificateIssuerName(issuer.getSigner())); + info.set(X509CertInfo.ISSUER, new CertificateIssuerName(myname)); cert = new X509CertImpl(info); cert.sign(privateKey, this.sigAlg); @@ -315,7 +276,9 @@ public final class CertAndKeyGen { PKCS10 req = new PKCS10 (publicKey); try { - req.encodeAndSign (getSigner (myname)); + Signature signature = Signature.getInstance(sigAlg); + signature.initSign (privateKey); + req.encodeAndSign(myname, signature); } catch (CertificateException e) { throw new SignatureException (sigAlg + " CertificateException"); @@ -330,18 +293,6 @@ public final class CertAndKeyGen { return req; } - private X500Signer getSigner (X500Name me) - throws InvalidKeyException, NoSuchAlgorithmException - { - Signature signature = Signature.getInstance(sigAlg); - - // XXX should have a way to pass prng to the signature - // algorithm ... appropriate for DSS/DSA, not RSA - - signature.initSign (privateKey); - return new X500Signer (signature, me); - } - private SecureRandom prng; private String sigAlg; private KeyPairGenerator keyGen; diff --git a/jdk/src/share/classes/sun/security/x509/X500Signer.java b/jdk/src/share/classes/sun/security/x509/X500Signer.java deleted file mode 100644 index b51b31d329e..00000000000 --- a/jdk/src/share/classes/sun/security/x509/X500Signer.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 1996-2003 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.security.x509; - -import java.security.Signature; -import java.security.SignatureException; -import java.security.Signer; -import java.security.NoSuchAlgorithmException; - -/** - * This class provides a binding between a Signature object and an - * authenticated X.500 name (from an X.509 certificate chain), which - * is needed in many public key signing applications. - * - *

    The name of the signer is important, both because knowing it is the - * whole point of the signature, and because the associated X.509 certificate - * is always used to verify the signature. - * - *

    The X.509 certificate chain is temporarily not associated with - * the signer, but this omission will be resolved. - * - * - * @author David Brownell - * @author Amit Kapoor - * @author Hemma Prafullchandra - */ -public final class X500Signer extends Signer -{ - private static final long serialVersionUID = -8609982645394364834L; - - /** - * Called for each chunk of the data being signed. That - * is, you can present the data in many chunks, so that - * it doesn't need to be in a single sequential buffer. - * - * @param buf buffer holding the next chunk of the data to be signed - * @param offset starting point of to-be-signed data - * @param len how many bytes of data are to be signed - * @exception SignatureException on errors. - */ - public void update(byte buf[], int offset, int len) - throws SignatureException { - sig.update (buf, offset, len); - } - - /** - * Produces the signature for the data processed by update(). - * - * @exception SignatureException on errors. - */ - public byte[] sign() throws SignatureException { - return sig.sign(); - } - - /** - * Returns the algorithm used to sign. - */ - public AlgorithmId getAlgorithmId() { - return algid; - } - - /** - * Returns the name of the signing agent. - */ - public X500Name getSigner() { - return agent; - } - - /* - * Constructs a binding between a signature and an X500 name - * from an X.509 certificate. - */ - // package private ----hmmmmm ????? - public X500Signer(Signature sig, X500Name agent) { - if (sig == null || agent == null) - throw new IllegalArgumentException ("null parameter"); - - this.sig = sig; - this.agent = agent; - - try { - this.algid = AlgorithmId.getAlgorithmId(sig.getAlgorithm()); - - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("internal error! " + e.getMessage()); - } - } - - private Signature sig; - private X500Name agent; // XXX should be X509CertChain - private AlgorithmId algid; -} diff --git a/jdk/src/share/classes/sun/security/x509/X509Cert.java b/jdk/src/share/classes/sun/security/x509/X509Cert.java deleted file mode 100644 index e90014c0493..00000000000 --- a/jdk/src/share/classes/sun/security/x509/X509Cert.java +++ /dev/null @@ -1,892 +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 sun.security.x509; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.math.BigInteger; -import java.security.*; -import java.util.Date; -import java.util.Enumeration; - -import sun.security.util.*; // DER - -/** - * @author David Brownell - * - * @see CertAndKeyGen - * @deprecated Use the new X509Certificate class. - * This class is only restored for backwards compatibility. - */ -@Deprecated -public class X509Cert implements Certificate, Serializable { - - static final long serialVersionUID = -52595524744692374L; - - /* - * NOTE: All fields are marked transient, because we do not want them to - * be included in the class description when we serialize an object of - * this class. We override "writeObject" and "readObject" to use the - * ASN.1 encoding of a certificate as the serialized form, instead of - * calling the default routines which would operate on the field values. - * - * MAKE SURE TO MARK ANY FIELDS THAT ARE ADDED IN THE FUTURE AS TRANSIENT. - */ - - /* The algorithm id */ - transient protected AlgorithmId algid; - - /* - * Certificate data, and its envelope - */ - transient private byte rawCert []; - transient private byte signature []; - transient private byte signedCert []; - - /* - * X509.v1 data (parsed) - */ - transient private X500Name subject; // from subject - transient private PublicKey pubkey; - - transient private Date notafter; // from CA (constructor) - transient private Date notbefore; - - transient private int version; // from CA (signAndEncode) - transient private BigInteger serialnum; - transient private X500Name issuer; - transient private AlgorithmId issuerSigAlg; - - /* - * flag to indicate whether or not this certificate has already been parsed - * (through a call to one of the constructors or the "decode" or - * "readObject" methods). This is to ensure that certificates are - * immutable. - */ - transient private boolean parsed=false; - - /* - * X509.v2 extensions - */ - - /* - * X509.v3 extensions - */ - - /* - * Other extensions ... Netscape, Verisign, SET, etc - */ - - - /** - * Construct a uninitialized X509 Cert on which - * decode must later be called (or which may be deserialized). - */ - // XXX deprecated, delete this - public X509Cert() { } - - - /** - * Unmarshals a certificate from its encoded form, parsing the - * encoded bytes. This form of constructor is used by agents which - * need to examine and use certificate contents. That is, this is - * one of the more commonly used constructors. Note that the buffer - * must include only a certificate, and no "garbage" may be left at - * the end. If you need to ignore data at the end of a certificate, - * use another constructor. - * - * @param cert the encoded bytes, with no terminatu (CONSUMED) - * @exception IOException when the certificate is improperly encoded. - */ - public X509Cert(byte cert []) throws IOException - { - DerValue in = new DerValue (cert); - parse (in); - if (in.data.available () != 0) - throw new CertParseError ("garbage at end"); - signedCert = cert; - } - - - /** - * Unmarshals a certificate from its encoded form, parsing the - * encoded bytes. This form of constructor is used by agents which - * need to examine and use certificate contents. That is, this is - * one of the most commonly used constructors. - * - * @param buf the buffer holding the encoded bytes - * @param offset the offset in the buffer where the bytes begin - * @param len how many bytes of certificate exist - * - * @exception IOException when the certificate is improperly encoded. - */ - public X509Cert(byte buf [], int offset, int len) throws IOException - { - DerValue in = new DerValue (buf, offset, len); - - parse (in); - if (in.data.available () != 0) - throw new CertParseError ("garbage at end"); - signedCert = new byte [len]; - System.arraycopy (buf, offset, signedCert, 0, len); - } - - - /** - * Unmarshal a certificate from its encoded form, parsing a DER value. - * This form of constructor is used by agents which need to examine - * and use certificate contents. - * - * @param derVal the der value containing the encoded cert. - * @exception IOException when the certificate is improperly encoded. - */ - public X509Cert(DerValue derVal) throws IOException - { - parse (derVal); - if (derVal.data.available () != 0) - throw new CertParseError ("garbage at end"); - signedCert = derVal.toByteArray (); - } - - - /** - * Partially constructs a certificate from descriptive parameters. - * This constructor may be used by Certificate Authority (CA) code, - * which later signs and encodes the - * certificate. Also, self-signed certificates serve as CA certificates, - * and are sometimes used as certificate requests. - * - *

    Until the certificate has been signed and encoded, some of - * the mandatory fields in the certificate will not be available - * via accessor functions: the serial number, issuer name and signing - * algorithm, and of course the signed certificate. The fields passed - * to this constructor are available, and must be non-null. - * - *

    Note that the public key being signed is generally independent of - * the signature algorithm being used. So for example Diffie-Hellman - * keys (which do not support signatures) can be placed in X.509 - * certificates when some other signature algorithm (e.g. DSS/DSA, - * or one of the RSA based algorithms) is used. - * - * @see CertAndKeyGen - * - * @param subjectName the X.500 distinguished name being certified - * @param subjectPublicKey the public key being certified. This - * must be an "X509Key" implementing the "PublicKey" interface. - * @param notBefore the first time the certificate is valid - * @param notAfter the last time the certificate is valid - * - * @exception CertException if the public key is inappropriate - */ - public X509Cert(X500Name subjectName, X509Key subjectPublicKey, - Date notBefore, Date notAfter) throws CertException - { - subject = subjectName; - - if (!(subjectPublicKey instanceof PublicKey)) - throw new CertException (CertException.err_INVALID_PUBLIC_KEY, - "Doesn't implement PublicKey interface"); - - // The X509 cert API requires X509 keys, else things break. - pubkey = subjectPublicKey; - notbefore = notBefore; - notafter = notAfter; - version = 0; - } - - - /** - * Decode an X.509 certificate from an input stream. - * - * @param in an input stream holding at least one certificate - * @exception IOException when the certificate is improperly encoded, or - * if it has already been parsed. - */ - public void decode(InputStream in) throws IOException - { - DerValue val = new DerValue(in); - parse(val); - signedCert = val.toByteArray(); - } - - - /** - * Appends the certificate to an output stream. - * - * @param out an input stream to which the certificate is appended. - * @exception IOException when appending fails. - */ - public void encode (OutputStream out) throws IOException - { out.write (getSignedCert ()); } - - - /** - * Compares two certificates. This is false if the - * certificates are not both X.509 certs, otherwise it - * compares them as binary data. - * - * @param other the object being compared with this one - * @return true iff the certificates are equivalent - */ - public boolean equals (Object other) - { - if (other instanceof X509Cert) - return equals ((X509Cert) other); - else - return false; - } - - - /** - * Compares two certificates, returning false if any data - * differs between the two. - * - * @param other the object being compared with this one - * @return true iff the certificates are equivalent - */ - public boolean equals (X509Cert src) - { - if (this == src) - return true; - if (signedCert == null || src.signedCert == null) - return false; - if (signedCert.length != src.signedCert.length) - return false; - for (int i = 0; i < signedCert.length; i++) - if (signedCert [i] != src.signedCert [i]) - return false; - return true; - } - - - /** Returns the "X.509" format identifier. */ - public String getFormat () // for Certificate - { return "X.509"; } - - - /** Returns getIssuerName */ - public Principal getGuarantor () // for Certificate - { return getIssuerName (); } - - - /** Returns getSubjectName */ - public Principal getPrincipal () - { return getSubjectName (); } - - - /** - * Throws an exception if the certificate is invalid because it is - * now outside of the certificate's validity period, or because it - * was not signed using the verification key provided. Successfully - * verifying a certificate does not indicate that one should - * trust the entity which it represents. - * - *

    Note that since this class represents only a single X.509 - * certificate, it cannot know anything about the certificate chain - * which is used to provide the verification key and to establish trust. - * Other code must manage and use those cert chains. - * - *

    For now, you must walk the cert chain being used to verify any - * given cert. Start at the root, which is a self-signed certificate; - * verify it using the key inside the certificate. Then use that to - * verify the next certificate in the chain, issued by that CA. In - * this manner, verify each certificate until you reach the particular - * certificate you wish to verify. You should not use a certificate - * if any of the verification operations for its certificate chain - * were unsuccessful. - * - * - * @param issuerPublicKey the public key of the issuing CA - * @exception CertException when the certificate is not valid. - */ - public void verify (PublicKey issuerPublicKey) - throws CertException - { - Date now = new Date (); - - if (now.before (notbefore)) - throw new CertException (CertException.verf_INVALID_NOTBEFORE); - if (now.after (notafter)) - throw new CertException (CertException.verf_INVALID_EXPIRED); - if (signedCert == null) - throw new CertException (CertException.verf_INVALID_SIG, - "?? certificate is not signed yet ??"); - - // - // Verify the signature ... - // - String algName = null; - - try { - Signature sigVerf = null; - - algName = issuerSigAlg.getName(); - sigVerf = Signature.getInstance(algName); - sigVerf.initVerify (issuerPublicKey); - sigVerf.update (rawCert, 0, rawCert.length); - - if (!sigVerf.verify (signature)) { - throw new CertException (CertException.verf_INVALID_SIG, - "Signature ... by <" + issuer + "> for <" + subject + ">"); - } - - // Gag -- too many catch clauses, let most through. - - } catch (NoSuchAlgorithmException e) { - throw new CertException (CertException.verf_INVALID_SIG, - "Unsupported signature algorithm (" + algName + ")"); - - } catch (InvalidKeyException e) { - // e.printStackTrace(); - throw new CertException (CertException.err_INVALID_PUBLIC_KEY, - "Algorithm (" + algName + ") rejected public key"); - - } catch (SignatureException e) { - throw new CertException (CertException.verf_INVALID_SIG, - "Signature by <" + issuer + "> for <" + subject + ">"); - } - } - - - /** - * Creates an X.509 certificate, and signs it using the issuer - * passed (associating a signature algorithm and an X.500 name). - * This operation is used to implement the certificate generation - * functionality of a certificate authority. - * - * @see #getSignedCert - * @see #getSigner - * @see CertAndKeyGen - * - * @param serial the serial number of the certificate (non-null) - * @param issuer the certificate issuer (CA) (non-null) - * @return the signed certificate, as returned by getSignedCert - * - * @exception IOException if any of the data could not be encoded, - * or when any mandatory data was omitted - * @exception SignatureException on signing failures - */ - public byte [] - encodeAndSign ( - BigInteger serial, - X500Signer issuer - ) throws IOException, SignatureException - { - rawCert = null; - - /* - * Get the remaining cert parameters, and make sure we have enough. - * - * We deduce version based on what attribute data are available - * For now, we have no attributes, so we always deduce X.509v1 ! - */ - version = 0; - serialnum = serial; - this.issuer = issuer.getSigner (); - issuerSigAlg = issuer.getAlgorithmId (); - - if (subject == null || pubkey == null - || notbefore == null || notafter == null) - throw new IOException ("not enough cert parameters"); - - /* - * Encode the raw cert, create its signature and put it - * into the envelope. - */ - rawCert = DERencode (); - signedCert = sign (issuer, rawCert); - return signedCert; - } - - - /** - * Returns an X500Signer that may be used to create signatures. Those - * signature may in turn be verified using this certificate (or a - * copy of it). - * - *

    NOTE: If the private key is by itself capable of - * creating signatures, this fact may not be recognized at this time. - * Specifically, the case of DSS/DSA keys which get their algorithm - * parameters from higher in the certificate chain is not supportable - * without using an X509CertChain API, and there is no current support - * for other sources of algorithm parameters. - * - * @param algorithm the signature algorithm to be used. Note that a - * given public/private key pair may support several such algorithms. - * @param privateKey the private key used to create the signature, - * which must correspond to the public key in this certificate - * @return the Signer object - * - * @exception NoSuchAlgorithmException if the signature - * algorithm is not supported - * @exception InvalidKeyException if either the key in the certificate, - * or the private key parameter, does not support the requested - * signature algorithm - */ - public X500Signer getSigner (AlgorithmId algorithmId, - PrivateKey privateKey) - throws NoSuchAlgorithmException, InvalidKeyException - { - String algorithm; - Signature sig; - - if (privateKey instanceof Key) { - Key key = (Key)privateKey; - algorithm = key.getAlgorithm(); - } else { - throw new InvalidKeyException("private key not a key!"); - } - - sig = Signature.getInstance(algorithmId.getName()); - - if (!pubkey.getAlgorithm ().equals (algorithm)) { - - throw new InvalidKeyException( "Private key algorithm " + - algorithm + - " incompatible with certificate " + - pubkey.getAlgorithm()); - } - sig.initSign (privateKey); - return new X500Signer (sig, subject); - } - - - /** - * Returns a signature object that may be used to verify signatures - * created using a specified signature algorithm and the public key - * contained in this certificate. - * - *

    NOTE: If the public key in this certificate is not by - * itself capable of verifying signatures, this may not be recognized - * at this time. Specifically, the case of DSS/DSA keys which get - * their algorithm parameters from higher in the certificate chain - * is not supportable without using an X509CertChain API, and there - * is no current support for other sources of algorithm parameters. - * - * @param algorithm the algorithm of the signature to be verified - * @return the Signature object - * @exception NoSuchAlgorithmException if the signature - * algorithm is not supported - * @exception InvalidKeyException if the key in the certificate - * does not support the requested signature algorithm - */ - public Signature getVerifier(String algorithm) - throws NoSuchAlgorithmException, InvalidKeyException - { - String algName; - Signature sig; - - sig = Signature.getInstance(algorithm); - sig.initVerify (pubkey); - return sig; - } - - - - /** - * Return the signed X.509 certificate as a byte array. - * The bytes are in standard DER marshaled form. - * Null is returned in the case of a partially constructed cert. - */ - public byte [] getSignedCert () - { return signedCert.clone(); } - - - /** - * Returns the certificate's serial number. - * Null is returned in the case of a partially constructed cert. - */ - public BigInteger getSerialNumber () - { return serialnum; } - - - /** - * Returns the subject's X.500 distinguished name. - */ - public X500Name getSubjectName () - { return subject; } - - - /** - * Returns the certificate issuer's X.500 distinguished name. - * Null is returned in the case of a partially constructed cert. - */ - public X500Name getIssuerName () - { return issuer; } - - - /** - * Returns the algorithm used by the issuer to sign the certificate. - * Null is returned in the case of a partially constructed cert. - */ - public AlgorithmId getIssuerAlgorithmId () - { return issuerSigAlg; } - - - /** - * Returns the first time the certificate is valid. - */ - public Date getNotBefore () - { return new Date(notbefore.getTime()); } - - - /** - * Returns the last time the certificate is valid. - */ - public Date getNotAfter () - { return new Date(notafter.getTime()); } - - - /** - * Returns the subject's public key. Note that some public key - * algorithms support an optional certificate generation policy - * where the keys in the certificates are not in themselves sufficient - * to perform a public key operation. Those keys need to be augmented - * by algorithm parameters, which the certificate generation policy - * chose not to place in the certificate. - * - *

    Two such public key algorithms are: DSS/DSA, where algorithm - * parameters could be acquired from a CA certificate in the chain - * of issuers; and Diffie-Hellman, with a similar solution although - * the CA then needs both a Diffie-Hellman certificate and a signature - * capable certificate. - */ - public PublicKey getPublicKey () - { return pubkey; } - - - /** - * Returns the X.509 version number of this certificate, zero based. - * That is, "2" indicates an X.509 version 3 (1993) certificate, - * and "0" indicates X.509v1 (1988). - * Zero is returned in the case of a partially constructed cert. - */ - public int getVersion () - { return version; } - - - /** - * Calculates a hash code value for the object. Objects - * which are equal will also have the same hashcode. - */ - public int hashCode () - { - int retval = 0; - - for (int i = 0; i < signedCert.length; i++) - retval += signedCert [i] * i; - return retval; - } - - - /** - * Returns a printable representation of the certificate. This does not - * contain all the information available to distinguish this from any - * other certificate. The certificate must be fully constructed - * before this function may be called; in particular, if you are - * creating certificates you must call encodeAndSign() before calling - * this function. - */ - public String toString () - { - String s; - - if (subject == null || pubkey == null - || notbefore == null || notafter == null - || issuer == null || issuerSigAlg == null - || serialnum == null) - throw new NullPointerException ("X.509 cert is incomplete"); - - s = " X.509v" + (version + 1) + " certificate,\n"; - s += " Subject is " + subject + "\n"; - s += " Key: " + pubkey; - s += " Validity <" + notbefore + "> until <" + notafter + ">\n"; - s += " Issuer is " + issuer + "\n"; - s += " Issuer signature used " + issuerSigAlg.toString () + "\n"; - s += " Serial number = " + Debug.toHexString(serialnum) + "\n"; - - // optional v2, v3 extras - - return "[\n" + s + "]"; - } - - - /** - * Returns a printable representation of the certificate. - * - * @param detailed true iff lots of detail is requested - */ - public String toString (boolean detailed) - { return toString (); } - - - /************************************************************/ - - /* - * Cert is a SIGNED ASN.1 macro, a three elment sequence: - * - * - Data to be signed (ToBeSigned) -- the "raw" cert - * - Signature algorithm (SigAlgId) - * - The signature bits - * - * This routine unmarshals the certificate, saving the signature - * parts away for later verification. - */ - private void parse (DerValue val) throws IOException - { - if (parsed == true) { - throw new IOException("Certificate already parsed"); - } - - DerValue seq [] = new DerValue [3]; - - seq [0] = val.data.getDerValue (); - seq [1] = val.data.getDerValue (); - seq [2] = val.data.getDerValue (); - - if (val.data.available () != 0) - throw new CertParseError ("signed overrun, bytes = " - + val.data.available ()); - if (seq [0].tag != DerValue.tag_Sequence) - throw new CertParseError ("signed fields invalid"); - - rawCert = seq [0].toByteArray (); // XXX slow; fixme! - - - issuerSigAlg = AlgorithmId.parse (seq [1]); - signature = seq [2].getBitString (); - - if (seq [1].data.available () != 0) { - // XXX why was this error check commented out? - // It was originally part of the next check. - throw new CertParseError ("algid field overrun"); - } - - if (seq [2].data.available () != 0) - throw new CertParseError ("signed fields overrun"); - - /* - * Let's have fun parsing the cert itself. - */ - DerInputStream in; - DerValue tmp; - - in = seq [0].data; - - /* - * Version -- this is optional (default zero). If it's there it's - * the first field and is specially tagged. - * - * Both branches leave "tmp" holding a value for the serial - * number that comes next. - */ - version = 0; - tmp = in.getDerValue (); - if (tmp.isConstructed () && tmp.isContextSpecific ()) { - version = tmp.data.getInteger(); - if (tmp.data.available () != 0) - throw new IOException ("X.509 version, bad format"); - tmp = in.getDerValue (); - } - - /* - * serial number ... an integer - */ - serialnum = tmp.getBigInteger (); - - /* - * algorithm type for CA's signature ... needs to match the - * one on the envelope, and that's about it! different IDs - * may represent a signature attack. In general we want to - * inherit parameters. - */ - tmp = in.getDerValue (); - { - AlgorithmId algid; - - - algid = AlgorithmId.parse(tmp); - - if (!algid.equals (issuerSigAlg)) - throw new CertParseError ("CA Algorithm mismatch!"); - - this.algid = algid; - } - - /* - * issuer name - */ - issuer = new X500Name (in); - - /* - * validity: SEQUENCE { start date, end date } - */ - tmp = in.getDerValue (); - if (tmp.tag != DerValue.tag_Sequence) - throw new CertParseError ("corrupt validity field"); - - notbefore = tmp.data.getUTCTime (); - notafter = tmp.data.getUTCTime (); - if (tmp.data.available () != 0) - throw new CertParseError ("excess validity data"); - - /* - * subject name and public key - */ - subject = new X500Name (in); - - tmp = in.getDerValue (); - pubkey = X509Key.parse (tmp); - - /* - * XXX for v2 and later, a bunch of tagged options follow - */ - - if (in.available () != 0) { - /* - * Until we parse V2/V3 data ... ignore it. - * - // throw new CertParseError ("excess cert data"); - System.out.println ( - "@end'o'cert, optional V2/V3 data unparsed: " - + in.available () - + " bytes" - ); - */ - } - - parsed = true; - } - - - /* - * Encode only the parts that will later be signed. - */ - private byte [] DERencode () throws IOException - { - DerOutputStream raw = new DerOutputStream (); - - encode (raw); - return raw.toByteArray (); - } - - - /* - * Marshal the contents of a "raw" certificate into a DER sequence. - */ - private void encode (DerOutputStream out) throws IOException - { - DerOutputStream tmp = new DerOutputStream (); - - /* - * encode serial number, issuer signing algorithm, - * and issuer name into the data we'll return - */ - tmp.putInteger (serialnum); - issuerSigAlg.encode (tmp); - issuer.encode (tmp); - - /* - * Validity is a two element sequence ... encode the - * elements, then wrap them into the data we'll return - */ - { - DerOutputStream seq = new DerOutputStream (); - - seq.putUTCTime (notbefore); - seq.putUTCTime (notafter); - tmp.write (DerValue.tag_Sequence, seq); - } - - /* - * Encode subject (principal) and associated key - */ - subject.encode (tmp); - tmp.write(pubkey.getEncoded()); - - /* - * Wrap the data; encoding of the "raw" cert is now complete. - */ - out.write (DerValue.tag_Sequence, tmp); - } - - - /* - * Calculate the signature of the "raw" certificate, - * and marshal the cert with the signature and a - * description of the signing algorithm. - */ - private byte [] sign (X500Signer issuer, byte data []) - throws IOException, SignatureException - { - /* - * Encode the to-be-signed data, then the algorithm used - * to create the signature. - */ - DerOutputStream out = new DerOutputStream (); - DerOutputStream tmp = new DerOutputStream (); - - tmp.write (data); - issuer.getAlgorithmId ().encode(tmp); - - - /* - * Create and encode the signature itself. - */ - issuer.update (data, 0, data.length); - signature = issuer.sign (); - tmp.putBitString (signature); - - /* - * Wrap the signed data in a SEQUENCE { data, algorithm, sig } - */ - out.write (DerValue.tag_Sequence, tmp); - return out.toByteArray (); - } - - - /** - * Serialization write ... X.509 certificates serialize as - * themselves, and they're parsed when they get read back. - * (Actually they serialize as some type data from the - * serialization subsystem, then the cert data.) - */ - private void writeObject (java.io.ObjectOutputStream stream) - throws IOException - { encode(stream); } - - /** - * Serialization read ... X.509 certificates serialize as - * themselves, and they're parsed when they get read back. - */ - private void readObject (ObjectInputStream stream) - throws IOException - { decode(stream); } -} diff --git a/jdk/src/share/classes/sun/tools/jar/JarVerifierStream.java b/jdk/src/share/classes/sun/tools/jar/JarVerifierStream.java deleted file mode 100644 index 52a48d18dd3..00000000000 --- a/jdk/src/share/classes/sun/tools/jar/JarVerifierStream.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright 1996-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 sun.tools.jar; - -import java.io.*; -import java.util.*; -import java.util.zip.*; -import java.util.jar.*; -import java.security.cert.Certificate; -import java.security.AccessController; -import java.security.cert.X509Certificate; -import java.security.PublicKey; -import java.security.Principal; -import sun.security.provider.SystemIdentity; - -/** - * This is OBSOLETE. DO NOT USE THIS. Use - * java.util.jar.JarEntry.getCertificates instead. It has to stay here - * because some apps (namely HJ and HJV) call directly into it. - * - * This class is stripped down greatly from JDK 1.1.x. - * - * @author Roland Schemers - */ -public class JarVerifierStream extends ZipInputStream { - - private JarEntry current; - private Hashtable> verified - = new Hashtable>(); - private JarInputStream jis; - private sun.tools.jar.Manifest man = null; - - /** - * construct a JarVerfierStream from an input stream. - */ - public JarVerifierStream(InputStream is) - throws IOException - { - super(is); - jis = new JarInputStream(is); - } - - public void close() - throws IOException - { - jis.close(); - } - - public void closeEntry() throws IOException { - jis.closeEntry(); - } - - /** - * This method scans to see which entry we're parsing and - * keeps various state information depending on what type of - * file is being parsed. Files it treats specially are:

      - * - *
    • Manifest files. At any point, this stream can be queried - * for a manifest. If it is present, a Manifest object will be - * returned. - * - *
    • Block Signature file. Like with the manifest, the stream - * can be queried at any time for all blocks parsed thus far. - * - *
    - */ - public synchronized ZipEntry getNextEntry() throws IOException { - current = (JarEntry) jis.getNextEntry(); - return current; - } - - /** - * read a single byte. - */ - public int read() throws IOException { - int n = jis.read(); - if (n == -1) { - addIds(); - } - return n; - } - - /** - * read an array of bytes. - */ - public int read(byte[] b, int off, int len) throws IOException { - int n = jis.read(b, off, len); - if (n == -1) { - addIds(); - } - return n; - } - - private void addIds() - { - - if (current != null) { - Certificate[] certs = current.getCertificates(); - if (certs != null) { - Vector ids = getIds(certs); - if (ids != null) { - verified.put(current.getName(), ids); - } - } - } - } - - /** - * Returns a Hashtable mapping filenames to vectors of identities. - */ - public Hashtable getVerifiedSignatures() { - /* we may want to return a copy of this at some point. - For now we simply trust the caller */ - if (verified.isEmpty()) - return null; - else - return verified; - } - - /** - * Returns an enumeration of PKCS7 blocks. This looks bogus, - * but Hotjava just checks to see if enumeration is not null - * to see if anything was signed! - */ - public Enumeration getBlocks() { - if (verified.isEmpty()) { - return null; - } else { - return new Enumeration() { - public boolean hasMoreElements() { return false; } - public Object nextElement() { return null; } - }; - } - } - - /** - * This method used to be called by various versions of - * AppletResourceLoader, even though they didn't do anything with - * the result. We leave them and return null for backwards compatability. - */ - public Hashtable getNameToHash() { - return null; - } - - /** - * Convert java.util.jar.Manifest object to a sun.tools.jar.Manifest - * object. - */ - - public sun.tools.jar.Manifest getManifest() { - if (man == null) { - try { - java.util.jar.Manifest jman = jis.getManifest(); - if (jman == null) - return null; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - jman.write(baos); - byte[] data = baos.toByteArray(); - man = new sun.tools.jar.Manifest(data); - } catch (IOException ioe) { - // return null - } - } - return man; - } - - static class CertCache { - Certificate [] certs; - Vector ids; - - boolean equals(Certificate[] certs) { - if (this.certs == null) { - if (certs!= null) - return false; - else - return true; - } - - if (certs == null) - return false; - - boolean match; - - for (int i = 0; i < certs.length; i++) { - match = false; - for (int j = 0; j < this.certs.length; j++) { - if (certs[i].equals(this.certs[j])) { - match = true; - break; - } - } - if (!match) return false; - } - - for (int i = 0; i < this.certs.length; i++) { - match = false; - for (int j = 0; j < certs.length; j++) { - if (this.certs[i].equals(certs[j])) { - match = true; - break; - } - } - if (!match) return false; - } - return true; - } - } - - private ArrayList certCache = null; - - - /** - * Returns the Identity vector for the given array of Certificates - */ - protected Vector getIds(Certificate[] certs) { - if (certs == null) - return null; - - if (certCache == null) - certCache = new ArrayList(); - CertCache cc; - for (int i = 0; i < certCache.size(); i++) { - cc = certCache.get(i); - if (cc.equals(certs)) { - return cc.ids; - } - } - cc = new CertCache(); - cc.certs = certs; - - if (certs.length > 0) { - for (int i=0; i() { - public Void run() - throws java.security.KeyManagementException - { - id.addCertificate(oldC); - return null; - } - }); - } catch (java.security.PrivilegedActionException pae) { - throw (java.security.KeyManagementException) - pae.getException(); - } - if (cc.ids == null) - cc.ids = new Vector(); - cc.ids.addElement(id); - } catch (java.security.KeyManagementException kme) { - // ignore if we can't create Identity - } catch (IOException ioe) { - // ignore if we can't parse - } catch (java.security.cert.CertificateEncodingException cee) { - // ignore if we can't encode - } - } - } - certCache.add(cc); - return cc.ids; - } -} From 5732731ca5b6f351625091f7010959db58af1f86 Mon Sep 17 00:00:00 2001 From: Martin Buchholz Date: Mon, 7 Dec 2009 15:32:26 -0800 Subject: [PATCH 51/56] 6905029: Broken links in Deflater and DeflaterOutputStream javadoc Fix syntax errors in @links Reviewed-by: alanb --- jdk/src/share/classes/java/util/zip/Deflater.java | 4 ++-- .../classes/java/util/zip/DeflaterOutputStream.java | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/jdk/src/share/classes/java/util/zip/Deflater.java b/jdk/src/share/classes/java/util/zip/Deflater.java index e592ce0dfd4..dbf25e688fc 100644 --- a/jdk/src/share/classes/java/util/zip/Deflater.java +++ b/jdk/src/share/classes/java/util/zip/Deflater.java @@ -318,7 +318,7 @@ class Deflater { /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value - * of 0 indicates that {@link needsInput() needsInput} should be called + * of 0 indicates that {@link #needsInput() needsInput} should be called * in order to determine if more input data is required. * *

    This method uses {@link #NO_FLUSH} as its compression flush mode. @@ -339,7 +339,7 @@ class Deflater { /** * Compresses the input data and fills specified buffer with compressed * data. Returns actual number of bytes of compressed data. A return value - * of 0 indicates that {@link needsInput() needsInput} should be called + * of 0 indicates that {@link #needsInput() needsInput} should be called * in order to determine if more input data is required. * *

    This method uses {@link #NO_FLUSH} as its compression flush mode. diff --git a/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java b/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java index 238de92e815..109f698199b 100644 --- a/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java +++ b/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java @@ -66,7 +66,7 @@ class DeflaterOutputStream extends FilterOutputStream { * @param def the compressor ("deflater") * @param size the output buffer size * @param syncFlush - * if {@code true} the {@link flush()} method of this + * if {@code true} the {@link #flush()} method of this * instance flushes the compressor with flush mode * {@link Deflater#SYNC_FLUSH} before flushing the output * stream, otherwise only flushes the output stream @@ -114,7 +114,7 @@ class DeflaterOutputStream extends FilterOutputStream { * @param out the output stream * @param def the compressor ("deflater") * @param syncFlush - * if {@code true} the {@link flush()} method of this + * if {@code true} the {@link #flush()} method of this * instance flushes the compressor with flush mode * {@link Deflater#SYNC_FLUSH} before flushing the output * stream, otherwise only flushes the output stream @@ -151,7 +151,7 @@ class DeflaterOutputStream extends FilterOutputStream { * * @param out the output stream * @param syncFlush - * if {@code true} the {@link flush()} method of this + * if {@code true} the {@link #flush()} method of this * instance flushes the compressor with flush mode * {@link Deflater#SYNC_FLUSH} before flushing the output * stream, otherwise only flushes the output stream @@ -262,10 +262,10 @@ class DeflaterOutputStream extends FilterOutputStream { /** * Flushes the compressed output stream. * - * If {@link DeflaterOutputStream(OutputStream, Deflater, int, boolean) + * If {@link #DeflaterOutputStream(OutputStream, Deflater, int, boolean) * syncFlush} is {@code true} when this compressed output stream is - * constructed this method flushes the underlying {@code compressor} - * first with the flush mode {@link Deflater#SYNC_FLUSH} to force + * constructed, this method first flushes the underlying {@code compressor} + * with the flush mode {@link Deflater#SYNC_FLUSH} to force * all pending data to be flushed out to the output stream and then * flushes the output stream. Otherwise this method only flushes the * output stream without flushing the {@code compressor}. From 74ad65ac210db29cbaabb57558293a0e272eb007 Mon Sep 17 00:00:00 2001 From: Martin Buchholz Date: Mon, 7 Dec 2009 16:44:40 -0800 Subject: [PATCH 52/56] 6900043: Add method to return line.separator property Add System.lineSeparator(), returning getProperty("line.separator") Reviewed-by: darcy --- jdk/src/share/classes/java/lang/System.java | 17 ++++++++++++++++- jdk/src/share/classes/java/util/Formatter.java | 7 +------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/jdk/src/share/classes/java/lang/System.java b/jdk/src/share/classes/java/lang/System.java index b0c46528cbd..3d55a2eaea4 100644 --- a/jdk/src/share/classes/java/lang/System.java +++ b/jdk/src/share/classes/java/lang/System.java @@ -619,6 +619,20 @@ public final class System { return props; } + /** + * Returns the system-dependent line separator string. It always + * returns the same value - the initial value of the {@linkplain + * #getProperty(String) system property} {@code line.separator}. + * + *

    On UNIX systems, it returns {@code "\n"}; on Microsoft + * Windows systems it returns {@code "\r\n"}. + */ + public static String lineSeparator() { + return lineSeparator; + } + + private static String lineSeparator; + /** * Sets the system properties to the Properties * argument. @@ -1104,6 +1118,7 @@ public final class System { private static void initializeSystemClass() { props = new Properties(); initProperties(props); + lineSeparator = props.getProperty("line.separator"); sun.misc.Version.init(); // Workaround until DownloadManager initialization is revisited. @@ -1192,7 +1207,7 @@ public final class System { } /* returns the class of the caller. */ - static Class getCallerClass() { + static Class getCallerClass() { // NOTE use of more generic Reflection.getCallerClass() return Reflection.getCallerClass(3); } diff --git a/jdk/src/share/classes/java/util/Formatter.java b/jdk/src/share/classes/java/util/Formatter.java index 59ff1da0711..46a6431298c 100644 --- a/jdk/src/share/classes/java/util/Formatter.java +++ b/jdk/src/share/classes/java/util/Formatter.java @@ -2552,9 +2552,6 @@ public final class Formatter implements Closeable, Flushable { private boolean dt = false; private char c; - // cache the line separator - private String ls; - private int index(String s) { if (s != null) { try { @@ -2702,9 +2699,7 @@ public final class Formatter implements Closeable, Flushable { printHashCode(arg); break; case Conversion.LINE_SEPARATOR: - if (ls == null) - ls = System.getProperty("line.separator"); - a.append(ls); + a.append(System.lineSeparator()); break; case Conversion.PERCENT_SIGN: a.append('%'); From decdef947baeed7baea99754cf9bf823bac16683 Mon Sep 17 00:00:00 2001 From: Josh Bloch Date: Tue, 8 Dec 2009 12:40:30 +0000 Subject: [PATCH 53/56] 6905046: More Dual-pivot quicksort improvements More improvements from the DPQ team Reviewed-by: alanb --- .../classes/java/util/DualPivotQuicksort.java | 1030 ++++++++++------- 1 file changed, 627 insertions(+), 403 deletions(-) diff --git a/jdk/src/share/classes/java/util/DualPivotQuicksort.java b/jdk/src/share/classes/java/util/DualPivotQuicksort.java index b368d0b95b1..07cda259dd4 100644 --- a/jdk/src/share/classes/java/util/DualPivotQuicksort.java +++ b/jdk/src/share/classes/java/util/DualPivotQuicksort.java @@ -36,12 +36,12 @@ package java.util; * @author Jon Bentley * @author Josh Bloch * - * @version 2009.11.16 m765.827.v12a + * @version 2009.11.29 m765.827.12i */ final class DualPivotQuicksort { /** - * Suppresses default constructor. + * Prevents instantiation. */ private DualPivotQuicksort() {} @@ -84,7 +84,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * * @param a the array to be sorted * @param fromIndex the index of the first element, inclusive, to be sorted @@ -101,8 +101,8 @@ final class DualPivotQuicksort { /** * Sorts the specified range of the array into ascending order. This * method differs from the public {@code sort} method in that the - * {@code right} index is inclusive, and it does no range checking on - * {@code left} or {@code right}. + * {@code right} index is inclusive, and it does no range checking + * on {@code left} or {@code right}. * * @param a the array to be sorted * @param left the index of the first element, inclusive, to be sorted @@ -111,13 +111,13 @@ final class DualPivotQuicksort { private static void doSort(int[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - int ak = a[k]; + for (int i = left + 1; i <= right; i++) { + int ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else { // Use Dual-Pivot Quicksort on large arrays dualPivotQuicksort(a, left, right); @@ -162,7 +162,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -170,27 +170,26 @@ final class DualPivotQuicksort { int pivot1 = ae2; a[e2] = a[left]; int pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -200,37 +199,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { int ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -243,30 +242,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { int ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -289,26 +292,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { int ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -330,7 +362,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * * @param a the array to be sorted * @param fromIndex the index of the first element, inclusive, to be sorted @@ -357,13 +389,13 @@ final class DualPivotQuicksort { private static void doSort(long[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - long ak = a[k]; + for (int i = left + 1; i <= right; i++) { + long ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else { // Use Dual-Pivot Quicksort on large arrays dualPivotQuicksort(a, left, right); @@ -408,7 +440,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -416,27 +448,26 @@ final class DualPivotQuicksort { long pivot1 = ae2; a[e2] = a[left]; long pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -446,37 +477,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { long ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -489,30 +520,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { long ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -535,26 +570,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { long ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -576,7 +640,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * * @param a the array to be sorted * @param fromIndex the index of the first element, inclusive, to be sorted @@ -606,13 +670,13 @@ final class DualPivotQuicksort { private static void doSort(short[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - short ak = a[k]; + for (int i = left + 1; i <= right; i++) { + short ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else if (right-left+1 > COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR) { // Use counting sort on huge arrays @@ -671,7 +735,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -679,27 +743,26 @@ final class DualPivotQuicksort { short pivot1 = ae2; a[e2] = a[left]; short pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -709,37 +772,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { short ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -752,30 +815,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { short ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -798,26 +865,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { short ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -839,7 +935,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * * @param a the array to be sorted * @param fromIndex the index of the first element, inclusive, to be sorted @@ -869,13 +965,13 @@ final class DualPivotQuicksort { private static void doSort(char[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - char ak = a[k]; + for (int i = left + 1; i <= right; i++) { + char ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else if (right-left+1 > COUNTING_SORT_THRESHOLD_FOR_SHORT_OR_CHAR) { // Use counting sort on huge arrays @@ -932,7 +1028,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -940,27 +1036,26 @@ final class DualPivotQuicksort { char pivot1 = ae2; a[e2] = a[left]; char pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -970,37 +1065,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { char ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -1013,30 +1108,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { char ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -1059,26 +1158,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { char ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -1100,7 +1228,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * * @param a the array to be sorted * @param fromIndex the index of the first element, inclusive, to be sorted @@ -1130,13 +1258,13 @@ final class DualPivotQuicksort { private static void doSort(byte[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - byte ak = a[k]; + for (int i = left + 1; i <= right; i++) { + byte ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else if (right - left + 1 > COUNTING_SORT_THRESHOLD_FOR_BYTE) { // Use counting sort on huge arrays @@ -1195,7 +1323,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -1203,27 +1331,26 @@ final class DualPivotQuicksort { byte pivot1 = ae2; a[e2] = a[left]; byte pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -1233,37 +1360,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { byte ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -1276,30 +1403,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { byte ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -1322,26 +1453,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { byte ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -1371,7 +1531,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty and the call is a no-op). * *

    The {@code <} relation does not provide a total order on all float * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN} @@ -1485,13 +1645,13 @@ final class DualPivotQuicksort { private static void doSort(float[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - float ak = a[k]; + for (int i = left + 1; i <= right; i++) { + float ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else { // Use Dual-Pivot Quicksort on large arrays dualPivotQuicksort(a, left, right); @@ -1536,7 +1696,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -1544,27 +1704,26 @@ final class DualPivotQuicksort { float pivot1 = ae2; a[e2] = a[left]; float pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -1574,37 +1733,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { float ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -1617,30 +1776,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { float ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -1663,26 +1826,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { float ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } @@ -1712,7 +1904,7 @@ final class DualPivotQuicksort { * Sorts the specified range of the array into ascending order. The range * to be sorted extends from the index {@code fromIndex}, inclusive, to * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex}, - * the range to be sorted is empty. + * the range to be sorted is empty (and the call is a no-op). * *

    The {@code <} relation does not provide a total order on all double * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN} @@ -1826,13 +2018,13 @@ final class DualPivotQuicksort { private static void doSort(double[] a, int left, int right) { // Use insertion sort on tiny arrays if (right - left + 1 < INSERTION_SORT_THRESHOLD) { - for (int k = left + 1; k <= right; k++) { - double ak = a[k]; + for (int i = left + 1; i <= right; i++) { + double ai = a[i]; int j; - for (j = k - 1; j >= left && ak < a[j]; j--) { + for (j = i - 1; j >= left && ai < a[j]; j--) { a[j + 1] = a[j]; } - a[j + 1] = ak; + a[j + 1] = ai; } } else { // Use Dual-Pivot Quicksort on large arrays dualPivotQuicksort(a, left, right); @@ -1877,7 +2069,7 @@ final class DualPivotQuicksort { * second terciles of the array. Note that pivot1 <= pivot2. * * The pivots are stored in local variables, and the first and - * the last of the sorted elements are moved to the locations + * the last of the elements to be sorted are moved to the locations * formerly occupied by the pivots. When partitioning is complete, * the pivots are swapped back into their final positions, and * excluded from subsequent sorting. @@ -1885,27 +2077,26 @@ final class DualPivotQuicksort { double pivot1 = ae2; a[e2] = a[left]; double pivot2 = ae4; a[e4] = a[right]; - /* - * Partitioning - * - * left part center part right part - * ------------------------------------------------------------ - * [ < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 ] - * ------------------------------------------------------------ - * ^ ^ ^ - * | | | - * less k great - */ - // Pointers int less = left + 1; // The index of first element of center part int great = right - 1; // The index before first element of right part - boolean pivotsDiffer = pivot1 != pivot2; + boolean pivotsDiffer = (pivot1 != pivot2); if (pivotsDiffer) { /* + * Partitioning: + * + * left part center part right part + * +------------------------------------------------------------+ + * | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 | + * +------------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * * Invariants: + * * all in (left, less) < pivot1 * pivot1 <= all in [less, k) <= pivot2 * all in (great, right) > pivot2 @@ -1915,37 +2106,37 @@ final class DualPivotQuicksort { outer: for (int k = less; k <= great; k++) { double ak = a[k]; - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else if (ak > pivot2) { + } else if (ak > pivot2) { // Move a[k] to right part while (a[great] > pivot2) { - if (k == great--) { + if (great-- == k) { break outer; } } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // pivot1 <= a[great] <= pivot2 + a[k] = a[great]; + a[great--] = ak; } } } } else { // Pivots are equal /* - * Partition degenerates to the traditional 3-way - * (or "Dutch National Flag") partition: + * Partition degenerates to the traditional 3-way, + * or "Dutch National Flag", partition: * * left part center part right part - * ------------------------------------------------- - * [ < pivot | == pivot | ? | > pivot ] - * ------------------------------------------------- - * + * +----------------------------------------------+ + * | < pivot | == pivot | ? | > pivot | + * +----------------------------------------------+ * ^ ^ ^ * | | | * less k great @@ -1958,30 +2149,34 @@ final class DualPivotQuicksort { * * Pointer k is the first index of ?-part */ - outer: for (int k = less; k <= great; k++) { double ak = a[k]; if (ak == pivot1) { continue; } - if (ak < pivot1) { - if (k > less) { + if (ak < pivot1) { // Move a[k] to left part + if (k != less) { a[k] = a[less]; a[less] = ak; } less++; - } else { // a[k] > pivot + } else { // (a[k] > pivot1) - Move a[k] to right part + /* + * We know that pivot1 == a[e3] == pivot2. Thus, we know + * that great will still be >= k when the following loop + * terminates, even though we don't test for it explicitly. + * In other words, a[e3] acts as a sentinel for great. + */ while (a[great] > pivot1) { - if (k == great--) { - break outer; - } + great--; } - a[k] = a[great]; - a[great--] = ak; - - if ((ak = a[k]) < pivot1) { + if (a[great] < pivot1) { a[k] = a[less]; - a[less++] = ak; + a[less++] = a[great]; + a[great--] = ak; + } else { // a[great] == pivot1 + a[k] = pivot1; + a[great--] = ak; } } } @@ -2004,26 +2199,55 @@ final class DualPivotQuicksort { } /* - * If center part is too large (comprises > 5/6 of - * the array), swap internal pivot values to ends + * If center part is too large (comprises > 2/3 of the array), + * swap internal pivot values to ends */ - if (less < e1 && e5 < great) { + if (less < e1 && great > e5) { while (a[less] == pivot1) { less++; } while (a[great] == pivot2) { great--; } - for (int k = less + 1; k <= great; ) { + + /* + * Partitioning: + * + * left part center part right part + * +----------------------------------------------------------+ + * | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 | + * +----------------------------------------------------------+ + * ^ ^ ^ + * | | | + * less k great + * + * Invariants: + * + * all in (*, less) == pivot1 + * pivot1 < all in [less, k) < pivot2 + * all in (great, *) == pivot2 + * + * Pointer k is the first index of ?-part + */ + outer: + for (int k = less; k <= great; k++) { double ak = a[k]; - if (ak == pivot1) { - a[k++] = a[less]; - a[less++] = pivot1; - } else if (ak == pivot2) { - a[k] = a[great]; + if (ak == pivot2) { // Move a[k] to right part + while (a[great] == pivot2) { + if (great-- == k) { + break outer; + } + } + if (a[great] == pivot1) { + a[k] = a[less]; + a[less++] = pivot1; + } else { // pivot1 < a[great] < pivot2 + a[k] = a[great]; + } a[great--] = pivot2; - } else { - k++; + } else if (ak == pivot1) { // Move a[k] to left part + a[k] = a[less]; + a[less++] = pivot1; } } } From 881a1c584218e32b9427345f3d91da7b57ce0c16 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Tue, 8 Dec 2009 09:02:09 -0800 Subject: [PATCH 54/56] 6907568: java/awt/KeyboardFocusManager.java inproperly merged and lost a changeset Reapply fix for 6879044 in java.awt.KeyboardFocusManager Reviewed-by: dcherepanov, asaha --- .../java/awt/KeyboardFocusManager.java | 109 +++++++++--------- 1 file changed, 54 insertions(+), 55 deletions(-) diff --git a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java index fd412d8646e..e515e8963fd 100644 --- a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java +++ b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java @@ -53,8 +53,7 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; +import sun.util.logging.PlatformLogger; import sun.awt.AppContext; import sun.awt.HeadlessToolkit; @@ -111,7 +110,7 @@ public abstract class KeyboardFocusManager { // Shared focus engine logger - private static final Logger focusLog = Logger.getLogger("java.awt.focus.KeyboardFocusManager"); + private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.KeyboardFocusManager"); static { /* ensure that the necessary native libraries are loaded */ @@ -154,7 +153,7 @@ public abstract class KeyboardFocusManager */ private static native void initIDs(); - private static final Logger log = Logger.getLogger("java.awt.KeyboardFocusManager"); + private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.KeyboardFocusManager"); /** * The identifier for the Forward focus traversal keys. @@ -504,8 +503,8 @@ public abstract class KeyboardFocusManager if (this == getCurrentKeyboardFocusManager()) { return focusOwner; } else { - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); } throw new SecurityException(notPrivileged); } @@ -609,9 +608,9 @@ public abstract class KeyboardFocusManager } void setNativeFocusOwner(Component comp) { - if (focusLog.isLoggable(Level.FINEST)) { - focusLog.log(Level.FINEST, "Calling peer {0} setCurrentFocusOwner for {1}", - new Object[] {String.valueOf(peer), String.valueOf(comp)}); + if (focusLog.isLoggable(PlatformLogger.FINEST)) { + focusLog.finest("Calling peer {0} setCurrentFocusOwner for {1}", + String.valueOf(peer), String.valueOf(comp)); } peer.setCurrentFocusOwner(comp); } @@ -673,8 +672,8 @@ public abstract class KeyboardFocusManager if (this == getCurrentKeyboardFocusManager()) { return permanentFocusOwner; } else { - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); } throw new SecurityException(notPrivileged); } @@ -781,8 +780,8 @@ public abstract class KeyboardFocusManager if (this == getCurrentKeyboardFocusManager()) { return focusedWindow; } else { - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); } throw new SecurityException(notPrivileged); } @@ -885,8 +884,8 @@ public abstract class KeyboardFocusManager if (this == getCurrentKeyboardFocusManager()) { return activeWindow; } else { - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); } throw new SecurityException(notPrivileged); } @@ -919,8 +918,8 @@ public abstract class KeyboardFocusManager Window oldActiveWindow; synchronized (KeyboardFocusManager.class) { oldActiveWindow = getActiveWindow(); - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "Setting global active window to " + activeWindow + ", old active " + oldActiveWindow); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("Setting global active window to " + activeWindow + ", old active " + oldActiveWindow); } try { @@ -1215,8 +1214,8 @@ public abstract class KeyboardFocusManager if (this == getCurrentKeyboardFocusManager()) { return currentFocusCycleRoot; } else { - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("This manager is " + this + ", current is " + getCurrentKeyboardFocusManager()); } throw new SecurityException(notPrivileged); } @@ -2149,9 +2148,9 @@ public abstract class KeyboardFocusManager HeavyweightFocusRequest(Component heavyweight, Component descendant, boolean temporary, CausedFocusEvent.Cause cause) { - if (log.isLoggable(Level.FINE)) { + if (log.isLoggable(PlatformLogger.FINE)) { if (heavyweight == null) { - log.log(Level.FINE, "Assertion (heavyweight != null) failed"); + log.fine("Assertion (heavyweight != null) failed"); } } @@ -2161,12 +2160,12 @@ public abstract class KeyboardFocusManager } boolean addLightweightRequest(Component descendant, boolean temporary, CausedFocusEvent.Cause cause) { - if (log.isLoggable(Level.FINE)) { + if (log.isLoggable(PlatformLogger.FINE)) { if (this == HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) { - log.log(Level.FINE, "Assertion (this != HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) failed"); + log.fine("Assertion (this != HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) failed"); } if (descendant == null) { - log.log(Level.FINE, "Assertion (descendant != null) failed"); + log.fine("Assertion (descendant != null) failed"); } } @@ -2339,12 +2338,12 @@ public abstract class KeyboardFocusManager (Component heavyweight, Component descendant, boolean temporary, boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause) { - if (log.isLoggable(Level.FINE)) { + if (log.isLoggable(PlatformLogger.FINE)) { if (heavyweight == null) { - log.log(Level.FINE, "Assertion (heavyweight != null) failed"); + log.fine("Assertion (heavyweight != null) failed"); } if (time == 0) { - log.log(Level.FINE, "Assertion (time != 0) failed"); + log.fine("Assertion (time != 0) failed"); } } @@ -2361,31 +2360,31 @@ public abstract class KeyboardFocusManager Component currentFocusOwner = thisManager.getGlobalFocusOwner(); Component nativeFocusOwner = thisManager.getNativeFocusOwner(); Window nativeFocusedWindow = thisManager.getNativeFocusedWindow(); - if (focusLog.isLoggable(Level.FINER)) { - focusLog.log(Level.FINER, "SNFH for {0} in {1}", - new Object[] {String.valueOf(descendant), String.valueOf(heavyweight)}); + if (focusLog.isLoggable(PlatformLogger.FINER)) { + focusLog.finer("SNFH for {0} in {1}", + String.valueOf(descendant), String.valueOf(heavyweight)); } - if (focusLog.isLoggable(Level.FINEST)) { - focusLog.log(Level.FINEST, "0. Current focus owner {0}", - String.valueOf(currentFocusOwner)); - focusLog.log(Level.FINEST, "0. Native focus owner {0}", - String.valueOf(nativeFocusOwner)); - focusLog.log(Level.FINEST, "0. Native focused window {0}", - String.valueOf(nativeFocusedWindow)); + if (focusLog.isLoggable(PlatformLogger.FINEST)) { + focusLog.finest("0. Current focus owner {0}", + String.valueOf(currentFocusOwner)); + focusLog.finest("0. Native focus owner {0}", + String.valueOf(nativeFocusOwner)); + focusLog.finest("0. Native focused window {0}", + String.valueOf(nativeFocusedWindow)); } synchronized (heavyweightRequests) { HeavyweightFocusRequest hwFocusRequest = getLastHWRequest(); - if (focusLog.isLoggable(Level.FINEST)) { - focusLog.log(Level.FINEST, "Request {0}", String.valueOf(hwFocusRequest)); + if (focusLog.isLoggable(PlatformLogger.FINEST)) { + focusLog.finest("Request {0}", String.valueOf(hwFocusRequest)); } if (hwFocusRequest == null && heavyweight == nativeFocusOwner) { if (descendant == currentFocusOwner) { // Redundant request. - if (focusLog.isLoggable(Level.FINEST)) - focusLog.log(Level.FINEST, "1. SNFH_FAILURE for {0}", - String.valueOf(descendant)); + if (focusLog.isLoggable(PlatformLogger.FINEST)) + focusLog.finest("1. SNFH_FAILURE for {0}", + String.valueOf(descendant)); return SNFH_FAILURE; } @@ -2417,8 +2416,8 @@ public abstract class KeyboardFocusManager // SunToolkit.postPriorityEvent(newFocusOwnerEvent); SunToolkit.postEvent(descendant.appContext, newFocusOwnerEvent); - if (focusLog.isLoggable(Level.FINEST)) - focusLog.log(Level.FINEST, "2. SNFH_HANDLED for {0}", String.valueOf(descendant)); + if (focusLog.isLoggable(PlatformLogger.FINEST)) + focusLog.finest("2. SNFH_HANDLED for {0}", String.valueOf(descendant)); return SNFH_SUCCESS_HANDLED; } else if (hwFocusRequest != null && hwFocusRequest.heavyweight == heavyweight) { @@ -2431,7 +2430,7 @@ public abstract class KeyboardFocusManager manager.enqueueKeyEvents(time, descendant); } - if (focusLog.isLoggable(Level.FINEST)) + if (focusLog.isLoggable(PlatformLogger.FINEST)) focusLog.finest("3. SNFH_HANDLED for lightweight" + descendant + " in " + heavyweight); return SNFH_SUCCESS_HANDLED; @@ -2454,7 +2453,7 @@ public abstract class KeyboardFocusManager (hwFocusRequest != null) ? hwFocusRequest.heavyweight : nativeFocusedWindow)) { - if (focusLog.isLoggable(Level.FINEST)) + if (focusLog.isLoggable(PlatformLogger.FINEST)) focusLog.finest("4. SNFH_FAILURE for " + descendant); return SNFH_FAILURE; } @@ -2464,7 +2463,7 @@ public abstract class KeyboardFocusManager heavyweightRequests.add (new HeavyweightFocusRequest(heavyweight, descendant, temporary, cause)); - if (focusLog.isLoggable(Level.FINEST)) + if (focusLog.isLoggable(PlatformLogger.FINEST)) focusLog.finest("5. SNFH_PROCEED for " + descendant); return SNFH_SUCCESS_PROCEED; } @@ -2855,14 +2854,14 @@ public abstract class KeyboardFocusManager } KeyboardFocusManager manager = getCurrentKeyboardFocusManager(); - if (focusLog.isLoggable(Level.FINER)) { + if (focusLog.isLoggable(PlatformLogger.FINER)) { if (event instanceof FocusEvent || event instanceof WindowEvent) { - focusLog.log(Level.FINER, ">>> {0}", new Object[] {String.valueOf(event)}); + focusLog.finer(">>> {0}", String.valueOf(event)); } - if (focusLog.isLoggable(Level.FINER) && event instanceof KeyEvent) { - focusLog.log(Level.FINER, " focus owner is {0}", - new Object[] {String.valueOf(manager.getGlobalFocusOwner())}); - focusLog.log(Level.FINER, ">>> {0}", new Object[] {String.valueOf(event)}); + if (focusLog.isLoggable(PlatformLogger.FINER) && event instanceof KeyEvent) { + focusLog.finer(" focus owner is {0}", + String.valueOf(manager.getGlobalFocusOwner())); + focusLog.finer(">>> {0}", String.valueOf(event)); } } @@ -2946,9 +2945,9 @@ public abstract class KeyboardFocusManager } } static void removeLastFocusRequest(Component heavyweight) { - if (log.isLoggable(Level.FINE)) { + if (log.isLoggable(PlatformLogger.FINE)) { if (heavyweight == null) { - log.log(Level.FINE, "Assertion (heavyweight != null) failed"); + log.fine("Assertion (heavyweight != null) failed"); } } From f11ee4ea15150b2127d4bfa941c554cacaf5e249 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Wed, 9 Dec 2009 14:02:48 +0300 Subject: [PATCH 55/56] 6900622: Security warning icon is not getting displayed properly for tooltip Pass a correct value for the hWndInsertAfter argument to the ::SetWindowPos() function Reviewed-by: art, dcherepanov --- jdk/src/windows/native/sun/windows/awt_Window.cpp | 10 +++++++--- jdk/src/windows/native/sun/windows/awt_Window.h | 4 ++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/jdk/src/windows/native/sun/windows/awt_Window.cpp b/jdk/src/windows/native/sun/windows/awt_Window.cpp index 1819115859b..c6ff055877e 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.cpp +++ b/jdk/src/windows/native/sun/windows/awt_Window.cpp @@ -220,6 +220,7 @@ AwtWindow::AwtWindow() { ::InitializeCriticalSection(&contentBitmapCS); m_windowType = Type::NORMAL; + m_alwaysOnTop = false; } AwtWindow::~AwtWindow() @@ -352,10 +353,10 @@ void AwtWindow::RepositionSecurityWarning(JNIEnv *env) RECT rect; CalculateWarningWindowBounds(env, &rect); - ::SetWindowPos(warningWindow, HWND_NOTOPMOST, + ::SetWindowPos(warningWindow, IsAlwaysOnTop() ? HWND_TOPMOST : GetHWnd(), rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, - SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOZORDER | + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER ); } @@ -831,7 +832,9 @@ void AwtWindow::StartSecurityAnimation(AnimationKind kind) securityAnimationTimerElapse, NULL); if (securityAnimationKind == akShow) { - ::SetWindowPos(warningWindow, HWND_NOTOPMOST, 0, 0, 0, 0, + ::SetWindowPos(warningWindow, + IsAlwaysOnTop() ? HWND_TOPMOST : GetHWnd(), + 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW | SWP_NOOWNERZORDER); @@ -2270,6 +2273,7 @@ void AwtWindow::_SetAlwaysOnTop(void *param) if (::IsWindow(w->GetHWnd())) { w->SendMessage(WM_AWT_SETALWAYSONTOP, (WPARAM)value, (LPARAM)w); + w->m_alwaysOnTop = (bool)value; } ret: env->DeleteGlobalRef(self); diff --git a/jdk/src/windows/native/sun/windows/awt_Window.h b/jdk/src/windows/native/sun/windows/awt_Window.h index fa611b481c7..32be9d0d96b 100644 --- a/jdk/src/windows/native/sun/windows/awt_Window.h +++ b/jdk/src/windows/native/sun/windows/awt_Window.h @@ -383,6 +383,10 @@ private: // Tweak the style according to the type of the window void TweakStyle(DWORD & style, DWORD & exStyle); + // Set in _SetAlwaysOnTop() + bool m_alwaysOnTop; +public: + inline bool IsAlwaysOnTop() { return m_alwaysOnTop; } }; #endif /* AWT_WINDOW_H */ From 9fa825078162dcf3b5828f3aace971d0120ecfdf Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Wed, 9 Dec 2009 14:33:55 +0300 Subject: [PATCH 56/56] 6903893: Fix failed for CR 6834576: RemoveChild/ test fail with deadlock on rhel and sles Reviewed-by: dcherepanov, art --- jdk/src/solaris/classes/sun/awt/X11/XToolkit.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java index fb6f1180c28..8676c6affb9 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -1449,7 +1449,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable { * (which is assigned to the virtual pointer) reports the maximum * capabilities of the mouse pointer (i.e. 32 physical buttons). */ - private native synchronized int getNumberOfButtonsImpl(); + private native int getNumberOfButtonsImpl(); @Override public int getNumberOfButtons(){