From 9555cf3b507c630560b6d5fb11238c986eff0242 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 9 Nov 2016 10:36:32 -0800 Subject: [PATCH 001/402] 8164934: Optional.map() javadoc code example Reviewed-by: forax, chegar --- .../share/classes/java/util/Optional.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/Optional.java b/jdk/src/java.base/share/classes/java/util/Optional.java index 28700a836f2..94f3c17511a 100644 --- a/jdk/src/java.base/share/classes/java/util/Optional.java +++ b/jdk/src/java.base/share/classes/java/util/Optional.java @@ -214,20 +214,20 @@ public final class Optional { * @apiNote * This method supports post-processing on {@code Optional} values, without * the need to explicitly check for a return status. For example, the - * following code traverses a stream of file names, selects one that has not - * yet been processed, and then opens that file, returning an - * {@code Optional}: + * following code traverses a stream of URIs, selects one that has not + * yet been processed, and creates a path from that URI, returning + * an {@code Optional}: * *
{@code
-     *     Optional fis =
-     *         names.stream().filter(name -> !isProcessedYet(name))
+     *     Optional p =
+     *         uris.stream().filter(uri -> !isProcessedYet(uri))
      *                       .findFirst()
-     *                       .map(name -> new FileInputStream(name));
+     *                       .map(Paths::get);
      * }
* - * Here, {@code findFirst} returns an {@code Optional}, and then - * {@code map} returns an {@code Optional} for the desired - * file if one exists. + * Here, {@code findFirst} returns an {@code Optional}, and then + * {@code map} returns an {@code Optional} for the desired + * URI if one exists. * * @param mapper the mapping function to apply to a value, if present * @param The type of the value returned from the mapping function From 1c628411dff99daf8f11fd9480b9a1bc5ea1654a Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Thu, 10 Nov 2016 08:59:34 +0000 Subject: [PATCH 002/402] 8169362: Interop automated testing with Chrome Reviewed-by: wetmore, jnimeh, asmotrak --- .../ssl/interop/ClientHelloChromeInterOp.java | 75 +++ .../net/ssl/interop/ClientHelloInterOp.java | 432 ++++++++++++++++++ 2 files changed, 507 insertions(+) create mode 100644 jdk/test/javax/net/ssl/interop/ClientHelloChromeInterOp.java create mode 100644 jdk/test/javax/net/ssl/interop/ClientHelloInterOp.java diff --git a/jdk/test/javax/net/ssl/interop/ClientHelloChromeInterOp.java b/jdk/test/javax/net/ssl/interop/ClientHelloChromeInterOp.java new file mode 100644 index 00000000000..5921a971c77 --- /dev/null +++ b/jdk/test/javax/net/ssl/interop/ClientHelloChromeInterOp.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// SunJSSE does not support dynamic system properties, no way to re-use +// system properties in samevm/agentvm mode. +// + +/* + * @test + * @bug 8169362 + * @summary Interop automated testing with Chrome + * @modules java.base/sun.security.util + * @run main/othervm ClientHelloChromeInterOp + */ + +import java.util.Base64; +import sun.security.util.HexDumpEncoder; + +public class ClientHelloChromeInterOp extends ClientHelloInterOp { + // The ClientHello message. + // + // Captured from Chrome browser (version 54.0.2840.87 m (64-bit)) on + // Windows 10. + private final static String ClientHelloMsg = + "FgMBAL4BAAC6AwOWBEueOntnurZ+WAW0D9Qn2HpdzXLu0MgDjsD9e5JU6AAAIsA\n" + + "rwC/ALMAwzKnMqMwUzBPACcATwArAFACcAJ0ALwA1AAoBAABv/wEAAQAAAAATAB\n" + + "EAAA53d3cub3JhY2xlLmNvbQAXAAAAIwAAAA0AEgAQBgEGAwUBBQMEAQQDAgECA\n" + + "wAFAAUBAAAAAAASAAAAEAAOAAwCaDIIaHR0cC8xLjF1UAAAAAsAAgEAAAoACAAG\n" + + "AB0AFwAY"; + + /* + * Main entry point for this test. + */ + public static void main(String args[]) throws Exception { + (new ClientHelloChromeInterOp()).run(); + } + + @Override + protected byte[] createClientHelloMessage() { + byte[] bytes = Base64.getMimeDecoder().decode(ClientHelloMsg); + + // Dump the hex codes of the ClientHello message so that developers + // can easily check whether the message is captured correct or not. + HexDumpEncoder dump = new HexDumpEncoder(); + System.out.println("The ClientHello message used"); + try { + dump.encodeBuffer(bytes, System.out); + } catch (Exception e) { + // ignore + } + + return bytes; + } +} diff --git a/jdk/test/javax/net/ssl/interop/ClientHelloInterOp.java b/jdk/test/javax/net/ssl/interop/ClientHelloInterOp.java new file mode 100644 index 00000000000..c6bf74bd533 --- /dev/null +++ b/jdk/test/javax/net/ssl/interop/ClientHelloInterOp.java @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.net.ssl.*; +import javax.net.ssl.SSLEngineResult.*; +import java.io.*; +import java.nio.*; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.KeyFactory; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.spec.*; +import java.util.Base64; + +public abstract class ClientHelloInterOp { + + /* + * Certificates and keys used in the test. + */ + // Trusted certificates. + private final static String[] trustedCertStrs = { + // SHA256withECDSA, curve prime256v1 + // Validity + // Not Before: Nov 9 03:24:05 2016 GMT + // Not After : Oct 20 03:24:05 2037 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIICHDCCAcGgAwIBAgIJAM83C/MVp9F5MAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTAeFw0xNjExMDkwMzI0MDVaFw0zNzEwMjAwMzI0MDVaMDsxCzAJBgNVBAYTAlVT\n" + + "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZTBZ\n" + + "MBMGByqGSM49AgEGCCqGSM49AwEHA0IABGeQXwyeNyU4UAATfwUbMO5zaREI21Wh\n" + + "bds6WDu+PmfK8SWsTgsgpYxBRui+fZtYqSmbdjkurvAQ3j2fvN++BtWjga0wgaow\n" + + "HQYDVR0OBBYEFDF/OeJ82qBSRkAm1rdZUPbWfDzyMGsGA1UdIwRkMGKAFDF/OeJ8\n" + + "2qBSRkAm1rdZUPbWfDzyoT+kPTA7MQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2\n" + + "YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2WCCQDPNwvzFafReTAPBgNV\n" + + "HRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjAKBggqhkjOPQQDAgNJADBGAiEAlHQY\n" + + "QFPlODOsjLVQYSxgeSUvYzMp0vP8naeVB9bfFG8CIQCFfrKZvhq9z3bOtlYKxs2a\n" + + "EWUjUZ82a1JTqkP+lgHY5A==\n" + + "-----END CERTIFICATE-----", + + // SHA256withRSA, 2048 bits + // Validity + // Not Before: Nov 9 03:24:16 2016 GMT + // Not After : Oct 20 03:24:16 2037 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIIDpzCCAo+gAwIBAgIJAJAYpR2aIlA1MA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + + "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" + + "aXZjZTAeFw0xNjExMDkwMzI0MTZaFw0zNzEwMjAwMzI0MTZaMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL+F/FTPODYzsU0Pakfp\n" + + "lsh88YoQWZPjABhCU+HPsCTMYc8UBkaiduUzregwwVBW3D7kmec2K408krGQsxdy\n" + + "oKJA12GL/XX1YgzDEsyBRk/gvex5lPaBIZiJ5IZlUfjLuRDGxPjtRelBTpZ7SUet\n" + + "PJVZz6zV6hMPGO6kQzCtbzzET515EE0okIS40LkAmtWoOmVm3gRldomaZTrZ0V2L\n" + + "MMaJGzrXYqk0SX+PYul8v+2EEHeMuaXG/XpK5xsg9gZvzpKqFQcBOdENoJHB07go\n" + + "jCmRC328ALqr+bMyktKAuYfB+mhjmN2AU8TQx72WPpvNTXxFDYcwo+8254cCAVKB\n" + + "e98CAwEAAaOBrTCBqjAdBgNVHQ4EFgQUlJQlQTbi8YIyiNf+SqF7LtH+gicwawYD\n" + + "VR0jBGQwYoAUlJQlQTbi8YIyiNf+SqF7LtH+giehP6Q9MDsxCzAJBgNVBAYTAlVT\n" + + "MQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZjZYIJ\n" + + "AJAYpR2aIlA1MA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3\n" + + "DQEBCwUAA4IBAQAI0lTY0YAKQ2VdoIQ6dnqolphLVWdNGiC9drHEYSn7+hmAD2r2\n" + + "v1U/9m752TkcT74a65xKbEVuVtleD/w6i+QjALW2PYt6ivjOnnY0a9Y9a9UCa00j\n" + + "C9415sCw84Tp9VoKtuYqzhN87bBUeABOw5dsW3z32C2N/YhprkqeF/vdx4JxulPr\n" + + "PKze5BREXnKLA1ISoDioCPphvNMKrSpkAofb1rTCwtgt5V/WFls283L52ORmpRGO\n" + + "Ja88ztXOz00ZGu0RQLwlmpN7m8tNgA/5MPrldyYIwegP4RSkkJlF/8+hxvvqfJhK\n" + + "FFDa0HHQSJfR2b9628Iniw1UHOMMT6qx5EHr\n" + + "-----END CERTIFICATE-----" + }; + + // End entity certificate. + private final static String[] endEntityCertStrs = { + // SHA256withECDSA, curve prime256v1 + // Validity + // Not Before: Nov 9 03:24:05 2016 GMT + // Not After : Jul 27 03:24:05 2036 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIIB1DCCAXmgAwIBAgIJAKVa+4dIUjaLMAoGCCqGSM49BAMCMDsxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTAeFw0xNjExMDkwMzI0MDVaFw0zNjA3MjcwMzI0MDVaMFIxCzAJBgNVBAYTAlVT\n" + + "MQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZjZTEV\n" + + "MBMGA1UEAwwMSW50ZXJPcCBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\n" + + "h4vXNUJzULq4e7fAOvF0WiWU6cllOAMus1GqTFvcnRPOChl8suZsvksO0CpZqL3h\n" + + "jXmVX9dp1FV/rUBGLo1aG6NPME0wCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBSO8V5+\n" + + "bj0ik0T9BtJc4jLJt7m6wjAfBgNVHSMEGDAWgBQxfznifNqgUkZAJta3WVD21nw8\n" + + "8jAKBggqhkjOPQQDAgNJADBGAiEAk7MF+L9bFRwUsbPsBCbCqH9DMdzBQR+kFDNf\n" + + "lfn8Rs4CIQD9qWvBXd+EJqwraxiX6cftaFchn+T2HpvMboy+irMFow==\n" + + "-----END CERTIFICATE-----", + + // SHA256withRSA, 2048 bits + // Validity + // Not Before: Nov 9 03:24:16 2016 GMT + // Not After : Jul 27 03:24:16 2036 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIIDczCCAlugAwIBAgIJAPhM2oUKx0aJMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNV\n" + + "BAYTAlVTMQ0wCwYDVQQKEwRKYXZhMR0wGwYDVQQLExRTdW5KU1NFIFRlc3QgU2Vy\n" + + "aXZjZTAeFw0xNjExMDkwMzI0MTZaFw0zNjA3MjcwMzI0MTZaMFIxCzAJBgNVBAYT\n" + + "AlVTMQ0wCwYDVQQKDARKYXZhMR0wGwYDVQQLDBRTdW5KU1NFIFRlc3QgU2VyaXZj\n" + + "ZTEVMBMGA1UEAwwMSW50ZXJPcCBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" + + "MIIBCgKCAQEA36tJaXfJ2B/AFvES+tnueyQPSNABVu9nfMdU+NEPamJ+FH7cEF8Z\n" + + "1Spr1vlQgNzCpDUVrfnmT75rCapgz5ldA9+y+3hdfUyHjZBzzfx+6GHXLB4u6eU2\n" + + "NATa7vqSLNbcLcfZ7/QmkFqg4JRJbX4F42kKkRJrWdKZ8UoCYC8WXWvDaZ3nUs05\n" + + "XHe+mBJ8qMNPTbYST1jpzXPyH5CljlFGYi2mKJDTImDhwht7mu2+zvwvbJ81Gj2X\n" + + "JUSTSf9fu0zxFcCk6RmJPw9nSVqePVlOwtNNBodfKN+k4yr+gOz1v8NmMtmEtklV\n" + + "Sulr/J4QxI+E2Zar/C+4XjxkvstIS+PNKQIDAQABo2MwYTALBgNVHQ8EBAMCA+gw\n" + + "HQYDVR0OBBYEFHt19CItAz0VOF0WKGWwaT4DtEsSMB8GA1UdIwQYMBaAFJSUJUE2\n" + + "4vGCMojX/kqhey7R/oInMBIGA1UdEQEB/wQIMAaHBH8AAAEwDQYJKoZIhvcNAQEL\n" + + "BQADggEBACKYZWvo9B9IEpCCdBba2sNo4X1NI/VEY3fyUx1lkw+Kna+1d2Ab+RCZ\n" + + "cf3Y85fcwv03hNE///wNBp+Nde4NQRDK/oiQARzWwWslfinm5d83eQwzC3cpSzt+\n" + + "7ts6M5UlOblGsLXZI7THWO1tkgoEra9p+zezxLMmf/2MpNyZMZlVoJPM2YGxU9cN\n" + + "ws0AyeY1gpBEdT21vjsBPdxxj6qklXVMnzS3zF8YwXyOndDYQWdjmFEknRK/qmQ2\n" + + "gkLHrzpSpyCziecna5mGuDRdCU2dpsWiq1npEPXTq+PQGwWYcoaFTtXF8DDqhfPC\n" + + "4Abe8gPm6MfzerdmS3RFTj9b/DIIENM=\n" + + "-----END CERTIFICATE-----" + }; + + // Private key in the format of PKCS#8. + private final static String[] endEntityPrivateKeys = { + // + // EC private key related to cert endEntityCertStrs[0]. + // + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgA3pmS+OrIjGyUv2F\n" + + "K/PkyayJIePM2RTFYxNoQqmJGnihRANCAASHi9c1QnNQurh7t8A68XRaJZTpyWU4\n" + + "Ay6zUapMW9ydE84KGXyy5my+Sw7QKlmoveGNeZVf12nUVX+tQEYujVob", + + // + // RSA private key related to cert endEntityCertStrs[1]. + // + "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDfq0lpd8nYH8AW\n" + + "8RL62e57JA9I0AFW72d8x1T40Q9qYn4UftwQXxnVKmvW+VCA3MKkNRWt+eZPvmsJ\n" + + "qmDPmV0D37L7eF19TIeNkHPN/H7oYdcsHi7p5TY0BNru+pIs1twtx9nv9CaQWqDg\n" + + "lEltfgXjaQqREmtZ0pnxSgJgLxZda8NpnedSzTlcd76YEnyow09NthJPWOnNc/If\n" + + "kKWOUUZiLaYokNMiYOHCG3ua7b7O/C9snzUaPZclRJNJ/1+7TPEVwKTpGYk/D2dJ\n" + + "Wp49WU7C000Gh18o36TjKv6A7PW/w2Yy2YS2SVVK6Wv8nhDEj4TZlqv8L7hePGS+\n" + + "y0hL480pAgMBAAECggEBAJyP1zk+IkloIBtu7+wrdCU6HoDHKMjjlzrehHoOTI4Z\n" + + "F0vdaMkE6J4vrYCyz0kEPjKW/e/jxvT2wxHm8xEdtuApS61+mWJFmXTcMlNzdJnR\n" + + "Mr6s+gW67fAHngA94OgGFeTtyX2PFxdgeM/6vFMqLZD7S+w0SnR7WEpvla4iB7On\n" + + "lXqhJKVQeVc+IpByg/S4MmJb91jck73GltCaCL/b6BTrsz+zc/AY5tb8JInxjMZ9\n" + + "jmjmA+s6l7tnBrFQfJHlF9a374lxCOtZTxyxVJjD7tQcGpsUpSHXZGdpDcT34qYT\n" + + "UGh0yp2Mc/1PfWni5gS/6UGLrYmT57RRCn5YJBJTEkkCgYEA/XPCNehFaOMSxOZh\n" + + "OGBVhQ+eRAmdpJfMhSUsDdEdQLZyWGmZsMTHjZZrwevBX/D0dxQYDv/sAl0GZomJ\n" + + "d6iRCHlscycwx5Q0U/EpacsgRlYHz1nMRzXqS3Ry+8O8qQlliqCLUM7SfVgzdI5/\n" + + "ll9JMrng9NnRl8ccjEdOGK8g/MMCgYEA4eriKMfRslGY4uOQoTPbuEJSMMwQ2X4k\n" + + "lPj1p+xSQfU9QBaWJake67oBj3vpCxqN7/VkvCIeC6LCjhLpWHCn4EkdGiqkEdWz\n" + + "m5CHzpzVIgznzWnbt0rCVL2KdL+ihgY8KPDdsZ6tZrABHuYhsWkAu10wyvuQYM88\n" + + "3u6yOIQn36MCgYEAk5qR1UEzAxWTPbaJkgKQa5Cf9DHBbDS3eCcg098f8SsPxquh\n" + + "RRAkwzGCCgqZsJ0sUhkStdGXifzRGHAq7dPuuwe0ABAn2WNXYjeFjcYtQqkhnUFH\n" + + "tYURsOXdfQAOZEdDqos691GrxjHSraO7bECL6Y3VE+Oyq3jbCFsSgU+kn28CgYBT\n" + + "mrXZO6FJqVK33FlAns1YEgsSjeJKapklHEDkxNroF9Zz6ifkhgKwX6SGMefbORd/\n" + + "zsNZsBKIYdI3+52pIf+uS8BeV5tiEkCmeEUZ3AYv1LDP3rX1zc++xmn/rI97o8EN\n" + + "sZ2JRtyK3OV9RtL/MYmYzPLqm1Ah02+GXLVNnvKWmwKBgE8Ble8CzrXYuuPdGxXz\n" + + "BZU6HnXQrmTUcgeze0tj8SDHzCfsGsaG6pHrVNkT7CKsRuCHTZLM0kXmUijLFKuP\n" + + "5xyE257z4IbbEbs+tcbB3p28n4/47MzZkSR3kt8+FrsEMZq5oOHbFTGzgp9dhZCC\n" + + "dKUqlw5BPHdbxoWB/JpSHGCV" + }; + + // Private key names of endEntityPrivateKeys. + private final static String[] endEntityPrivateKeyNames = { + "EC", + "RSA" + }; + + /* + * Run the test case. + */ + public void run() throws Exception { + SSLEngine serverEngine = createServerEngine(); + + // + // Create and size the buffers appropriately. + // + SSLSession session = serverEngine.getSession(); + ByteBuffer serverAppInbound = + ByteBuffer.allocate(session.getApplicationBufferSize()); + ByteBuffer clientHello = + ByteBuffer.allocate(session.getPacketBufferSize()); + + // + // Generate a ClientHello message, and check if the server + // engine can read it or not. + // + clientHello.put(createClientHelloMessage()); + clientHello.flip(); + + SSLEngineResult serverResult = + serverEngine.unwrap(clientHello, serverAppInbound); + log("Server unwrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + + // + // Generate server responses to the ClientHello request. + // + ByteBuffer clientNetInbound = + ByteBuffer.allocate(session.getPacketBufferSize()); + ByteBuffer clientAppInbound = + ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); + + serverResult = serverEngine.wrap(clientAppInbound, clientNetInbound); + log("Server wrap: ", serverResult); + runDelegatedTasks(serverResult, serverEngine); + } + + /* + * Create a ClientHello message. + */ + abstract protected byte[] createClientHelloMessage(); + + /* + * Create an instance of SSLContext for client use. + */ + protected SSLContext createClientSSLContext() throws Exception { + return createSSLContext(trustedCertStrs, null, null, null); + } + + /* + * Create an instance of SSLContext for server use. + */ + protected SSLContext createServerSSLContext() throws Exception { + return createSSLContext(null, + endEntityCertStrs, endEntityPrivateKeys, + endEntityPrivateKeyNames); + } + + /* + * Create an instance of SSLContext with the specified trust/key materials. + */ + protected SSLContext createSSLContext( + String[] trustedMaterials, + String[] keyMaterialCerts, + String[] keyMaterialKeys, + String[] keyMaterialKeyAlgs) throws Exception { + + KeyStore ts = null; // trust store + KeyStore ks = null; // key store + char passphrase[] = "passphrase".toCharArray(); + + // Generate certificate from cert string. + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + // Import the trused certs. + ByteArrayInputStream is; + if (trustedMaterials != null && trustedMaterials.length != 0) { + ts = KeyStore.getInstance("JKS"); + ts.load(null, null); + + Certificate[] trustedCert = + new Certificate[trustedMaterials.length]; + for (int i = 0; i < trustedMaterials.length; i++) { + String trustedCertStr = trustedMaterials[i]; + + is = new ByteArrayInputStream(trustedCertStr.getBytes()); + try { + trustedCert[i] = cf.generateCertificate(is); + } finally { + is.close(); + } + + ts.setCertificateEntry("trusted-cert-" + i, trustedCert[i]); + } + } + + // Import the key materials. + // + // Note that certification pathes bigger than one are not supported yet. + boolean hasKeyMaterials = + (keyMaterialCerts != null) && (keyMaterialCerts.length != 0) && + (keyMaterialKeys != null) && (keyMaterialKeys.length != 0) && + (keyMaterialKeyAlgs != null) && (keyMaterialKeyAlgs.length != 0) && + (keyMaterialCerts.length == keyMaterialKeys.length) && + (keyMaterialCerts.length == keyMaterialKeyAlgs.length); + if (hasKeyMaterials) { + ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + + for (int i = 0; i < keyMaterialCerts.length; i++) { + String keyCertStr = keyMaterialCerts[i]; + + // generate the private key. + PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( + Base64.getMimeDecoder().decode(keyMaterialKeys[i])); + KeyFactory kf = + KeyFactory.getInstance(keyMaterialKeyAlgs[i]); + PrivateKey priKey = kf.generatePrivate(priKeySpec); + + // generate certificate chain + is = new ByteArrayInputStream(keyCertStr.getBytes()); + Certificate keyCert = null; + try { + keyCert = cf.generateCertificate(is); + } finally { + is.close(); + } + + Certificate[] chain = new Certificate[] { keyCert }; + + // import the key entry. + ks.setKeyEntry("cert-" + i, priKey, passphrase, chain); + } + } + + // Create an SSLContext object. + TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); + tmf.init(ts); + + SSLContext context = SSLContext.getInstance("TLS"); + if (hasKeyMaterials && ks != null) { + KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); + kmf.init(ks, passphrase); + + context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + } else { + context.init(null, tmf.getTrustManagers(), null); + } + + return context; + } + + /* + * Create an instance of SSLEngine in client mode. + */ + protected SSLEngine createClientEngine() throws Exception { + return createClientEngine(createClientSSLContext()); + } + + /* + * Create an instance of SSLEngine in client mode with the + * specified SSLContext object. + */ + protected SSLEngine createClientEngine( + SSLContext context) throws Exception { + + SSLEngine engine = context.createSSLEngine(); + engine.setUseClientMode(true); + + /* + * Customize the SSLEngine object. + */ + // blank + + return engine; + } + + /* + * Create an instance of SSLEngine in server mode. + */ + protected SSLEngine createServerEngine() throws Exception { + return createServerEngine(createServerSSLContext()); + } + + /* + * Create an instance of SSLEngine in server mode with the + * specified SSLContext object. + */ + protected SSLEngine createServerEngine( + SSLContext context) throws Exception { + + SSLEngine engine = context.createSSLEngine(); + engine.setUseClientMode(false); + + /* + * Customize the SSLEngine object. + */ + engine.setNeedClientAuth(false); + + return engine; + } + + /* + * Run the delagayed tasks if any. + * + * If the result indicates that we have outstanding tasks to do, + * go ahead and run them in this thread. + */ + protected static void runDelegatedTasks(SSLEngineResult result, + SSLEngine engine) throws Exception { + + if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { + Runnable runnable; + while ((runnable = engine.getDelegatedTask()) != null) { + log("\trunning delegated task..."); + runnable.run(); + } + HandshakeStatus hsStatus = engine.getHandshakeStatus(); + if (hsStatus == HandshakeStatus.NEED_TASK) { + throw new Exception( + "handshake shouldn't need additional tasks"); + } + log("\tnew HandshakeStatus: " + hsStatus); + } + } + + /* + * Logging the specificated message and the SSLEngine operation result. + */ + protected static void log(String str, SSLEngineResult result) { + HandshakeStatus hsStatus = result.getHandshakeStatus(); + log(str + + result.getStatus() + "/" + hsStatus + ", consumed: " + + result.bytesConsumed() + "/produced: " + result.bytesProduced() + + " bytes"); + + if (hsStatus == HandshakeStatus.FINISHED) { + log("\t...ready for application data"); + } + } + + /* + * Logging the specificated message. + */ + protected static void log(String str) { + System.out.println(str); + } +} From ac33542985a7430a467f7d0433946c5e1d4a08d7 Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Wed, 9 Nov 2016 14:24:41 +0300 Subject: [PATCH 003/402] 8169196: [TESTBUG] Three tests from sun/net/www have undeclared dependencies Reviewed-by: dfuchs --- .../net/www/http/HttpClient/RetryPost.java | 25 +++++-- .../sun/net/www/http/HttpClient/RetryPost.sh | 68 ------------------- .../http/KeepAliveStream/InfiniteLoop.java | 11 ++- .../sun/net/www/protocol/http/NoNTLM.java | 25 +++++-- 4 files changed, 46 insertions(+), 83 deletions(-) delete mode 100644 jdk/test/sun/net/www/http/HttpClient/RetryPost.sh diff --git a/jdk/test/sun/net/www/http/HttpClient/RetryPost.java b/jdk/test/sun/net/www/http/HttpClient/RetryPost.java index da7d868c3f2..1f2774d5a60 100644 --- a/jdk/test/sun/net/www/http/HttpClient/RetryPost.java +++ b/jdk/test/sun/net/www/http/HttpClient/RetryPost.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,10 +21,25 @@ * questions. */ -import java.net.*; -import java.util.*; -import java.io.*; -import com.sun.net.httpserver.*; +/* + * @test + * @bug 6427251 6382788 + * @modules jdk.httpserver + * @run main RetryPost + * @run main/othervm -Dsun.net.http.retryPost=false RetryPost noRetry + * @summary HttpURLConnection automatically retries non-idempotent method POST + */ + +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.SocketException; +import java.net.URL; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; diff --git a/jdk/test/sun/net/www/http/HttpClient/RetryPost.sh b/jdk/test/sun/net/www/http/HttpClient/RetryPost.sh deleted file mode 100644 index 218c1d4b717..00000000000 --- a/jdk/test/sun/net/www/http/HttpClient/RetryPost.sh +++ /dev/null @@ -1,68 +0,0 @@ -# -# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - - # @test - # @bug 6427251 6382788 - # @run shell/timeout=140 RetryPost.sh - # @summary HttpURLConnection automatically retries non-idempotent method POST - -OS=`uname -s` -case "$OS" in - SunOS | Linux | Darwin | AIX ) - PS=":" - FS="/" - ;; - CYGWIN* ) - PS=";" - FS="/" - ;; - Windows* ) - PS=";" - FS="\\" - ;; - * ) - echo "Unrecognized system!" - exit 1; - ;; -esac - -# compile -${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d . ${TESTSRC}${FS}RetryPost.java - -# run with no option specified. Should retry POST request. -${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} RetryPost -result=$? -if [ "$result" -ne "0" ]; then - exit 1 -fi - -# run with option specified. Should not retry POST request. -${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Dsun.net.http.retryPost=false RetryPost noRetry -result=$? -if [ "$result" -ne "0" ]; then - exit 1 -fi - -# no failures, exit. -exit 0 - diff --git a/jdk/test/sun/net/www/http/KeepAliveStream/InfiniteLoop.java b/jdk/test/sun/net/www/http/KeepAliveStream/InfiniteLoop.java index c25c7fe2723..b3f0ced39dc 100644 --- a/jdk/test/sun/net/www/http/KeepAliveStream/InfiniteLoop.java +++ b/jdk/test/sun/net/www/http/KeepAliveStream/InfiniteLoop.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,14 +24,19 @@ /* * @test * @bug 8004863 + * @modules jdk.httpserver * @summary Checks for proper close code in KeepAliveStream */ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import java.io.*; -import java.net.*; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.URL; import java.util.concurrent.Phaser; // Racey test, will not always fail, but if it does then we have a problem. diff --git a/jdk/test/sun/net/www/protocol/http/NoNTLM.java b/jdk/test/sun/net/www/protocol/http/NoNTLM.java index 788bb3d3de8..a0b74a36b30 100644 --- a/jdk/test/sun/net/www/protocol/http/NoNTLM.java +++ b/jdk/test/sun/net/www/protocol/http/NoNTLM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,11 +26,19 @@ * @summary Sanity check that NTLM will not be selected by the http protocol * handler when running on a profile that does not support NTLM * @modules java.base/sun.net.www + * java.base/sun.net.www.protocol.http * @run main/othervm NoNTLM */ -import java.net.*; -import java.io.*; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.Proxy; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URL; import sun.net.www.MessageHeader; public class NoNTLM { @@ -208,11 +216,14 @@ public class NoNTLM { } public static void main(String[] args) throws Exception { - // assume NTLM is not supported when Kerberos is not available try { - Class.forName("javax.security.auth.kerberos.KerberosPrincipal"); - System.out.println("Kerberos is present, assuming NTLM is supported too"); - return; + Class ntlmProxyClass = Class.forName("sun.net.www.protocol.http.NTLMAuthenticationProxy", true, NoNTLM.class.getClassLoader()); + Field ntlmSupportedField = ntlmProxyClass.getDeclaredField("supported"); + ntlmSupportedField.setAccessible(true); + if (ntlmSupportedField.getBoolean(null)) { + System.out.println("NTLM is supported. Nothing to do. Exiting."); + return; + } } catch (ClassNotFoundException okay) { } // setup Authenticator From e3e8bf9ebe3a124d86be3706a341a9e310964f99 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Thu, 10 Nov 2016 15:19:47 -0800 Subject: [PATCH 004/402] 8169001: Remove launcher's built-in ergonomics Reviewed-by: dholmes, erikj --- jdk/make/launcher/Launcher-jdk.compiler.gmk | 9 +- jdk/make/launcher/Launcher-jdk.javadoc.gmk | 3 +- jdk/make/launcher/Launcher-jdk.jdeps.gmk | 9 +- jdk/make/launcher/Launcher-jdk.jlink.gmk | 6 +- jdk/make/launcher/Launcher-jdk.jshell.gmk | 3 +- jdk/src/java.base/macosx/conf/x86_64/jvm.cfg | 2 +- .../macosx/native/libjli/java_md_macosx.c | 7 +- .../classes/sun/launcher/LauncherHelper.java | 27 +- .../launcher/resources/launcher.properties | 3 - .../java.base/share/native/launcher/defines.h | 10 +- .../java.base/share/native/launcher/main.c | 4 +- jdk/src/java.base/share/native/libjli/java.c | 79 +---- jdk/src/java.base/share/native/libjli/java.h | 9 - jdk/src/java.base/unix/conf/aarch64/jvm.cfg | 3 +- jdk/src/java.base/unix/conf/amd64/jvm.cfg | 3 +- jdk/src/java.base/unix/conf/i586/jvm.cfg | 4 +- jdk/src/java.base/unix/conf/ia64/jvm.cfg | 7 +- jdk/src/java.base/unix/conf/ppc64/jvm.cfg | 2 +- jdk/src/java.base/unix/conf/ppc64le/jvm.cfg | 2 +- jdk/src/java.base/unix/conf/s390x/jvm.cfg | 2 +- jdk/src/java.base/unix/conf/sparc/jvm.cfg | 6 +- jdk/src/java.base/unix/conf/sparcv9/jvm.cfg | 2 +- jdk/src/java.base/unix/conf/zero/jvm.cfg | 3 +- jdk/src/java.base/unix/native/libjli/ergo.c | 113 ------ jdk/src/java.base/unix/native/libjli/ergo.h | 42 --- .../java.base/unix/native/libjli/ergo_i586.c | 323 ------------------ jdk/src/java.base/windows/conf/amd64/jvm.cfg | 5 +- jdk/src/java.base/windows/conf/i586/jvm.cfg | 2 +- jdk/src/java.base/windows/conf/ia64/jvm.cfg | 6 +- .../java.base/windows/native/libjli/java_md.c | 5 - 30 files changed, 43 insertions(+), 658 deletions(-) delete mode 100644 jdk/src/java.base/unix/native/libjli/ergo.c delete mode 100644 jdk/src/java.base/unix/native/libjli/ergo.h delete mode 100644 jdk/src/java.base/unix/native/libjli/ergo_i586.c diff --git a/jdk/make/launcher/Launcher-jdk.compiler.gmk b/jdk/make/launcher/Launcher-jdk.compiler.gmk index 5a1637d1dc0..bf41ea83391 100644 --- a/jdk/make/launcher/Launcher-jdk.compiler.gmk +++ b/jdk/make/launcher/Launcher-jdk.compiler.gmk @@ -28,14 +28,12 @@ include LauncherCommon.gmk $(eval $(call SetupBuildLauncher, javac, \ MAIN_CLASS := com.sun.tools.javac.Main, \ JAVA_ARGS := --add-modules ALL-DEFAULT, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) $(eval $(call SetupBuildLauncher, javah, \ MAIN_CLASS := com.sun.tools.javah.Main, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) $(eval $(call SetupBuildLauncher, serialver, \ @@ -48,8 +46,7 @@ ifeq ($(ENABLE_SJAVAC), yes) # into any real images $(eval $(call SetupBuildLauncher, sjavac, \ MAIN_CLASS := com.sun.tools.sjavac.Main, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ OUTPUT_DIR := $(JDK_OUTPUTDIR)/bin, \ )) endif diff --git a/jdk/make/launcher/Launcher-jdk.javadoc.gmk b/jdk/make/launcher/Launcher-jdk.javadoc.gmk index 534a9d97341..889028a2b17 100644 --- a/jdk/make/launcher/Launcher-jdk.javadoc.gmk +++ b/jdk/make/launcher/Launcher-jdk.javadoc.gmk @@ -28,6 +28,5 @@ include LauncherCommon.gmk $(eval $(call SetupBuildLauncher, javadoc, \ MAIN_CLASS := jdk.javadoc.internal.tool.Main, \ JAVA_ARGS := --add-modules ALL-DEFAULT, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) diff --git a/jdk/make/launcher/Launcher-jdk.jdeps.gmk b/jdk/make/launcher/Launcher-jdk.jdeps.gmk index db29ecd88da..217523c48cc 100644 --- a/jdk/make/launcher/Launcher-jdk.jdeps.gmk +++ b/jdk/make/launcher/Launcher-jdk.jdeps.gmk @@ -27,18 +27,15 @@ include LauncherCommon.gmk $(eval $(call SetupBuildLauncher, javap, \ MAIN_CLASS := com.sun.tools.javap.Main, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) $(eval $(call SetupBuildLauncher, jdeps, \ MAIN_CLASS := com.sun.tools.jdeps.Main, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) $(eval $(call SetupBuildLauncher, jdeprscan, \ MAIN_CLASS := com.sun.tools.jdeprscan.Main, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) diff --git a/jdk/make/launcher/Launcher-jdk.jlink.gmk b/jdk/make/launcher/Launcher-jdk.jlink.gmk index 92cb61e5572..df2173996d7 100644 --- a/jdk/make/launcher/Launcher-jdk.jlink.gmk +++ b/jdk/make/launcher/Launcher-jdk.jlink.gmk @@ -34,13 +34,11 @@ $(eval $(call SetupBuildLauncher, jlink,\ MAIN_CLASS := jdk.tools.jlink.internal.Main, \ JAVA_ARGS := --add-modules ALL-DEFAULT, \ CFLAGS := -DENABLE_ARG_FILES \ - -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + -DEXPAND_CLASSPATH_WILDCARDS, \ )) $(eval $(call SetupBuildLauncher, jmod,\ MAIN_CLASS := jdk.tools.jmod.Main, \ CFLAGS := -DENABLE_ARG_FILES \ - -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + -DEXPAND_CLASSPATH_WILDCARDS, \ )) diff --git a/jdk/make/launcher/Launcher-jdk.jshell.gmk b/jdk/make/launcher/Launcher-jdk.jshell.gmk index b03f044c9c3..e80876f645c 100644 --- a/jdk/make/launcher/Launcher-jdk.jshell.gmk +++ b/jdk/make/launcher/Launcher-jdk.jshell.gmk @@ -27,6 +27,5 @@ include LauncherCommon.gmk $(eval $(call SetupBuildLauncher, jshell, \ MAIN_CLASS := jdk.internal.jshell.tool.JShellTool, \ - CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \ - -DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \ + CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS, \ )) diff --git a/jdk/src/java.base/macosx/conf/x86_64/jvm.cfg b/jdk/src/java.base/macosx/conf/x86_64/jvm.cfg index 2502d2bacc3..d5acf55cf02 100644 --- a/jdk/src/java.base/macosx/conf/x86_64/jvm.cfg +++ b/jdk/src/java.base/macosx/conf/x86_64/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c index 8205f12f5d4..c6c36594a9d 100644 --- a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c +++ b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -922,11 +922,6 @@ void SetJavaLauncherPlatformProps() { /* Linux only */ } -jboolean -ServerClassMachine(void) { - return JNI_TRUE; -} - static JavaVM* jvmInstance = NULL; static jboolean sameThread = JNI_FALSE; /* start VM in current thread */ diff --git a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java index f19ed371e52..45e781b9b4a 100644 --- a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java +++ b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -139,8 +139,7 @@ public final class LauncherHelper { * line entirely. */ static void showSettings(boolean printToStderr, String optionFlag, - long initialHeapSize, long maxHeapSize, long stackSize, - boolean isServer) { + long initialHeapSize, long maxHeapSize, long stackSize) { initOutput(printToStderr); String opts[] = optionFlag.split(":"); @@ -149,8 +148,7 @@ public final class LauncherHelper { : "all"; switch (optStr) { case "vm": - printVmSettings(initialHeapSize, maxHeapSize, - stackSize, isServer); + printVmSettings(initialHeapSize, maxHeapSize, stackSize); break; case "properties": printProperties(); @@ -159,8 +157,7 @@ public final class LauncherHelper { printLocale(); break; default: - printVmSettings(initialHeapSize, maxHeapSize, stackSize, - isServer); + printVmSettings(initialHeapSize, maxHeapSize, stackSize); printProperties(); printLocale(); break; @@ -172,7 +169,7 @@ public final class LauncherHelper { */ private static void printVmSettings( long initialHeapSize, long maxHeapSize, - long stackSize, boolean isServer) { + long stackSize) { ostream.println(VM_SETTINGS); if (stackSize != 0L) { @@ -190,8 +187,6 @@ public final class LauncherHelper { ostream.println(INDENT + "Max. Heap Size (Estimated): " + SizePrefix.scaleValue(Runtime.getRuntime().maxMemory())); } - ostream.println(INDENT + "Ergonomics Machine Class: " - + ((isServer) ? "server" : "client")); ostream.println(INDENT + "Using VM: " + System.getProperty("java.vm.name")); ostream.println(); @@ -378,18 +373,6 @@ public final class LauncherHelper { vm1, vm2)); } - /** - * Appends the vm Ergo message to the header, already created. - * initHelpSystem must be called before using this method. - */ - static void appendVmErgoMessage(boolean isServerClass, String vm) { - outBuf = outBuf.append(getLocalizedMessage("java.launcher.ergo.message1", - vm)); - outBuf = (isServerClass) ? outBuf.append(",\n") - .append(getLocalizedMessage("java.launcher.ergo.message2")) - .append("\n\n") : outBuf.append(".\n\n"); - } - /** * Appends the last invariant part to the previously created messages, * and finishes up the printing to the desired output stream. diff --git a/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties b/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties index 3801d542fcc..f66bfa92461 100644 --- a/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties +++ b/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties @@ -35,9 +35,6 @@ java.launcher.opt.datamodel =\ -d{0}\t Deprecated, will be removed in a fut java.launcher.opt.vmselect =\ {0}\t to select the "{1}" VM\n java.launcher.opt.hotspot =\ {0}\t is a synonym for the "{1}" VM [deprecated]\n -java.launcher.ergo.message1 =\ The default VM is {0} -java.launcher.ergo.message2 =\ because you are running on a server-class machine.\n - # Translators please note do not translate the options themselves java.launcher.opt.footer =\ -cp \n\ \ -classpath \n\ diff --git a/jdk/src/java.base/share/native/launcher/defines.h b/jdk/src/java.base/share/native/launcher/defines.h index 1dd0cbe5b32..4470ae5d466 100644 --- a/jdk/src/java.base/share/native/launcher/defines.h +++ b/jdk/src/java.base/share/native/launcher/defines.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -70,14 +70,6 @@ static const jboolean const_cpwildcard = JNI_TRUE; static const jboolean const_cpwildcard = JNI_FALSE; #endif /* EXPAND_CLASSPATH_WILDCARDS */ -#if defined(NEVER_ACT_AS_SERVER_CLASS_MACHINE) -static const jint const_ergo_class = NEVER_SERVER_CLASS; -#elif defined(ALWAYS_ACT_AS_SERVER_CLASS_MACHINE) -static const jint const_ergo_class = ALWAYS_SERVER_CLASS; -#else -static const jint const_ergo_class = DEFAULT_POLICY; -#endif /* NEVER_ACT_AS_SERVER_CLASS_MACHINE */ - #ifdef ENABLE_ARG_FILES static const jboolean const_disable_argfile = JNI_FALSE; #else diff --git a/jdk/src/java.base/share/native/launcher/main.c b/jdk/src/java.base/share/native/launcher/main.c index 22298385114..a254a154426 100644 --- a/jdk/src/java.base/share/native/launcher/main.c +++ b/jdk/src/java.base/share/native/launcher/main.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -156,5 +156,5 @@ main(int argc, char **argv) (const_progname != NULL) ? const_progname : *margv, (const_launcher != NULL) ? const_launcher : *margv, HAS_JAVA_ARGS, - const_cpwildcard, const_javaw, const_ergo_class); + const_cpwildcard, const_javaw, 0); } diff --git a/jdk/src/java.base/share/native/libjli/java.c b/jdk/src/java.base/share/native/libjli/java.c index 70a7bf7a6d9..914dbb4a7b7 100644 --- a/jdk/src/java.base/share/native/libjli/java.c +++ b/jdk/src/java.base/share/native/libjli/java.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,7 +78,6 @@ static jboolean _is_java_args = JNI_FALSE; static jboolean _have_classpath = JNI_FALSE; static const char *_fVersion; static jboolean _wc_enabled = JNI_FALSE; -static jint _ergo_policy = DEFAULT_POLICY; /* * Entries for splash screen environment variables. @@ -218,7 +217,7 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */ jboolean javaargs, /* JAVA_ARGS */ jboolean cpwildcard, /* classpath wildcard*/ jboolean javaw, /* windows-only javaw */ - jint ergo /* ergonomics class policy */ + jint ergo /* unused */ ) { int mode = LM_UNKNOWN; @@ -236,7 +235,6 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */ _program_name = pname; _is_java_args = javaargs; _wc_enabled = cpwildcard; - _ergo_policy = ergo; InitLauncher(javaw); DumpState(); @@ -431,7 +429,7 @@ JavaMain(void * _args) LEAVE(); } - FreeKnownVMs(); /* after last possible PrintUsage() */ + FreeKnownVMs(); /* after last possible PrintUsage */ if (JLI_IsTraceLauncher()) { end = CounterGet(); @@ -669,11 +667,6 @@ CheckJvmType(int *pargc, char ***argv, jboolean speculative) { /* use the default VM type if not specified (no alias processing) */ if (jvmtype == NULL) { char* result = knownVMs[0].name+1; - /* Use a different VM type if we are on a server class machine? */ - if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && - (ServerClassMachine() == JNI_TRUE)) { - result = knownVMs[0].server_class+1; - } JLI_TraceLauncher("Default VM: %s\n", result); return result; } @@ -1777,15 +1770,14 @@ ShowSettings(JNIEnv *env, char *optString) jclass cls = GetLauncherHelperClass(env); NULL_CHECK(cls); NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls, - "showSettings", "(ZLjava/lang/String;JJJZ)V")); + "showSettings", "(ZLjava/lang/String;JJJ)V")); NULL_CHECK(joptString = (*env)->NewStringUTF(env, optString)); (*env)->CallStaticVoidMethod(env, cls, showSettingsID, USE_STDERR, joptString, (jlong)initialHeapSize, (jlong)maxHeapSize, - (jlong)threadStackSize, - ServerClassMachine()); + (jlong)threadStackSize); } /** @@ -1812,7 +1804,7 @@ ListModules(JNIEnv *env, char *optString) static void PrintUsage(JNIEnv* env, jboolean doXUsage) { - jmethodID initHelp, vmSelect, vmSynonym, vmErgo, printHelp, printXUsageMessage; + jmethodID initHelp, vmSelect, vmSynonym, printHelp, printXUsageMessage; jstring jprogname, vm1, vm2; int i; jclass cls = GetLauncherHelperClass(env); @@ -1831,8 +1823,6 @@ PrintUsage(JNIEnv* env, jboolean doXUsage) NULL_CHECK(vmSynonym = (*env)->GetStaticMethodID(env, cls, "appendVmSynonymMessage", "(Ljava/lang/String;Ljava/lang/String;)V")); - NULL_CHECK(vmErgo = (*env)->GetStaticMethodID(env, cls, - "appendVmErgoMessage", "(ZLjava/lang/String;)V")); NULL_CHECK(printHelp = (*env)->GetStaticMethodID(env, cls, "printHelpMessage", "(Z)V")); @@ -1845,13 +1835,6 @@ PrintUsage(JNIEnv* env, jboolean doXUsage) /* Assemble the other variant part of the usage */ - if ((knownVMs[0].flag == VM_KNOWN) || - (knownVMs[0].flag == VM_IF_SERVER_CLASS)) { - NULL_CHECK(vm1 = (*env)->NewStringUTF(env, knownVMs[0].name)); - NULL_CHECK(vm2 = (*env)->NewStringUTF(env, knownVMs[0].name+1)); - (*env)->CallStaticVoidMethod(env, cls, vmSelect, vm1, vm2); - CHECK_EXCEPTION_RETURN(); - } for (i=1; iNewStringUTF(env, knownVMs[i].name)); @@ -1869,20 +1852,6 @@ PrintUsage(JNIEnv* env, jboolean doXUsage) } } - /* The first known VM is the default */ - { - jboolean isServerClassMachine = ServerClassMachine(); - - const char* defaultVM = knownVMs[0].name+1; - if ((knownVMs[0].flag == VM_IF_SERVER_CLASS) && isServerClassMachine) { - defaultVM = knownVMs[0].server_class+1; - } - - NULL_CHECK(vm1 = (*env)->NewStringUTF(env, defaultVM)); - (*env)->CallStaticVoidMethod(env, cls, vmErgo, isServerClassMachine, vm1); - CHECK_EXCEPTION_RETURN(); - } - /* Complete the usage message and print to stderr*/ (*env)->CallStaticVoidMethod(env, cls, printHelp, USE_STDERR); } @@ -2011,19 +1980,7 @@ ReadKnownVMs(const char *jvmCfgName, jboolean speculative) } else if (!JLI_StrCCmp(tmpPtr, "ERROR")) { vmType = VM_ERROR; } else if (!JLI_StrCCmp(tmpPtr, "IF_SERVER_CLASS")) { - tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace); - if (*tmpPtr != 0) { - tmpPtr += JLI_StrSpn(tmpPtr, whiteSpace); - } - if (*tmpPtr == 0) { - JLI_ReportErrorMessage(CFG_WARN4, lineno, jvmCfgName); - } else { - /* Null terminate server class VM name */ - serverClassVMName = tmpPtr; - tmpPtr += JLI_StrCSpn(tmpPtr, whiteSpace); - *tmpPtr = 0; - vmType = VM_IF_SERVER_CLASS; - } + /* ignored */ } else { JLI_ReportErrorMessage(CFG_WARN5, lineno, &jvmCfgName[0]); vmType = VM_KNOWN; @@ -2043,11 +2000,6 @@ ReadKnownVMs(const char *jvmCfgName, jboolean speculative) JLI_TraceLauncher(" name: %s vmType: %s alias: %s\n", knownVMs[cnt].name, "VM_ALIASED_TO", knownVMs[cnt].alias); break; - case VM_IF_SERVER_CLASS: - knownVMs[cnt].server_class = JLI_StringDup(serverClassVMName); - JLI_TraceLauncher(" name: %s vmType: %s server_class: %s\n", - knownVMs[cnt].name, "VM_IF_SERVER_CLASS", knownVMs[cnt].server_class); - break; } cnt++; } @@ -2197,12 +2149,6 @@ GetLauncherName() return _launcher_name; } -jint -GetErgoPolicy() -{ - return _ergo_policy; -} - jboolean IsJavaArgs() { @@ -2267,17 +2213,6 @@ DumpState() printf("\tlauncher name:%s\n", GetLauncherName()); printf("\tjavaw:%s\n", (IsJavaw() == JNI_TRUE) ? "on" : "off"); printf("\tfullversion:%s\n", GetFullVersion()); - printf("\tergo_policy:"); - switch(GetErgoPolicy()) { - case NEVER_SERVER_CLASS: - printf("NEVER_ACT_AS_A_SERVER_CLASS_MACHINE\n"); - break; - case ALWAYS_SERVER_CLASS: - printf("ALWAYS_ACT_AS_A_SERVER_CLASS_MACHINE\n"); - break; - default: - printf("DEFAULT_ERGONOMICS_POLICY\n"); - } } /* diff --git a/jdk/src/java.base/share/native/libjli/java.h b/jdk/src/java.base/share/native/libjli/java.h index b5056de84a9..189bffc5285 100644 --- a/jdk/src/java.base/share/native/libjli/java.h +++ b/jdk/src/java.base/share/native/libjli/java.h @@ -166,19 +166,10 @@ char *CheckJvmType(int *argc, char ***argv, jboolean speculative); void AddOption(char *str, void *info); jboolean IsWhiteSpaceOption(const char* name); -enum ergo_policy { - DEFAULT_POLICY = 0, - NEVER_SERVER_CLASS, - ALWAYS_SERVER_CLASS -}; - const char* GetProgramName(); const char* GetFullVersion(); jboolean IsJavaArgs(); jboolean IsJavaw(); -jint GetErgoPolicy(); - -jboolean ServerClassMachine(); int ContinueInNewThread(InvocationFunctions* ifn, jlong threadStackSize, int argc, char** argv, diff --git a/jdk/src/java.base/unix/conf/aarch64/jvm.cfg b/jdk/src/java.base/unix/conf/aarch64/jvm.cfg index be6bb934250..deaf28d24b1 100644 --- a/jdk/src/java.base/unix/conf/aarch64/jvm.cfg +++ b/jdk/src/java.base/unix/conf/aarch64/jvm.cfg @@ -21,10 +21,9 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/amd64/jvm.cfg b/jdk/src/java.base/unix/conf/amd64/jvm.cfg index 17c4be37ac9..0642e728b7f 100644 --- a/jdk/src/java.base/unix/conf/amd64/jvm.cfg +++ b/jdk/src/java.base/unix/conf/amd64/jvm.cfg @@ -21,10 +21,9 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/i586/jvm.cfg b/jdk/src/java.base/unix/conf/i586/jvm.cfg index 4be4bb14b5f..58ae999105a 100644 --- a/jdk/src/java.base/unix/conf/i586/jvm.cfg +++ b/jdk/src/java.base/unix/conf/i586/jvm.cfg @@ -23,13 +23,13 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the # "-XXaltjvm=" option, but that too is unsupported # and may not be available in a future release. # --client IF_SERVER_CLASS -server -server KNOWN +-client KNOWN -minimal KNOWN diff --git a/jdk/src/java.base/unix/conf/ia64/jvm.cfg b/jdk/src/java.base/unix/conf/ia64/jvm.cfg index f9d3b5ece40..63cd6690d0a 100644 --- a/jdk/src/java.base/unix/conf/ia64/jvm.cfg +++ b/jdk/src/java.base/unix/conf/ia64/jvm.cfg @@ -1,6 +1,3 @@ -# -# -# # Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # @@ -24,11 +21,9 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# -# # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/ppc64/jvm.cfg b/jdk/src/java.base/unix/conf/ppc64/jvm.cfg index 6c024af438f..8fad8561dea 100644 --- a/jdk/src/java.base/unix/conf/ppc64/jvm.cfg +++ b/jdk/src/java.base/unix/conf/ppc64/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/ppc64le/jvm.cfg b/jdk/src/java.base/unix/conf/ppc64le/jvm.cfg index 6c024af438f..8fad8561dea 100644 --- a/jdk/src/java.base/unix/conf/ppc64le/jvm.cfg +++ b/jdk/src/java.base/unix/conf/ppc64le/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/s390x/jvm.cfg b/jdk/src/java.base/unix/conf/s390x/jvm.cfg index 2c147c9b97d..567857e64ba 100644 --- a/jdk/src/java.base/unix/conf/s390x/jvm.cfg +++ b/jdk/src/java.base/unix/conf/s390x/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/sparc/jvm.cfg b/jdk/src/java.base/unix/conf/sparc/jvm.cfg index 4be4bb14b5f..fae21410cd9 100644 --- a/jdk/src/java.base/unix/conf/sparc/jvm.cfg +++ b/jdk/src/java.base/unix/conf/sparc/jvm.cfg @@ -1,4 +1,4 @@ -# Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -23,13 +23,13 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the # "-XXaltjvm=" option, but that too is unsupported # and may not be available in a future release. # --client IF_SERVER_CLASS -server -server KNOWN +-client KNOWN -minimal KNOWN diff --git a/jdk/src/java.base/unix/conf/sparcv9/jvm.cfg b/jdk/src/java.base/unix/conf/sparcv9/jvm.cfg index 84f6d2706e8..0c4ef90bbd5 100644 --- a/jdk/src/java.base/unix/conf/sparcv9/jvm.cfg +++ b/jdk/src/java.base/unix/conf/sparcv9/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/conf/zero/jvm.cfg b/jdk/src/java.base/unix/conf/zero/jvm.cfg index 1b8d52792bc..38f1d8003da 100644 --- a/jdk/src/java.base/unix/conf/zero/jvm.cfg +++ b/jdk/src/java.base/unix/conf/zero/jvm.cfg @@ -21,10 +21,9 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/unix/native/libjli/ergo.c b/jdk/src/java.base/unix/native/libjli/ergo.c deleted file mode 100644 index 2047087e7c5..00000000000 --- a/jdk/src/java.base/unix/native/libjli/ergo.c +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* This file houses the common methods for VM ergonomics the platforms - * are split into ergo_sparc and ergo_x86, and they could be split more - * in the future if required. The following comments are not entirely - * true after bifurcation of the platform specific files. - */ - -/* - * The following methods (down to ServerClassMachine()) answer - * the question about whether a machine is a "server-class" - * machine. A server-class machine is loosely defined as one - * with 2 or more processors and 2 gigabytes or more physical - * memory. The definition of a processor is a physical package, - * not a hyperthreaded chip masquerading as a multi-processor. - * The definition of memory is also somewhat fuzzy, since x86 - * machines seem not to report all the memory in their DIMMs, we - * think because of memory mapping of graphics cards, etc. - * - * This code is somewhat more confused with #ifdef's than we'd - * like because this file is used by both Solaris and Linux - * platforms, and so needs to be parameterized for SPARC and - * i586 hardware. The other Linux platforms (amd64 and ia64) - * don't even ask this question, because they only come with - * server JVMs. - */ - -#include "ergo.h" - -/* Dispatch to the platform-specific definition of "server-class" */ -jboolean -ServerClassMachine(void) { - jboolean result; - switch(GetErgoPolicy()) { - case NEVER_SERVER_CLASS: - return JNI_FALSE; - case ALWAYS_SERVER_CLASS: - return JNI_TRUE; - default: - result = ServerClassMachineImpl(); - JLI_TraceLauncher("ServerClassMachine: returns default value of %s\n", - (result == JNI_TRUE ? "true" : "false")); - return result; - } -} - -#ifdef USE_GENERIC_ERGO -/* Ask the OS how many processors there are. */ -static unsigned long -physical_processors(void) { - const unsigned long sys_processors = sysconf(_SC_NPROCESSORS_CONF); - JLI_TraceLauncher("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors); - return sys_processors; -} - -jboolean -ServerClassMachineImpl(void) { - jboolean result = JNI_FALSE; - /* How big is a server class machine? */ - const unsigned long server_processors = 2UL; - const uint64_t server_memory = 2UL * GB; - const uint64_t actual_memory = physical_memory(); - - /* Is this a server class machine? */ - if (actual_memory >= server_memory) { - const unsigned long actual_processors = physical_processors(); - if (actual_processors >= server_processors) { - result = JNI_TRUE; - } - } - JLI_TraceLauncher("unix_" LIBARCHNAME "_ServerClassMachine: %s\n", - (result == JNI_TRUE ? "JNI_TRUE" : "JNI_FALSE")); - return result; -} -#endif - -/* Compute physical memory by asking the OS */ -uint64_t -physical_memory(void) { - const uint64_t pages = (uint64_t) sysconf(_SC_PHYS_PAGES); - const uint64_t page_size = (uint64_t) sysconf(_SC_PAGESIZE); - const uint64_t result = pages * page_size; -# define UINT64_FORMAT "%" PRIu64 - - JLI_TraceLauncher("pages: " UINT64_FORMAT - " page_size: " UINT64_FORMAT - " physical memory: " UINT64_FORMAT " (%.3fGB)\n", - pages, page_size, result, result / (double) GB); - return result; -} diff --git a/jdk/src/java.base/unix/native/libjli/ergo.h b/jdk/src/java.base/unix/native/libjli/ergo.h deleted file mode 100644 index 4f146e0e678..00000000000 --- a/jdk/src/java.base/unix/native/libjli/ergo.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#ifndef _ERGO_H -#define _ERGO_H - -#include -#include -#include -#include -#include -#include -#include - -#include "java.h" - -jboolean ServerClassMachineImpl(void); -uint64_t physical_memory(void); - -#endif /* _ERGO_H */ diff --git a/jdk/src/java.base/unix/native/libjli/ergo_i586.c b/jdk/src/java.base/unix/native/libjli/ergo_i586.c deleted file mode 100644 index f2421700289..00000000000 --- a/jdk/src/java.base/unix/native/libjli/ergo_i586.c +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include "ergo.h" - -static unsigned long physical_processors(void); - -#ifdef __solaris__ - -/* - * A utility method for asking the CPU about itself. - * There's a corresponding version of linux-i586 - * because the compilers are different. - */ -static void -get_cpuid(uint32_t arg, - uint32_t* eaxp, - uint32_t* ebxp, - uint32_t* ecxp, - uint32_t* edxp) { -#ifdef _LP64 - asm( - /* rbx is a callee-saved register */ - " movq %rbx, %r11 \n" - /* rdx and rcx are 3rd and 4th argument registers */ - " movq %rdx, %r10 \n" - " movq %rcx, %r9 \n" - " movl %edi, %eax \n" - " cpuid \n" - " movl %eax, (%rsi)\n" - " movl %ebx, (%r10)\n" - " movl %ecx, (%r9) \n" - " movl %edx, (%r8) \n" - /* Restore rbx */ - " movq %r11, %rbx"); -#else - /* EBX is a callee-saved register */ - asm(" pushl %ebx"); - /* Need ESI for storing through arguments */ - asm(" pushl %esi"); - asm(" movl 8(%ebp), %eax \n" - " cpuid \n" - " movl 12(%ebp), %esi \n" - " movl %eax, (%esi) \n" - " movl 16(%ebp), %esi \n" - " movl %ebx, (%esi) \n" - " movl 20(%ebp), %esi \n" - " movl %ecx, (%esi) \n" - " movl 24(%ebp), %esi \n" - " movl %edx, (%esi) "); - /* Restore ESI and EBX */ - asm(" popl %esi"); - /* Restore EBX */ - asm(" popl %ebx"); -#endif /* LP64 */ -} - -/* The definition of a server-class machine for solaris-i586/amd64 */ -jboolean -ServerClassMachineImpl(void) { - jboolean result = JNI_FALSE; - /* How big is a server class machine? */ - const unsigned long server_processors = 2UL; - const uint64_t server_memory = 2UL * GB; - /* - * We seem not to get our full complement of memory. - * We allow some part (1/8?) of the memory to be "missing", - * based on the sizes of DIMMs, and maybe graphics cards. - */ - const uint64_t missing_memory = 256UL * MB; - const uint64_t actual_memory = physical_memory(); - - /* Is this a server class machine? */ - if (actual_memory >= (server_memory - missing_memory)) { - const unsigned long actual_processors = physical_processors(); - if (actual_processors >= server_processors) { - result = JNI_TRUE; - } - } - JLI_TraceLauncher("solaris_" LIBARCHNAME "_ServerClassMachine: %s\n", - (result == JNI_TRUE ? "true" : "false")); - return result; -} - -#endif /* __solaris__ */ - -#ifdef __linux__ - -/* - * A utility method for asking the CPU about itself. - * There's a corresponding version of solaris-i586 - * because the compilers are different. - */ -static void -get_cpuid(uint32_t arg, - uint32_t* eaxp, - uint32_t* ebxp, - uint32_t* ecxp, - uint32_t* edxp) { -#ifdef _LP64 - __asm__ volatile (/* Instructions */ - " movl %4, %%eax \n" - " cpuid \n" - " movl %%eax, (%0)\n" - " movl %%ebx, (%1)\n" - " movl %%ecx, (%2)\n" - " movl %%edx, (%3)\n" - : /* Outputs */ - : /* Inputs */ - "r" (eaxp), - "r" (ebxp), - "r" (ecxp), - "r" (edxp), - "r" (arg) - : /* Clobbers */ - "%rax", "%rbx", "%rcx", "%rdx", "memory" - ); -#else /* _LP64 */ - uint32_t value_of_eax = 0; - uint32_t value_of_ebx = 0; - uint32_t value_of_ecx = 0; - uint32_t value_of_edx = 0; - __asm__ volatile (/* Instructions */ - /* ebx is callee-save, so push it */ - " pushl %%ebx \n" - " movl %4, %%eax \n" - " cpuid \n" - " movl %%eax, %0 \n" - " movl %%ebx, %1 \n" - " movl %%ecx, %2 \n" - " movl %%edx, %3 \n" - /* restore ebx */ - " popl %%ebx \n" - - : /* Outputs */ - "=m" (value_of_eax), - "=m" (value_of_ebx), - "=m" (value_of_ecx), - "=m" (value_of_edx) - : /* Inputs */ - "m" (arg) - : /* Clobbers */ - "%eax", "%ecx", "%edx" - ); - *eaxp = value_of_eax; - *ebxp = value_of_ebx; - *ecxp = value_of_ecx; - *edxp = value_of_edx; -#endif /* _LP64 */ -} - -/* The definition of a server-class machine for linux-i586 */ -jboolean -ServerClassMachineImpl(void) { - jboolean result = JNI_FALSE; - /* How big is a server class machine? */ - const unsigned long server_processors = 2UL; - const uint64_t server_memory = 2UL * GB; - /* - * We seem not to get our full complement of memory. - * We allow some part (1/8?) of the memory to be "missing", - * based on the sizes of DIMMs, and maybe graphics cards. - */ - const uint64_t missing_memory = 256UL * MB; - const uint64_t actual_memory = physical_memory(); - - /* Is this a server class machine? */ - if (actual_memory >= (server_memory - missing_memory)) { - const unsigned long actual_processors = physical_processors(); - if (actual_processors >= server_processors) { - result = JNI_TRUE; - } - } - JLI_TraceLauncher("linux_" LIBARCHNAME "_ServerClassMachine: %s\n", - (result == JNI_TRUE ? "true" : "false")); - return result; -} -#endif /* __linux__ */ - -/* - * Routines shared by solaris-i586 and linux-i586. - */ - -enum HyperThreadingSupport_enum { - hts_supported = 1, - hts_too_soon_to_tell = 0, - hts_not_supported = -1, - hts_not_pentium4 = -2, - hts_not_intel = -3 -}; -typedef enum HyperThreadingSupport_enum HyperThreadingSupport; - -/* Determine if hyperthreading is supported */ -static HyperThreadingSupport -hyperthreading_support(void) { - HyperThreadingSupport result = hts_too_soon_to_tell; - /* Bits 11 through 8 is family processor id */ -# define FAMILY_ID_SHIFT 8 -# define FAMILY_ID_MASK 0xf - /* Bits 23 through 20 is extended family processor id */ -# define EXT_FAMILY_ID_SHIFT 20 -# define EXT_FAMILY_ID_MASK 0xf - /* Pentium 4 family processor id */ -# define PENTIUM4_FAMILY_ID 0xf - /* Bit 28 indicates Hyper-Threading Technology support */ -# define HT_BIT_SHIFT 28 -# define HT_BIT_MASK 1 - uint32_t vendor_id[3] = { 0U, 0U, 0U }; - uint32_t value_of_eax = 0U; - uint32_t value_of_edx = 0U; - uint32_t dummy = 0U; - - /* Yes, this is supposed to be [0], [2], [1] */ - get_cpuid(0, &dummy, &vendor_id[0], &vendor_id[2], &vendor_id[1]); - JLI_TraceLauncher("vendor: %c %c %c %c %c %c %c %c %c %c %c %c \n", - ((vendor_id[0] >> 0) & 0xff), - ((vendor_id[0] >> 8) & 0xff), - ((vendor_id[0] >> 16) & 0xff), - ((vendor_id[0] >> 24) & 0xff), - ((vendor_id[1] >> 0) & 0xff), - ((vendor_id[1] >> 8) & 0xff), - ((vendor_id[1] >> 16) & 0xff), - ((vendor_id[1] >> 24) & 0xff), - ((vendor_id[2] >> 0) & 0xff), - ((vendor_id[2] >> 8) & 0xff), - ((vendor_id[2] >> 16) & 0xff), - ((vendor_id[2] >> 24) & 0xff)); - get_cpuid(1, &value_of_eax, &dummy, &dummy, &value_of_edx); - JLI_TraceLauncher("value_of_eax: 0x%x value_of_edx: 0x%x\n", - value_of_eax, value_of_edx); - if ((((value_of_eax >> FAMILY_ID_SHIFT) & FAMILY_ID_MASK) == PENTIUM4_FAMILY_ID) || - (((value_of_eax >> EXT_FAMILY_ID_SHIFT) & EXT_FAMILY_ID_MASK) != 0)) { - if ((((vendor_id[0] >> 0) & 0xff) == 'G') && - (((vendor_id[0] >> 8) & 0xff) == 'e') && - (((vendor_id[0] >> 16) & 0xff) == 'n') && - (((vendor_id[0] >> 24) & 0xff) == 'u') && - (((vendor_id[1] >> 0) & 0xff) == 'i') && - (((vendor_id[1] >> 8) & 0xff) == 'n') && - (((vendor_id[1] >> 16) & 0xff) == 'e') && - (((vendor_id[1] >> 24) & 0xff) == 'I') && - (((vendor_id[2] >> 0) & 0xff) == 'n') && - (((vendor_id[2] >> 8) & 0xff) == 't') && - (((vendor_id[2] >> 16) & 0xff) == 'e') && - (((vendor_id[2] >> 24) & 0xff) == 'l')) { - if (((value_of_edx >> HT_BIT_SHIFT) & HT_BIT_MASK) == HT_BIT_MASK) { - JLI_TraceLauncher("Hyperthreading supported\n"); - result = hts_supported; - } else { - JLI_TraceLauncher("Hyperthreading not supported\n"); - result = hts_not_supported; - } - } else { - JLI_TraceLauncher("Not GenuineIntel\n"); - result = hts_not_intel; - } - } else { - JLI_TraceLauncher("not Pentium 4 or extended\n"); - result = hts_not_pentium4; - } - return result; -} - -/* Determine how many logical processors there are per CPU */ -static unsigned int -logical_processors_per_package(void) { - /* - * After CPUID with EAX==1, register EBX bits 23 through 16 - * indicate the number of logical processors per package - */ -# define NUM_LOGICAL_SHIFT 16 -# define NUM_LOGICAL_MASK 0xff - unsigned int result = 1U; - const HyperThreadingSupport hyperthreading = hyperthreading_support(); - - if (hyperthreading == hts_supported) { - uint32_t value_of_ebx = 0U; - uint32_t dummy = 0U; - - get_cpuid(1, &dummy, &value_of_ebx, &dummy, &dummy); - result = (value_of_ebx >> NUM_LOGICAL_SHIFT) & NUM_LOGICAL_MASK; - JLI_TraceLauncher("logical processors per package: %u\n", result); - } - return result; -} - -/* Compute the number of physical processors, not logical processors */ -static unsigned long -physical_processors(void) { - const long sys_processors = sysconf(_SC_NPROCESSORS_CONF); - unsigned long result = sys_processors; - - JLI_TraceLauncher("sysconf(_SC_NPROCESSORS_CONF): %lu\n", sys_processors); - if (sys_processors > 1) { - unsigned int logical_processors = logical_processors_per_package(); - if (logical_processors > 1) { - result = (unsigned long) sys_processors / logical_processors; - } - } - JLI_TraceLauncher("physical processors: %lu\n", result); - return result; -} diff --git a/jdk/src/java.base/windows/conf/amd64/jvm.cfg b/jdk/src/java.base/windows/conf/amd64/jvm.cfg index 21ab9fd0fde..41ef6cb7e1a 100644 --- a/jdk/src/java.base/windows/conf/amd64/jvm.cfg +++ b/jdk/src/java.base/windows/conf/amd64/jvm.cfg @@ -1,6 +1,3 @@ -# -# -# # Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # @@ -27,7 +24,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/windows/conf/i586/jvm.cfg b/jdk/src/java.base/windows/conf/i586/jvm.cfg index 2bacbb66feb..895ab8962c5 100644 --- a/jdk/src/java.base/windows/conf/i586/jvm.cfg +++ b/jdk/src/java.base/windows/conf/i586/jvm.cfg @@ -23,7 +23,7 @@ # # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/windows/conf/ia64/jvm.cfg b/jdk/src/java.base/windows/conf/ia64/jvm.cfg index ac0c8084224..63cd6690d0a 100644 --- a/jdk/src/java.base/windows/conf/ia64/jvm.cfg +++ b/jdk/src/java.base/windows/conf/ia64/jvm.cfg @@ -1,6 +1,3 @@ -# -# -# # Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # @@ -24,10 +21,9 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# # List of JVMs that can be used as an option to java, javac, etc. # Order is important -- first in this list is the default JVM. -# NOTE that this both this file and its format are UNSUPPORTED and +# NOTE that both this file and its format are UNSUPPORTED and # WILL GO AWAY in a future release. # # You may also select a JVM in an arbitrary location with the diff --git a/jdk/src/java.base/windows/native/libjli/java_md.c b/jdk/src/java.base/windows/native/libjli/java_md.c index 1db3c408740..adb90a50cc4 100644 --- a/jdk/src/java.base/windows/native/libjli/java_md.c +++ b/jdk/src/java.base/windows/native/libjli/java_md.c @@ -639,11 +639,6 @@ void JLI_ReportExceptionDescription(JNIEnv * env) { } } -jboolean -ServerClassMachine() { - return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE; -} - /* * Wrapper for platform dependent unsetenv function. */ From 7b4b8a2eec591a7ba3dd64f8428cc593dcc61bcb Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Fri, 11 Nov 2016 11:31:17 +0800 Subject: [PATCH 005/402] 8169041: com/sun/corba/cachedSocket should be added to exclusiveAccess.dirs Reviewed-by: chegar --- jdk/test/TEST.ROOT | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/TEST.ROOT b/jdk/test/TEST.ROOT index 8a4164133fe..1e703488ea6 100644 --- a/jdk/test/TEST.ROOT +++ b/jdk/test/TEST.ROOT @@ -18,7 +18,7 @@ keys=2d dnd i18n intermittent randomness headful othervm.dirs=java/awt java/beans javax/accessibility javax/imageio javax/sound javax/print javax/management com/sun/awt sun/awt sun/java2d sun/pisces javax/xml/jaxp/testng/validation java/lang/ProcessHandle # Tests that cannot run concurrently -exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi java/util/stream javax/rmi +exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi java/util/stream javax/rmi com/sun/corba/cachedSocket # Group definitions groups=TEST.groups [closed/TEST.groups] From 6764a3bc32216348c394197282c3fe7caea61b6a Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:53 +0000 Subject: [PATCH 006/402] Added tag jdk-9+144 for changeset 612b698f8b8f --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 508a3a48852..d39ded9908c 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -386,3 +386,4 @@ e93b7ea559759f036c9f69fd2ddaf47bb4e98385 jdk-9+140 8d752af5f61d41f226adf2cda72a20faa9ad620a jdk-9+141 6ce43dd8e954b452f330dd7a412df5107f7e1923 jdk-9+142 8dbc8594f9d5149bf1c22221272284609408227a jdk-9+143 +efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 From 9889b2205653177bfff36d2cf396d6ef64f4e4eb Mon Sep 17 00:00:00 2001 From: Mark Sheppard Date: Fri, 11 Nov 2016 13:11:27 +0000 Subject: [PATCH 007/402] 8164815: 3 JCK NetworkInterface tests fail on Raspberry Pi Reviewed-by: chegar, alanb --- .../classes/java/net/NetworkInterface.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/net/NetworkInterface.java b/jdk/src/java.base/share/classes/java/net/NetworkInterface.java index f505bc48a82..960024f939d 100644 --- a/jdk/src/java.base/share/classes/java/net/NetworkInterface.java +++ b/jdk/src/java.base/share/classes/java/net/NetworkInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -335,15 +335,19 @@ public final class NetworkInterface { * {@link #getInetAddresses()} to obtain all IP addresses for this node * * @return an Enumeration of NetworkInterfaces found on this machine - * @exception SocketException if an I/O error occurs. + * @exception SocketException if an I/O error occurs, + * or if the platform does not have at least one configured + * network interface. * @see #networkInterfaces() */ public static Enumeration getNetworkInterfaces() throws SocketException { NetworkInterface[] netifs = getAll(); - assert netifs != null && netifs.length > 0; - - return enumerationFromArray(netifs); + if (netifs != null && netifs.length > 0) { + return enumerationFromArray(netifs); + } else { + throw new SocketException("No network interfaces configured"); + } } /** @@ -361,15 +365,19 @@ public final class NetworkInterface { * } * * @return a Stream of NetworkInterfaces found on this machine - * @exception SocketException if an I/O error occurs. + * @exception SocketException if an I/O error occurs, + * or if the platform does not have at least one configured + * network interface. * @since 9 */ public static Stream networkInterfaces() throws SocketException { NetworkInterface[] netifs = getAll(); - assert netifs != null && netifs.length > 0; - - return streamFromArray(netifs); + if (netifs != null && netifs.length > 0) { + return streamFromArray(netifs); + } else { + throw new SocketException("No network interfaces configured"); + } } private static Enumeration enumerationFromArray(T[] a) { From eab488fc011d24f1209e122ce1c40ce842167b3d Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Mon, 14 Nov 2016 10:07:10 +0100 Subject: [PATCH 008/402] 8169595: jshell tool: pasting multiple lines hangs input Need to allow newlines in the user's input. Reviewed-by: rfield --- .../share/classes/jdk/internal/jline/console/ConsoleReader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/console/ConsoleReader.java b/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/console/ConsoleReader.java index 999b0f7bd91..a7f26871f28 100644 --- a/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/console/ConsoleReader.java +++ b/jdk/src/jdk.internal.le/share/classes/jdk/internal/jline/console/ConsoleReader.java @@ -3222,7 +3222,7 @@ public class ConsoleReader } //where: private Pattern CURSOR_COLUMN_PATTERN = - Pattern.compile("(?.*)\033\\[[0-9]+;(?[0-9]+)R"); + Pattern.compile("(?.*)\033\\[[0-9]+;(?[0-9]+)R", Pattern.DOTALL); /** * Read a line for unsupported terminals. From 6cbbf83a1acdd5efea4d8f888260983c2a3533ca Mon Sep 17 00:00:00 2001 From: Sunny Chan Date: Thu, 28 Jan 2016 23:13:50 -0500 Subject: [PATCH 009/402] 8169556: Wrapping of FileInputStream's native skip and available methods Wrap further native methods in FileInputStreams Reviewed-by: chegar, bpb, rriggs --- jdk/make/mapfiles/libjava/mapfile-vers | 4 ++-- jdk/make/mapfiles/libjava/reorder-sparc | 2 +- jdk/make/mapfiles/libjava/reorder-sparcv9 | 2 +- jdk/make/mapfiles/libjava/reorder-x86 | 2 +- .../share/classes/java/io/FileInputStream.java | 12 ++++++++++-- .../java.base/share/native/libjava/FileInputStream.c | 4 ++-- 6 files changed, 17 insertions(+), 9 deletions(-) diff --git a/jdk/make/mapfiles/libjava/mapfile-vers b/jdk/make/mapfiles/libjava/mapfile-vers index f0e3f2bb076..5d7cc4a655f 100644 --- a/jdk/make/mapfiles/libjava/mapfile-vers +++ b/jdk/make/mapfiles/libjava/mapfile-vers @@ -77,13 +77,13 @@ SUNWprivate_1.1 { Java_java_io_FileDescriptor_initIDs; Java_java_io_FileDescriptor_sync; Java_java_io_FileDescriptor_getAppend; - Java_java_io_FileInputStream_available; + Java_java_io_FileInputStream_available0; Java_java_io_FileInputStream_close0; Java_java_io_FileInputStream_initIDs; Java_java_io_FileInputStream_open0; Java_java_io_FileInputStream_read0; Java_java_io_FileInputStream_readBytes; - Java_java_io_FileInputStream_skip; + Java_java_io_FileInputStream_skip0; Java_java_io_FileOutputStream_close0; Java_java_io_FileOutputStream_initIDs; Java_java_io_FileOutputStream_open0; diff --git a/jdk/make/mapfiles/libjava/reorder-sparc b/jdk/make/mapfiles/libjava/reorder-sparc index 6743ccedfaa..da91bfb6f68 100644 --- a/jdk/make/mapfiles/libjava/reorder-sparc +++ b/jdk/make/mapfiles/libjava/reorder-sparc @@ -44,7 +44,7 @@ text: .text%Java_java_io_FileInputStream_open0; text: .text%fileOpen; text: .text%Java_java_io_FileInputStream_readBytes; text: .text%readBytes; -text: .text%Java_java_io_FileInputStream_available; +text: .text%Java_java_io_FileInputStream_available0; text: .text%Java_java_io_FileInputStream_close0; text: .text%Java_java_lang_System_mapLibraryName; text: .text%Java_java_io_UnixFileSystem_getBooleanAttributes0; diff --git a/jdk/make/mapfiles/libjava/reorder-sparcv9 b/jdk/make/mapfiles/libjava/reorder-sparcv9 index 877d2d79b5e..aa605871ecc 100644 --- a/jdk/make/mapfiles/libjava/reorder-sparcv9 +++ b/jdk/make/mapfiles/libjava/reorder-sparcv9 @@ -48,7 +48,7 @@ text: .text%Java_java_io_FileInputStream_open0; text: .text%fileOpen; text: .text%Java_java_io_FileInputStream_readBytes; text: .text%readBytes; -text: .text%Java_java_io_FileInputStream_available; +text: .text%Java_java_io_FileInputStream_available0; text: .text%Java_java_io_FileInputStream_close0; text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2; text: .text%Java_java_io_UnixFileSystem_list; diff --git a/jdk/make/mapfiles/libjava/reorder-x86 b/jdk/make/mapfiles/libjava/reorder-x86 index d0407001e62..4e3e9365561 100644 --- a/jdk/make/mapfiles/libjava/reorder-x86 +++ b/jdk/make/mapfiles/libjava/reorder-x86 @@ -76,7 +76,7 @@ text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_Pri text: .text%JNU_GetEnv; text: .text%Java_java_io_UnixFileSystem_checkAccess; text: .text%Java_sun_reflect_NativeMethodAccessorImpl_invoke0; -text: .text%Java_java_io_FileInputStream_available; +text: .text%Java_java_io_FileInputStream_available0; text: .text%Java_java_lang_reflect_Array_newArray; text: .text%Java_java_lang_StackTraceElement_initStackTraceElements; text: .text%Java_java_lang_System_identityHashCode; diff --git a/jdk/src/java.base/share/classes/java/io/FileInputStream.java b/jdk/src/java.base/share/classes/java/io/FileInputStream.java index 713b2ad0e95..a321c61ae41 100644 --- a/jdk/src/java.base/share/classes/java/io/FileInputStream.java +++ b/jdk/src/java.base/share/classes/java/io/FileInputStream.java @@ -280,7 +280,11 @@ class FileInputStream extends InputStream * @exception IOException if n is negative, if the stream does not * support seek, or if an I/O error occurs. */ - public native long skip(long n) throws IOException; + public long skip(long n) throws IOException { + return skip0(n); + } + + private native long skip0(long n) throws IOException; /** * Returns an estimate of the number of remaining bytes that can be read (or @@ -299,7 +303,11 @@ class FileInputStream extends InputStream * @exception IOException if this file input stream has been closed by calling * {@code close} or an I/O error occurs. */ - public native int available() throws IOException; + public int available() throws IOException { + return available0(); + } + + private native int available0() throws IOException; /** * Closes this file input stream and releases any system resources diff --git a/jdk/src/java.base/share/native/libjava/FileInputStream.c b/jdk/src/java.base/share/native/libjava/FileInputStream.c index d0e23897015..44122a87b27 100644 --- a/jdk/src/java.base/share/native/libjava/FileInputStream.c +++ b/jdk/src/java.base/share/native/libjava/FileInputStream.c @@ -73,7 +73,7 @@ Java_java_io_FileInputStream_readBytes(JNIEnv *env, jobject this, } JNIEXPORT jlong JNICALL -Java_java_io_FileInputStream_skip(JNIEnv *env, jobject this, jlong toSkip) { +Java_java_io_FileInputStream_skip0(JNIEnv *env, jobject this, jlong toSkip) { jlong cur = jlong_zero; jlong end = jlong_zero; FD fd = GET_FD(this, fis_fd); @@ -90,7 +90,7 @@ Java_java_io_FileInputStream_skip(JNIEnv *env, jobject this, jlong toSkip) { } JNIEXPORT jint JNICALL -Java_java_io_FileInputStream_available(JNIEnv *env, jobject this) { +Java_java_io_FileInputStream_available0(JNIEnv *env, jobject this) { jlong ret; FD fd = GET_FD(this, fis_fd); if (fd == -1) { From d2b993e2ab96fbc4a10d321c18a8e37545a02d1e Mon Sep 17 00:00:00 2001 From: Erik Helin Date: Wed, 28 Sep 2016 16:41:38 +0200 Subject: [PATCH 010/402] 8166790: Add stress test GCBasher Reviewed-by: dfazunen, dholmes, erikj, tschatzl, lmesnik --- make/jprt.properties | 50 +++++++++++++------------------------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/make/jprt.properties b/make/jprt.properties index 2130ae6b5db..9a01ad3db7a 100644 --- a/make/jprt.properties +++ b/make/jprt.properties @@ -334,11 +334,7 @@ my.test.targets.hotspot.solaris.sparcv9= \ solaris_sparcv9_5.11-{product|fastdebug}-c2-jvm98, \ solaris_sparcv9_5.11-{product|fastdebug}-c2-jvm98_nontiered, \ solaris_sparcv9_5.11-{product|fastdebug}-c2-scimark, \ - solaris_sparcv9_5.11-product-c2-runThese8, \ - solaris_sparcv9_5.11-{product|fastdebug}-c2-GCBasher_SerialGC, \ - solaris_sparcv9_5.11-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - solaris_sparcv9_5.11-{product|fastdebug}-c2-GCBasher_CMS, \ - solaris_sparcv9_5.11-{product|fastdebug}-c2-GCBasher_G1 + solaris_sparcv9_5.11-product-c2-runThese8, my.test.targets.hotspot.solaris.x64= \ solaris_x64_5.11-{product|fastdebug}-c2-jvm98, \ @@ -346,40 +342,24 @@ my.test.targets.hotspot.solaris.x64= \ solaris_x64_5.11-{product|fastdebug}-c2-scimark, \ solaris_x64_5.11-product-c2-runThese8, \ solaris_x64_5.11-product-c2-runThese8_Xcomp_lang, \ - solaris_x64_5.11-product-c2-runThese8_Xcomp_vm, \ - solaris_x64_5.11-{product|fastdebug}-c2-GCBasher_SerialGC, \ - solaris_x64_5.11-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - solaris_x64_5.11-{product|fastdebug}-c2-GCBasher_CMS, \ - solaris_x64_5.11-{product|fastdebug}-c2-GCBasher_G1 + solaris_x64_5.11-product-c2-runThese8_Xcomp_vm, my.test.targets.hotspot.linux.i586= \ linux_i586_3.8-{product|fastdebug}-c2-jvm98, \ linux_i586_3.8-{product|fastdebug}-c2-jvm98_nontiered, \ linux_i586_3.8-{product|fastdebug}-c2-scimark, \ linux_i586_3.8-fastdebug-c2-runThese8_Xcomp_lang, \ - linux_i586_3.8-fastdebug-c2-runThese8_Xcomp_vm, \ - linux_i586_3.8-{product|fastdebug}-c2-GCBasher_SerialGC, \ - linux_i586_3.8-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - linux_i586_3.8-{product|fastdebug}-c2-GCBasher_CMS, \ - linux_i586_3.8-{product|fastdebug}-c2-GCBasher_G1 + linux_i586_3.8-fastdebug-c2-runThese8_Xcomp_vm my.test.targets.hotspot.linux.x64= \ linux_x64_3.8-{product|fastdebug}-c2-jvm98, \ linux_x64_3.8-{product|fastdebug}-c2-jvm98_nontiered, \ - linux_x64_3.8-{product|fastdebug}-c2-scimark, \ - linux_x64_3.8-{product|fastdebug}-c2-GCBasher_SerialGC, \ - linux_x64_3.8-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - linux_x64_3.8-{product|fastdebug}-c2-GCBasher_CMS, \ - linux_x64_3.8-{product|fastdebug}-c2-GCBasher_G1 + linux_x64_3.8-{product|fastdebug}-c2-scimark my.test.targets.hotspot.macosx.x64= \ macosx_x64_10.9-{product|fastdebug}-c2-jvm98, \ macosx_x64_10.9-{product|fastdebug}-c2-jvm98_nontiered, \ - macosx_x64_10.9-{product|fastdebug}-c2-scimark, \ - macosx_x64_10.9-{product|fastdebug}-c2-GCBasher_SerialGC, \ - macosx_x64_10.9-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - macosx_x64_10.9-{product|fastdebug}-c2-GCBasher_CMS, \ - macosx_x64_10.9-{product|fastdebug}-c2-GCBasher_G1 + macosx_x64_10.9-{product|fastdebug}-c2-scimark my.test.targets.hotspot.windows.i586= \ windows_i586_6.3-{product|fastdebug}-c2-jvm98, \ @@ -387,11 +367,7 @@ my.test.targets.hotspot.windows.i586= \ windows_i586_6.3-{product|fastdebug}-c2-scimark, \ windows_i586_6.3-product-c2-runThese8, \ windows_i586_6.3-product-c2-runThese8_Xcomp_lang, \ - windows_i586_6.3-product-c2-runThese8_Xcomp_vm, \ - windows_i586_6.3-{product|fastdebug}-c2-GCBasher_SerialGC, \ - windows_i586_6.3-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - windows_i586_6.3-{product|fastdebug}-c2-GCBasher_CMS, \ - windows_i586_6.3-{product|fastdebug}-c2-GCBasher_G1 + windows_i586_6.3-product-c2-runThese8_Xcomp_vm, my.test.targets.hotspot.windows.x64= \ windows_x64_6.3-{product|fastdebug}-c2-jvm98, \ @@ -399,11 +375,7 @@ my.test.targets.hotspot.windows.x64= \ windows_x64_6.3-{product|fastdebug}-c2-scimark, \ windows_x64_6.3-product-c2-runThese8, \ windows_x64_6.3-product-c2-runThese8_Xcomp_lang, \ - windows_x64_6.3-product-c2-runThese8_Xcomp_vm, \ - windows_x64_6.3-{product|fastdebug}-c2-GCBasher_SerialGC, \ - windows_x64_6.3-{product|fastdebug}-c2-GCBasher_ParallelGC, \ - windows_x64_6.3-{product|fastdebug}-c2-GCBasher_CMS, \ - windows_x64_6.3-{product|fastdebug}-c2-GCBasher_G1 + windows_x64_6.3-product-c2-runThese8_Xcomp_vm, # Some basic "smoke" tests for OpenJDK builds my.test.targets.hotspot.open= \ @@ -468,9 +440,17 @@ my.make.rule.test.targets.hotspot.reg= \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_gc_2}, \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_gc_closed}, \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_gc_gcold}, \ + ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_gc_gcbasher}, \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_runtime}, \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=hotspot_fast_serviceability}, \ ${my.make.rule.test.targets.hotspot.reg.group:GROUP=jdk_svc_sanity}, \ + solaris_sparcv9_5.11-product-c2-hotspot_fast_gc_gcbasher, \ + solaris_x64_5.11-product-c2-hotspot_fast_gc_gcbasher, \ + linux_i586_3.8-product-c2-hotspot_fast_gc_gcbasher, \ + linux_x64_3.8-product-c2-hotspot_fast_gc_gcbasher, \ + macosx_x64_10.9-product-c2-hotspot_fast_gc_gcbasher, \ + windows_i586_6.3-product-c2-hotspot_fast_gc_gcbasher, \ + windows_x64_6.3-product-c2-hotspot_fast_gc_gcbasher, \ ${my.additional.make.rule.test.targets.hotspot.reg} # Other Makefile based Hotspot tests From d45aa3fbb152d685d4073b42ecc5f5c4c15dd0e0 Mon Sep 17 00:00:00 2001 From: Amit Sapre Date: Thu, 20 Oct 2016 15:07:06 +0530 Subject: [PATCH 011/402] 8167294: MXBean javadoc should be updated to take modules into account Updated MXBean class javadoc to take modules into account Reviewed-by: alanb --- .../share/classes/javax/management/MXBean.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/jdk/src/java.management/share/classes/javax/management/MXBean.java b/jdk/src/java.management/share/classes/javax/management/MXBean.java index 8784a5fbaf8..ca5402effda 100644 --- a/jdk/src/java.management/share/classes/javax/management/MXBean.java +++ b/jdk/src/java.management/share/classes/javax/management/MXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -916,14 +916,14 @@ public interface ModuleMXBean {
  • Otherwise, J is not reconstructible.

  • -

    When only {@code @java.beans.ConstructorProperties} is present then - rule 2 is not applicable to subset Profiles of Java SE that do not include - the {@code java.beans} package. When targeting a runtime that does - not include the {@code java.beans} package, and where there is a mismatch - between the compile-time and runtime environment whereby J is - compiled with a public constructor and the {@code ConstructorProperties} - annotation, then J is not reconstructible unless another rule - applies.

    +

    Rule 2 is not applicable when {@code java.beans.ConstructorProperties} + is not visible (e.g. when the java.desktop module is not readable or when + the runtime image does not contain the java.desktop module). When + targeting a runtime that does not include the {@code java.beans} package, + and where there is a mismatch between the compile-time and runtime + environment whereby J is compiled with a public constructor + and the {@code ConstructorProperties} annotation, then J is + not reconstructible unless another rule applies.

    Here are examples showing different ways to code a type {@code NamedNumber} that consists of an {@code int} and a {@code From 43935fe3d11ebb4f9346f03aed599a533e43ed02 Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Mon, 24 Oct 2016 09:07:24 +0200 Subject: [PATCH 012/402] 8168483: Remove jtreg timeout handler timeout Reviewed-by: dholmes, tbell --- jdk/test/Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/test/Makefile b/jdk/test/Makefile index 6958d9abb58..6a979a4175e 100644 --- a/jdk/test/Makefile +++ b/jdk/test/Makefile @@ -143,7 +143,8 @@ ifneq ($(FAILURE_HANDLER_DIR), ) -timeoutHandlerDir:$(FAILURE_HANDLER_DIR_MIXED)/jtregFailureHandler.jar \ -observerDir:$(FAILURE_HANDLER_DIR_MIXED)/jtregFailureHandler.jar \ -timeoutHandler:jdk.test.failurehandler.jtreg.GatherProcessInfoTimeoutHandler \ - -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver + -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver \ + -timeoutHandlerTimeout:0 ifeq ($(UNAME_S), CYGWIN) JTREG_FAILURE_HANDLER_OPTIONS += -J-Djava.library.path="$(FAILURE_HANDLER_DIR_MIXED)" endif From 447f64bf30de8197df112b1304ab5e4445470715 Mon Sep 17 00:00:00 2001 From: Robbin Ehn Date: Mon, 24 Oct 2016 09:07:26 +0200 Subject: [PATCH 013/402] 8164501: Uninitialised memory in byteArrayToPacket of SharedMemoryConnection.c Reviewed-by: sla, dsamersoff --- .../native/libdt_shmem/SharedMemoryConnection.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/jdk/src/jdk.jdi/share/native/libdt_shmem/SharedMemoryConnection.c b/jdk/src/jdk.jdi/share/native/libdt_shmem/SharedMemoryConnection.c index 5936b5a0dc8..e28efe63128 100644 --- a/jdk/src/jdk.jdi/share/native/libdt_shmem/SharedMemoryConnection.c +++ b/jdk/src/jdk.jdi/share/native/libdt_shmem/SharedMemoryConnection.c @@ -174,9 +174,20 @@ byteArrayToPacket(JNIEnv *env, jbyteArray b, jdwpPacket *str) * Get the packet header */ (*env)->GetByteArrayRegion(env, b, 0, sizeof(pktHeader), pktHeader); + if ((*env)->ExceptionOccurred(env)) { + /* b shorter than sizeof(pktHeader) */ + return; + } total_length = (int)pktHeader[3] | ((int)pktHeader[2] << 8) | ((int)pktHeader[1] << 16) | ((int)pktHeader[0] << 24); + + if (total_length < sizeof(pktHeader)) { + throwException(env, "java/lang/IllegalArgumentException", + "JDWP header is incorrect"); + return; + } + /* * The id field is in big endian (also errorCode field in the case * of reply packets). @@ -195,9 +206,9 @@ byteArrayToPacket(JNIEnv *env, jbyteArray b, jdwpPacket *str) } /* - * The length of the JDWP packet is 11 + data + * The length of the JDWP packet is sizeof(pktHeader) + data */ - data_length = total_length - 11; + data_length = total_length - sizeof(pktHeader); if (data_length == 0) { data = NULL; @@ -209,7 +220,7 @@ byteArrayToPacket(JNIEnv *env, jbyteArray b, jdwpPacket *str) return; } - (*env)->GetByteArrayRegion(env, b, 11, /*sizeof(CmdPacket)+4*/ data_length, data); + (*env)->GetByteArrayRegion(env, b, sizeof(pktHeader), /*sizeof(CmdPacket)+4*/ data_length, data); if ((*env)->ExceptionOccurred(env)) { free(data); return; From cb81552d35fdace1f71f28f875add90111b6ac4d Mon Sep 17 00:00:00 2001 From: Sharath Ballal Date: Mon, 24 Oct 2016 14:52:07 +0300 Subject: [PATCH 014/402] 8160376: DebuggerException: Can't attach symbolicator to the process Make SA link to JavaRuntimeSupport in MacOS X Reviewed-by: dsamersoff, dcubed --- jdk/test/ProblemList.txt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 07902bcbf72..577cbf48e6e 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -285,11 +285,9 @@ java/util/BitSet/BitSetStreamTest.java 8079538 generic- sun/tools/jcmd/TestJcmdSanity.java 8031482 windows-all -sun/tools/jhsdb/BasicLauncherTest.java 8160376 macosx-all +sun/tools/jhsdb/BasicLauncherTest.java 8159806 macosx-all -sun/tools/jhsdb/HeapDumpTest.java 8160376 macosx-all - -sun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java 8160376 macosx-all +sun/tools/jhsdb/HeapDumpTest.java 8168397 macosx-all sun/tools/jps/TestJpsJar.java 8165500 generic-all From 0e6c22bcea44fbfac996b6409a498d4f7e02e1cf Mon Sep 17 00:00:00 2001 From: Dmitry Samersoff Date: Tue, 25 Oct 2016 14:49:35 +0300 Subject: [PATCH 015/402] 8165500: TestJpsJar shouldn't jar all test.classpath directories Refactor test to better handle errors Reviewed-by: sspitsyn --- jdk/test/ProblemList.txt | 4 - jdk/test/sun/tools/jps/JpsBase.java | 163 ------ jdk/test/sun/tools/jps/JpsHelper.java | 111 ++-- jdk/test/sun/tools/jps/LingeredApp.java | 489 ++++++++++++++++++ jdk/test/sun/tools/jps/LingeredAppForJps.java | 147 ++++++ jdk/test/sun/tools/jps/TestJps.java | 80 +++ jdk/test/sun/tools/jps/TestJpsClass.java | 65 --- jdk/test/sun/tools/jps/TestJpsJar.java | 66 --- .../sun/tools/jps/TestJpsJarRelative.java | 65 --- jdk/test/sun/tools/jps/TestJpsSanity.java | 2 +- 10 files changed, 793 insertions(+), 399 deletions(-) delete mode 100644 jdk/test/sun/tools/jps/JpsBase.java create mode 100644 jdk/test/sun/tools/jps/LingeredApp.java create mode 100644 jdk/test/sun/tools/jps/LingeredAppForJps.java create mode 100644 jdk/test/sun/tools/jps/TestJps.java delete mode 100644 jdk/test/sun/tools/jps/TestJpsClass.java delete mode 100644 jdk/test/sun/tools/jps/TestJpsJar.java delete mode 100644 jdk/test/sun/tools/jps/TestJpsJarRelative.java diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 577cbf48e6e..ccdd124fb02 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -289,10 +289,6 @@ sun/tools/jhsdb/BasicLauncherTest.java 8159806 macosx-a sun/tools/jhsdb/HeapDumpTest.java 8168397 macosx-all -sun/tools/jps/TestJpsJar.java 8165500 generic-all - -sun/tools/jps/TestJpsJarRelative.java 6456333 generic-all - sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java 8057732 generic-all demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java 8151899 generic-all diff --git a/jdk/test/sun/tools/jps/JpsBase.java b/jdk/test/sun/tools/jps/JpsBase.java deleted file mode 100644 index 1b810f357bb..00000000000 --- a/jdk/test/sun/tools/jps/JpsBase.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.net.URL; -import java.util.List; - -import jdk.testlibrary.OutputAnalyzer; -import jdk.testlibrary.ProcessTools; - -/** - * The base class for testing the jps utility. - * The test sequence is to start jps with different combinations of arguments - * and verify the output contains proper values. - */ -public final class JpsBase { - - /** - * The jps output should contain processes' names - * (except when jps is started in quite mode). - * The expected name of the test process is prepared here. - */ - - private static String getShortProcessName() { - URL url = JpsBase.class.getResource("JpsBase.class"); - boolean isJar = url.getProtocol().equals("jar"); - return (isJar) ? JpsBase.class.getSimpleName() + ".jar" : JpsBase.class.getSimpleName(); - } - - private static String getFullProcessName() { - URL url = JpsBase.class.getResource("JpsBase.class"); - boolean isJar = url.getProtocol().equals("jar"); - if (isJar) { - String urlPath = url.getPath(); - File jar = new File(urlPath.substring(urlPath.indexOf("file:") + 5, urlPath.indexOf("jar!") + 3)); - return jar.getAbsolutePath(); - } - - return JpsBase.class.getName(); - } - - private static boolean userDirSanityCheck(String fullProcessName) { - String userDir = System.getProperty("user.dir"); - if (!fullProcessName.startsWith(userDir)) { - System.err.printf("Test skipped. user.dir '%s' is not a prefix of '%s'\n", userDir, fullProcessName); - return false; - } - return true; - } - - public static void main(String[] args) throws Exception { - System.out.printf("INFO: user.dir: '%s''\n", System.getProperty("user.dir")); - long pid = ProcessTools.getProcessId(); - - List> combinations = JpsHelper.JpsArg.generateCombinations(); - for (List combination : combinations) { - OutputAnalyzer output = JpsHelper.jps(JpsHelper.JpsArg.asCmdArray(combination)); - output.shouldHaveExitValue(0); - - boolean isQuiet = false; - boolean isFull = false; - String pattern; - for (JpsHelper.JpsArg jpsArg : combination) { - switch (jpsArg) { - case q: - // If '-q' is specified output should contain only a list of local VM identifiers: - // 30673 - isQuiet = true; - JpsHelper.verifyJpsOutput(output, "^\\d+$"); - output.shouldContain(Long.toString(pid)); - break; - case l: - // If '-l' is specified output should contain the full package name for the application's main class - // or the full path name to the application's JAR file: - // 30673 /tmp/jtreg/jtreg-workdir/scratch/JpsBase.jar ... - isFull = true; - String fullProcessName = getFullProcessName(); - // Skip the test if user.dir is not a prefix of the current path - // It's possible if the test is run from symlinked dir or windows alias drive - if (userDirSanityCheck(fullProcessName)) { - pattern = "^" + pid + "\\s+" + replaceSpecialChars(fullProcessName) + ".*"; - output.shouldMatch(pattern); - } - break; - case m: - // If '-m' is specified output should contain the arguments passed to the main method: - // 30673 JpsBase monkey ... - for (String arg : args) { - pattern = "^" + pid + ".*" + replaceSpecialChars(arg) + ".*"; - output.shouldMatch(pattern); - } - break; - case v: - // If '-v' is specified output should contain VM arguments: - // 30673 JpsBase -Xmx512m -XX:+UseParallelGC -XX:Flags=/tmp/jtreg/jtreg-workdir/scratch/vmflags ... - for (String vmArg : JpsHelper.getVmArgs()) { - pattern = "^" + pid + ".*" + replaceSpecialChars(vmArg) + ".*"; - output.shouldMatch(pattern); - } - break; - case V: - // If '-V' is specified output should contain VM flags: - // 30673 JpsBase +DisableExplicitGC ... - pattern = "^" + pid + ".*" + replaceSpecialChars(JpsHelper.VM_FLAG) + ".*"; - output.shouldMatch(pattern); - break; - } - - if (isQuiet) { - break; - } - } - - if (!isQuiet) { - // Verify output line by line. - // Output should only contain lines with pids after the first line with pid. - JpsHelper.verifyJpsOutput(output, "^\\d+\\s+.*"); - if (!isFull) { - String shortProcessName = getShortProcessName(); - pattern = "^" + pid + "\\s+" + replaceSpecialChars(shortProcessName); - if (combination.isEmpty()) { - // If no arguments are specified output should only contain - // pid and process name - pattern += "$"; - } else { - pattern += ".*"; - } - output.shouldMatch(pattern); - } - } - } - } - - private static String replaceSpecialChars(String str) { - String tmp = str.replace("\\", "\\\\"); - tmp = tmp.replace("+", "\\+"); - tmp = tmp.replace(".", "\\."); - tmp = tmp.replace("\n", "\\\\n"); - tmp = tmp.replace("\r", "\\\\r"); - return tmp; - } - -} diff --git a/jdk/test/sun/tools/jps/JpsHelper.java b/jdk/test/sun/tools/jps/JpsHelper.java index 3078ea5a336..be9ad0733d5 100644 --- a/jdk/test/sun/tools/jps/JpsHelper.java +++ b/jdk/test/sun/tools/jps/JpsHelper.java @@ -204,44 +204,85 @@ public final class JpsHelper { "The ouput should contain all content of " + path.toAbsolutePath()); } - private static File getManifest(String className) throws IOException { - if (manifestFile == null) { - manifestFile = new File(className + ".mf"); - try (BufferedWriter output = new BufferedWriter(new FileWriter(manifestFile))) { - output.write("Main-Class: " + className + Utils.NEW_LINE); + public static void runJpsVariants(Long pid, String processName, String fullProcessName, String argument) throws Exception { + System.out.printf("INFO: user.dir: '%s''\n", System.getProperty("user.dir")); + List> combinations = JpsHelper.JpsArg.generateCombinations(); + for (List combination : combinations) { + OutputAnalyzer output = JpsHelper.jps(JpsHelper.JpsArg.asCmdArray(combination)); + output.shouldHaveExitValue(0); + + boolean isQuiet = false; + boolean isFull = false; + String pattern; + for (JpsHelper.JpsArg jpsArg : combination) { + switch (jpsArg) { + case q: + // If '-q' is specified output should contain only a list of local VM identifiers: + // 30673 + isQuiet = true; + JpsHelper.verifyJpsOutput(output, "^\\d+$"); + output.shouldContain(Long.toString(pid)); + break; + case l: + // If '-l' is specified output should contain the full package name for the application's main class + // or the full path name to the application's JAR file: + // 30673 /tmp/jtreg/jtreg-workdir/scratch/LingeredAppForJps.jar ... + isFull = true; + pattern = "^" + pid + "\\s+" + replaceSpecialChars(fullProcessName) + ".*"; + output.shouldMatch(pattern); + break; + case m: + // If '-m' is specified output should contain the arguments passed to the main method: + // 30673 LingeredAppForJps lockfilename ... + pattern = "^" + pid + ".*" + replaceSpecialChars(argument) + ".*"; + output.shouldMatch(pattern); + break; + case v: + // If '-v' is specified output should contain VM arguments: + // 30673 LingeredAppForJps -Xmx512m -XX:+UseParallelGC -XX:Flags=/tmp/jtreg/jtreg-workdir/scratch/vmflags ... + for (String vmArg : JpsHelper.getVmArgs()) { + pattern = "^" + pid + ".*" + replaceSpecialChars(vmArg) + ".*"; + output.shouldMatch(pattern); + } + break; + case V: + // If '-V' is specified output should contain VM flags: + // 30673 LingeredAppForJps +DisableExplicitGC ... + pattern = "^" + pid + ".*" + replaceSpecialChars(JpsHelper.VM_FLAG) + ".*"; + output.shouldMatch(pattern); + break; + } + + if (isQuiet) { + break; + } + } + + if (!isQuiet) { + // Verify output line by line. + // Output should only contain lines with pids after the first line with pid. + JpsHelper.verifyJpsOutput(output, "^\\d+\\s+.*"); + if (!isFull) { + pattern = "^" + pid + "\\s+" + replaceSpecialChars(processName); + if (combination.isEmpty()) { + // If no arguments are specified output should only contain + // pid and process name + pattern += "$"; + } else { + pattern += ".*"; + } + output.shouldMatch(pattern); + } } } - return manifestFile; } - /** - * Build a jar of test classes in runtime - */ - public static File buildJar(String className) throws Exception { - File jar = new File(className + ".jar"); - - List jarArgs = new ArrayList<>(); - jarArgs.add("-cfm"); - jarArgs.add(jar.getAbsolutePath()); - File manifestFile = getManifest(className); - jarArgs.add(manifestFile.getAbsolutePath()); - String testClassPath = System.getProperty("test.class.path", "?"); - for (String path : testClassPath.split(File.pathSeparator)) { - jarArgs.add("-C"); - jarArgs.add(path); - jarArgs.add("."); - } - - System.out.println("Running jar " + jarArgs.toString()); - sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); - if (!jarTool.run(jarArgs.toArray(new String[jarArgs.size()]))) { - throw new Exception("jar failed: args=" + jarArgs.toString()); - } - - manifestFile.delete(); - jar.deleteOnExit(); - - return jar; + private static String replaceSpecialChars(String str) { + String tmp = str.replace("\\", "\\\\"); + tmp = tmp.replace("+", "\\+"); + tmp = tmp.replace(".", "\\."); + tmp = tmp.replace("\n", "\\\\n"); + tmp = tmp.replace("\r", "\\\\r"); + return tmp; } - } diff --git a/jdk/test/sun/tools/jps/LingeredApp.java b/jdk/test/sun/tools/jps/LingeredApp.java new file mode 100644 index 00000000000..b4aab24bc41 --- /dev/null +++ b/jdk/test/sun/tools/jps/LingeredApp.java @@ -0,0 +1,489 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * This is a framework to launch an app that could be synchronized with caller + * to make further attach actions reliable across supported platforms + + * Caller example: + * SmartTestApp a = SmartTestApp.startApp(cmd); + * // do something + * a.stopApp(); + * + * or fine grained control + * + * a = new SmartTestApp("MyLock.lck"); + * a.createLock(); + * a.runApp(); + * a.waitAppReady(); + * // do something + * a.deleteLock(); + * a.waitAppTerminate(); + * + * Then you can work with app output and process object + * + * output = a.getAppOutput(); + * process = a.getProcess(); + * + */ +public class LingeredApp { + + private static final long spinDelay = 1000; + + private long lockCreationTime; + private final ArrayList storedAppOutput; + + protected Process appProcess; + protected static final int appWaitTime = 100; + protected final String lockFileName; + + /* + * Drain child process output, store it into string array + */ + class InputGobbler extends Thread { + + InputStream is; + List astr; + + InputGobbler(InputStream is, List astr) { + this.is = is; + this.astr = astr; + } + + public void run() { + try { + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line = null; + while ((line = br.readLine()) != null) { + astr.add(line); + } + } catch (IOException ex) { + // pass + } + } + } + + /** + * Create LingeredApp object on caller side. Lock file have be a valid filename + * at writable location + * + * @param lockFileName - the name of lock file + */ + public LingeredApp(String lockFileName) { + this.lockFileName = lockFileName; + this.storedAppOutput = new ArrayList(); + } + + public LingeredApp() { + final String lockName = UUID.randomUUID().toString() + ".lck"; + this.lockFileName = lockName; + this.storedAppOutput = new ArrayList(); + } + + /** + * + * @return name of lock file + */ + public String getLockFileName() { + return this.lockFileName; + } + + /** + * + * @return name of testapp + */ + public String getAppName() { + return this.getClass().getName(); + } + + /** + * + * @return pid of java process running testapp + */ + public long getPid() { + if (appProcess == null) { + throw new RuntimeException("Process is not alive"); + } + return appProcess.getPid(); + } + + /** + * + * @return process object + */ + public Process getProcess() { + return appProcess; + } + + /** + * + * @return application output as string array. Empty array if application produced no output + */ + public List getAppOutput() { + if (appProcess.isAlive()) { + throw new RuntimeException("Process is still alive. Can't get its output."); + } + return storedAppOutput; + } + + /* Make sure all part of the app use the same method to get dates, + as different methods could produce different results + */ + private static long epoch() { + return new Date().getTime(); + } + + private static long lastModified(String fileName) throws IOException { + Path path = Paths.get(fileName); + BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); + return attr.lastModifiedTime().toMillis(); + } + + private static void setLastModified(String fileName, long newTime) throws IOException { + Path path = Paths.get(fileName); + FileTime fileTime = FileTime.fromMillis(newTime); + Files.setLastModifiedTime(path, fileTime); + } + + /** + * create lock + * + * @throws IOException + */ + public void createLock() throws IOException { + Path path = Paths.get(lockFileName); + // Files.deleteIfExists(path); + Files.createFile(path); + lockCreationTime = lastModified(lockFileName); + } + + /** + * Delete lock + * + * @throws IOException + */ + public void deleteLock() throws IOException { + try { + Path path = Paths.get(lockFileName); + Files.delete(path); + } catch (NoSuchFileException ex) { + // Lock already deleted. Ignore error + } + } + + public void waitAppTerminate() { + while (true) { + try { + appProcess.waitFor(); + break; + } catch (InterruptedException ex) { + // pass + } + } + } + + /** + * The app touches the lock file when it's started + * wait while it happens. Caller have to delete lock on wait error. + * + * @param timeout + * @throws java.io.IOException + */ + public void waitAppReady(long timeout) throws IOException { + long here = epoch(); + while (true) { + long epoch = epoch(); + if (epoch - here > (timeout * 1000)) { + throw new IOException("App waiting timeout"); + } + + // Live process should touch lock file every second + long lm = lastModified(lockFileName); + if (lm > lockCreationTime) { + break; + } + + // Make sure process didn't already exit + if (!appProcess.isAlive()) { + throw new IOException("App exited unexpectedly with " + appProcess.exitValue()); + } + + try { + Thread.sleep(spinDelay); + } catch (InterruptedException ex) { + // pass + } + } + } + + /** + * Analyze an environment and prepare a command line to + * run the app, app name should be added explicitly + */ + public List runAppPrepare(List vmArguments) { + // We should always use testjava or throw an exception, + // so we can't use JDKToolFinder.getJDKTool("java"); + // that falls back to compile java on error + String jdkPath = System.getProperty("test.jdk"); + if (jdkPath == null) { + // we are not under jtreg, try env + Map env = System.getenv(); + jdkPath = env.get("TESTJAVA"); + } + + if (jdkPath == null) { + throw new RuntimeException("Can't determine jdk path neither test.jdk property no TESTJAVA env are set"); + } + + String osname = System.getProperty("os.name"); + String javapath = jdkPath + ((osname.startsWith("window")) ? "/bin/java.exe" : "/bin/java"); + + List cmd = new ArrayList(); + cmd.add(javapath); + + + if (vmArguments == null) { + // Propagate test.vm.options to LingeredApp, filter out possible empty options + String testVmOpts[] = System.getProperty("test.vm.opts","").split("\\s+"); + for (String s : testVmOpts) { + if (!s.equals("")) { + cmd.add(s); + } + } + } + else{ + // Lets user manage LingeredApp options + cmd.addAll(vmArguments); + } + + // Make sure we set correct classpath to run the app + cmd.add("-cp"); + String classpath = System.getProperty("test.class.path"); + cmd.add((classpath == null) ? "." : classpath); + + return cmd; + } + + /** + * Assemble command line to a printable string + */ + public void printCommandLine(List cmd) { + // A bit of verbosity + StringBuilder cmdLine = new StringBuilder(); + for (String strCmd : cmd) { + cmdLine.append("'").append(strCmd).append("' "); + } + + System.out.println("Command line: [" + cmdLine.toString() + "]"); + } + + public void startGobblerPipe() { + // Create pipe reader for process, and read stdin and stderr to array of strings + InputGobbler gb = new InputGobbler(appProcess.getInputStream(), storedAppOutput); + gb.start(); + } + + /** + * Run the app. + * + * @param vmArguments + * @throws IOException + */ + public void runApp(List vmArguments) + throws IOException { + + List cmd = runAppPrepare(vmArguments); + + cmd.add(this.getAppName()); + cmd.add(lockFileName); + + printCommandLine(cmd); + + ProcessBuilder pb = new ProcessBuilder(cmd); + // we don't expect any error output but make sure we are not stuck on pipe + // pb.redirectErrorStream(false); + // ProcessBuilder.start can throw IOException + pb.redirectError(ProcessBuilder.Redirect.INHERIT); + appProcess = pb.start(); + + startGobblerPipe(); + } + + /** + * Delete lock file that signals app to terminate, then + * wait until app is actually terminated. + * @throws IOException + */ + public void stopApp() throws IOException { + deleteLock(); + // The startApp() of the derived app can throw + // an exception before the LA actually starts + if (appProcess != null) { + waitAppTerminate(); + int exitcode = appProcess.exitValue(); + if (exitcode != 0) { + throw new IOException("LingeredApp terminated with non-zero exit code " + exitcode); + } + } + } + + /** + * High level interface for test writers + */ + /** + * Factory method that creates LingeredApp object with ready to use application + * lock name is autogenerated + * @param cmd - vm options, could be null to auto add testvm.options + * @return LingeredApp object + * @throws IOException + */ + public static LingeredApp startApp(List cmd) throws IOException { + LingeredApp a = new LingeredApp(); + a.createLock(); + try { + a.runApp(cmd); + a.waitAppReady(appWaitTime); + } catch (Exception ex) { + a.deleteLock(); + throw ex; + } + + return a; + } + + /** + * Factory method that starts pre-created LingeredApp + * lock name is autogenerated + * @param cmd - vm options, could be null to auto add testvm.options + * @param theApp - app to start + * @return LingeredApp object + * @throws IOException + */ + + public static void startApp(List cmd, LingeredApp theApp) throws IOException { + theApp.createLock(); + try { + theApp.runApp(cmd); + theApp.waitAppReady(appWaitTime); + } catch (Exception ex) { + theApp.deleteLock(); + throw ex; + } + } + + public static LingeredApp startApp() throws IOException { + return startApp(null); + } + + public static void stopApp(LingeredApp app) throws IOException { + if (app != null) { + // LingeredApp can throw an exception during the intialization, + // make sure we don't have cascade NPE + app.stopApp(); + } + } + + /** + * LastModified time might not work correctly in some cases it might + * cause later failures + */ + + public static boolean isLastModifiedWorking() { + boolean sane = true; + try { + long lm = lastModified("."); + if (lm == 0) { + System.err.println("SANITY Warning! The lastModifiedTime() doesn't work on this system, it returns 0"); + sane = false; + } + + long now = epoch(); + if (lm > now) { + System.err.println("SANITY Warning! The Clock is wrong on this system lastModifiedTime() > getTime()"); + sane = false; + } + + setLastModified(".", epoch()); + long lm1 = lastModified("."); + if (lm1 <= lm) { + System.err.println("SANITY Warning! The setLastModified doesn't work on this system"); + sane = false; + } + } + catch(IOException e) { + System.err.println("SANITY Warning! IOException during sanity check " + e); + sane = false; + } + + return sane; + } + + /** + * This part is the application it self + */ + public static void main(String args[]) { + + if (args.length != 1) { + System.err.println("Lock file name is not specified"); + System.exit(7); + } + + String theLockFileName = args[0]; + + try { + Path path = Paths.get(theLockFileName); + + while (Files.exists(path)) { + // Touch the lock to indicate our readiness + setLastModified(theLockFileName, epoch()); + Thread.sleep(spinDelay); + } + } catch (NoSuchFileException ex) { + // Lock deleted while we are setting last modified time. + // Ignore error and lets the app exits + } catch (Exception ex) { + System.err.println("LingeredApp ERROR: " + ex); + // Leave exit_code = 1 to Java launcher + System.exit(3); + } + + System.exit(0); + } +} diff --git a/jdk/test/sun/tools/jps/LingeredAppForJps.java b/jdk/test/sun/tools/jps/LingeredAppForJps.java new file mode 100644 index 00000000000..f2407411b77 --- /dev/null +++ b/jdk/test/sun/tools/jps/LingeredAppForJps.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.net.URL; + +public class LingeredAppForJps extends LingeredApp { + + // Copy runApp logic here to be able to run an app from JarFile + public void runAppWithName(List vmArguments, String runName) + throws IOException { + + List cmd = runAppPrepare(vmArguments); + if (runName.endsWith(".jar")) { + cmd.add("-Xdiag"); + cmd.add("-jar"); + } + cmd.add(runName); + cmd.add(lockFileName); + + printCommandLine(cmd); + + ProcessBuilder pb = new ProcessBuilder(cmd); + // we don't expect any error output but make sure we are not stuck on pipe + pb.redirectError(ProcessBuilder.Redirect.INHERIT); + appProcess = pb.start(); + startGobblerPipe(); + } + + public static LingeredApp startAppJar(List cmd, LingeredAppForJps app, File jar) throws IOException { + app.createLock(); + try { + app.runAppWithName(cmd, jar.getAbsolutePath()); + app.waitAppReady(appWaitTime); + } catch (Exception ex) { + app.deleteLock(); + throw ex; + } + + return app; + } + + /** + * The jps output should contain processes' names + * (except when jps is started in quite mode). + * The expected name of the test process is prepared here. + */ + public static String getProcessName() { + return LingeredAppForJps.class.getSimpleName(); + } + + public static String getProcessName(File jar) { + return jar.getName(); + } + + // full package name for the application's main class or the full path + // name to the application's JAR file: + + public static String getFullProcessName() { + return LingeredAppForJps.class.getCanonicalName(); + } + + public static String getFullProcessName(File jar) { + return jar.getAbsolutePath(); + } + + public static File buildJar() throws IOException { + String className = LingeredAppForJps.class.getName(); + File jar = new File(className + ".jar"); + String testClassPath = System.getProperty("test.class.path", "?"); + + File manifestFile = new File(className + ".mf"); + String nl = System.getProperty("line.separator"); + try (BufferedWriter output = new BufferedWriter(new FileWriter(manifestFile))) { + output.write("Main-Class: " + className + nl); + } + + List jarArgs = new ArrayList<>(); + jarArgs.add("-cfm"); + jarArgs.add(jar.getAbsolutePath()); + jarArgs.add(manifestFile.getAbsolutePath()); + + for (String path : testClassPath.split(File.pathSeparator)) { + String classFullName = path + File.separator + className + ".class"; + File f = new File(classFullName); + if (f.exists()) { + jarArgs.add("-C"); + jarArgs.add(path); + jarArgs.add("."); + System.out.println("INFO: scheduled to jar " + path); + break; + } + } + + System.out.println("Running jar " + jarArgs.toString()); + sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); + if (!jarTool.run(jarArgs.toArray(new String[jarArgs.size()]))) { + throw new IOException("jar failed: args=" + jarArgs.toString()); + } + + manifestFile.delete(); + jar.deleteOnExit(); + + // Print content of jar file + System.out.println("Content of jar file" + jar.getAbsolutePath()); + + jarArgs = new ArrayList<>(); + jarArgs.add("-tvf"); + jarArgs.add(jar.getAbsolutePath()); + + jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); + if (!jarTool.run(jarArgs.toArray(new String[jarArgs.size()]))) { + throw new IOException("jar failed: args=" + jarArgs.toString()); + } + + return jar; + } + + public static void main(String args[]) { + LingeredApp.main(args); + } + } diff --git a/jdk/test/sun/tools/jps/TestJps.java b/jdk/test/sun/tools/jps/TestJps.java new file mode 100644 index 00000000000..f8a84261c81 --- /dev/null +++ b/jdk/test/sun/tools/jps/TestJps.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @library /lib/testlibrary /test/lib + * @modules jdk.jartool/sun.tools.jar + * @build LingeredAppForJps + * @build LingeredApp + * @run main/othervm TestJps + */ + + /* + * Notes: + * @modules tag is ignored in driver mode, so need main/othervm + * + * Launching the process with relative path to an app jar file is not tested + * + * This test resides in default package, so correct appearance + * of the full package name actually is not tested. + */ + +import java.util.List; +import java.io.File; + +public class TestJps { + + public static void testJpsClass() throws Throwable { + LingeredApp app = new LingeredAppForJps(); + try { + LingeredApp.startApp(JpsHelper.getVmArgs(), app); + JpsHelper.runJpsVariants(app.getPid(), + LingeredAppForJps.getProcessName(), LingeredAppForJps.getFullProcessName(), app.getLockFileName()); + + } finally { + LingeredApp.stopApp(app); + } + } + + public static void testJpsJar() throws Throwable { + // Get any jar exception as early as possible + File jar = LingeredAppForJps.buildJar(); + + // Jar created go to the main test + LingeredAppForJps app = new LingeredAppForJps(); + try { + LingeredAppForJps.startAppJar(JpsHelper.getVmArgs(), app, jar); + JpsHelper.runJpsVariants(app.getPid(), + LingeredAppForJps.getProcessName(jar), LingeredAppForJps.getFullProcessName(jar), app.getLockFileName()); + } finally { + LingeredAppForJps.stopApp(app); + } + + } + + public static void main(String[] args) throws Throwable { + testJpsClass(); + testJpsJar(); + } +} diff --git a/jdk/test/sun/tools/jps/TestJpsClass.java b/jdk/test/sun/tools/jps/TestJpsClass.java deleted file mode 100644 index 7cde3ce57b8..00000000000 --- a/jdk/test/sun/tools/jps/TestJpsClass.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.util.ArrayList; -import java.util.List; - -import jdk.testlibrary.OutputAnalyzer; -import jdk.testlibrary.ProcessTools; - -/* - * @test - * @summary The test application will be started with java class: - * java JpsBase - * For all possible combinations of jps arguments a jps process - * will be started from within the test application. - * The output should contain proper values. - * @library /lib/testlibrary - * @modules jdk.jartool/sun.tools.jar - * java.management - * @build jdk.testlibrary.* JpsHelper JpsBase - * @run driver TestJpsClass - */ -public class TestJpsClass { - - public static void main(String[] args) throws Throwable { - String testJdk = System.getProperty("test.jdk", "?"); - String testSrc = System.getProperty("test.src", "?"); - String testClassPath = System.getProperty("test.class.path", "?"); - - List cmd = new ArrayList<>(); - cmd.addAll(JpsHelper.getVmArgs()); - cmd.add("-Dtest.jdk=" + testJdk); - cmd.add("-Dtest.src=" + testSrc); - cmd.add("-cp"); - cmd.add(testClassPath); - cmd.add("JpsBase"); - cmd.add("monkey"); - - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()])); - OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); - System.out.println(output.getOutput()); - output.shouldHaveExitValue(0); - } - -} diff --git a/jdk/test/sun/tools/jps/TestJpsJar.java b/jdk/test/sun/tools/jps/TestJpsJar.java deleted file mode 100644 index 97d744ec85f..00000000000 --- a/jdk/test/sun/tools/jps/TestJpsJar.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import jdk.testlibrary.OutputAnalyzer; -import jdk.testlibrary.ProcessTools; - -/* - * @test - * @summary The test application will be started with absolute jar: - * java -jar /tmp/jtreg/jtreg-workdir/scratch/JpsBase.jar - * For all possible combinations of jps arguments a jps process - * will be started from within the test application. - * The output should contain proper values. - * @library /lib/testlibrary - * @modules jdk.jartool/sun.tools.jar - * java.management - * @build JpsHelper JpsBase - * @run main/othervm TestJpsJar - */ -public class TestJpsJar { - - public static void main(String[] args) throws Throwable { - String testJdk = System.getProperty("test.jdk", "?"); - String testSrc = System.getProperty("test.src", "?"); - File jar = JpsHelper.buildJar("JpsBase"); - - List cmd = new ArrayList<>(); - cmd.addAll(JpsHelper.getVmArgs()); - cmd.add("-Dtest.jdk=" + testJdk); - cmd.add("-Dtest.src=" + testSrc); - cmd.add("-Duser.dir=" + System.getProperty("user.dir")); - cmd.add("-jar"); - cmd.add(jar.getAbsolutePath()); - cmd.add("monkey"); - - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()])); - OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); - System.out.println(output.getOutput()); - output.shouldHaveExitValue(0); - } - -} diff --git a/jdk/test/sun/tools/jps/TestJpsJarRelative.java b/jdk/test/sun/tools/jps/TestJpsJarRelative.java deleted file mode 100644 index 12282959105..00000000000 --- a/jdk/test/sun/tools/jps/TestJpsJarRelative.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import jdk.testlibrary.OutputAnalyzer; -import jdk.testlibrary.ProcessTools; - -/* - * @test - * @summary The test application will be started with relative jar: - * java -jar ./JpsBase.jar - * For all possible combinations of jps arguments a jps process - * will be started from within the test application. - * The output should contain proper values. - * @library /lib/testlibrary - * @modules jdk.jartool/sun.tools.jar - * java.management - * @build jdk.testlibrary.* JpsHelper JpsBase - * @run main/othervm TestJpsJarRelative - */ -public class TestJpsJarRelative { - - public static void main(String[] args) throws Throwable { - String testJdk = System.getProperty("test.jdk", "?"); - String testSrc = System.getProperty("test.src", "?"); - File jar = JpsHelper.buildJar("JpsBase"); - - List cmd = new ArrayList<>(); - cmd.addAll(JpsHelper.getVmArgs()); - cmd.add("-Dtest.jdk=" + testJdk); - cmd.add("-Dtest.src=" + testSrc); - cmd.add("-jar"); - cmd.add("." + File.separator + jar.getName()); - cmd.add("monkey"); - - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(cmd.toArray(new String[cmd.size()])); - OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); - System.out.println(output.getOutput()); - output.shouldHaveExitValue(0); - } - -} diff --git a/jdk/test/sun/tools/jps/TestJpsSanity.java b/jdk/test/sun/tools/jps/TestJpsSanity.java index 47d15635961..fa1cf9e8c91 100644 --- a/jdk/test/sun/tools/jps/TestJpsSanity.java +++ b/jdk/test/sun/tools/jps/TestJpsSanity.java @@ -96,7 +96,7 @@ public class TestJpsSanity { } private static void testJpsUnknownHost() throws Exception { - String invalidHostName = "Oja781nh2ev7vcvbajdg-Sda1-C"; + String invalidHostName = "Oja781nh2ev7vcvbajdg-Sda1-C.invalid"; OutputAnalyzer output = JpsHelper.jps(invalidHostName); Asserts.assertNotEquals(output.getExitValue(), 0, "Exit code shouldn't be 0"); Asserts.assertFalse(output.getStderr().isEmpty(), "Error output should not be empty"); From 6e7ec59861c771894851de38955fc0833d292b32 Mon Sep 17 00:00:00 2001 From: Amit Sapre Date: Wed, 26 Oct 2016 15:08:29 +0530 Subject: [PATCH 016/402] 8151099: java.lang.management.ManagementFactory.getPlatformMXBeans() should work even if jdk.management is not present Removed dependency of java.management over jdk.management. Reviewed-by: mchung, dfuchs, dholmes --- .../sun/management/VMManagementImpl.java | 10 ++++- .../native/libmanagement/VMManagementImpl.c | 9 +---- ...bageCollectionNotificationContentTest.java | 21 ++-------- .../GarbageCollectionNotificationTest.java | 21 ++-------- .../DefaultManagementProviderTest.java | 38 +++++++++++++++++++ 5 files changed, 55 insertions(+), 44 deletions(-) create mode 100644 jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java diff --git a/jdk/src/java.management/share/classes/sun/management/VMManagementImpl.java b/jdk/src/java.management/share/classes/sun/management/VMManagementImpl.java index b0e4d44a540..595a6bf48f5 100644 --- a/jdk/src/java.management/share/classes/sun/management/VMManagementImpl.java +++ b/jdk/src/java.management/share/classes/sun/management/VMManagementImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,13 @@ class VMManagementImpl implements VMManagement { } public boolean isGcNotificationSupported() { - return gcNotificationSupport; + boolean isSupported = true; + try { + Class.forName("com.sun.management.GarbageCollectorMXBean"); + } catch (ClassNotFoundException x) { + isSupported = false; + } + return isSupported; } public boolean isRemoteDiagnosticCommandsSupported() { diff --git a/jdk/src/java.management/share/native/libmanagement/VMManagementImpl.c b/jdk/src/java.management/share/native/libmanagement/VMManagementImpl.c index 51136856536..38a5b6af0cc 100644 --- a/jdk/src/java.management/share/native/libmanagement/VMManagementImpl.c +++ b/jdk/src/java.management/share/native/libmanagement/VMManagementImpl.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -96,13 +96,6 @@ Java_sun_management_VMManagementImpl_initOptionalSupportFields value = mos.isRemoteDiagnosticCommandsSupported; setStaticBooleanField(env, cls, "remoteDiagnosticCommandsSupport", value); - - if ((jmm_version > JMM_VERSION_1_2) || - (jmm_version == JMM_VERSION_1_2 && ((jmm_version&0xFF) >= 1))) { - setStaticBooleanField(env, cls, "gcNotificationSupport", JNI_TRUE); - } else { - setStaticBooleanField(env, cls, "gcNotificationSupport", JNI_FALSE); - } } JNIEXPORT jobjectArray JNICALL diff --git a/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationContentTest.java b/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationContentTest.java index 10d10f40903..d5df6a34135 100644 --- a/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationContentTest.java +++ b/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationContentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,22 +72,9 @@ public class GarbageCollectionNotificationContentTest { public static void main(String[] args) throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - final Boolean isNotificationSupported = AccessController.doPrivileged (new PrivilegedAction() { - public Boolean run() { - try { - Class cl = Class.forName("sun.management.VMManagementImpl"); - Field f = cl.getDeclaredField("gcNotificationSupport"); - f.setAccessible(true); - return f.getBoolean(null); - } catch(ClassNotFoundException e) { - return false; - } catch(NoSuchFieldException e) { - return false; - } catch(IllegalAccessException e) { - return false; - } - } - }); + final boolean isNotificationSupported = + sun.management.ManagementFactoryHelper.getVMManagement().isGcNotificationSupported(); + if(!isNotificationSupported) { System.out.println("GC Notification not supported by the JVM, test skipped"); return; diff --git a/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationTest.java b/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationTest.java index 3bbfea44193..5c42827eb4d 100644 --- a/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationTest.java +++ b/jdk/test/com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,22 +71,9 @@ public class GarbageCollectionNotificationTest { public static void main(String[] args) throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - final Boolean isNotificationSupported = AccessController.doPrivileged (new PrivilegedAction() { - public Boolean run() { - try { - Class cl = Class.forName("sun.management.VMManagementImpl"); - Field f = cl.getDeclaredField("gcNotificationSupport"); - f.setAccessible(true); - return f.getBoolean(null); - } catch(ClassNotFoundException e) { - return false; - } catch(NoSuchFieldException e) { - return false; - } catch(IllegalAccessException e) { - return false; - } - } - }); + final boolean isNotificationSupported = + sun.management.ManagementFactoryHelper.getVMManagement().isGcNotificationSupported(); + if(!isNotificationSupported) { System.out.println("GC Notification not supported by the JVM, test skipped"); return; diff --git a/jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java b/jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java new file mode 100644 index 00000000000..70c41098eb3 --- /dev/null +++ b/jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8151099 + * @summary Verify platform MXBeans initialized properly with java.management + * module only. No other management provider + * @run main/othervm --limit-modules=java.management DefaultManagementProviderTest + */ +import java.lang.management.ManagementFactory; + +public class DefaultManagementProviderTest { + public static void main(String[] argv) { + ManagementFactory.getPlatformMBeanServer(); + System.out.println("Test case passed"); + } +} From 29871f6f8acc33a8caf345c3a212faf2b67ddae5 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Fri, 14 Oct 2016 14:47:27 -0700 Subject: [PATCH 017/402] 8166974: invokedynamic implementation should not wrap Errors Reviewed-by: smarks, jrose --- .../classes/java/lang/invoke/CallSite.java | 107 ++++++++++-------- .../java/lang/invoke/package-info.java | 25 ++-- .../invoke/8022701/InvokeSeveralWays.java | 30 ++--- 3 files changed, 82 insertions(+), 80 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/CallSite.java b/jdk/src/java.base/share/classes/java/lang/invoke/CallSite.java index df245e661e9..c24f94951f0 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/CallSite.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/CallSite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -272,7 +272,7 @@ public class CallSite { MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget); } - // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite: + // this implements the upcall from the JVM, MethodHandleNatives.linkCallSite: static CallSite makeSite(MethodHandle bootstrapMethod, // Callee information: String name, MethodType type, @@ -293,59 +293,72 @@ public class CallSite { Object[] argv = (Object[]) info; maybeReBoxElements(argv); switch (argv.length) { - case 0: - binding = bootstrapMethod.invoke(caller, name, type); - break; - case 1: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0]); - break; - case 2: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0], argv[1]); - break; - case 3: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0], argv[1], argv[2]); - break; - case 4: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0], argv[1], argv[2], argv[3]); - break; - case 5: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0], argv[1], argv[2], argv[3], argv[4]); - break; - case 6: - binding = bootstrapMethod.invoke(caller, name, type, - argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); - break; - default: - final int NON_SPREAD_ARG_COUNT = 3; // (caller, name, type) - if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY) - throw new BootstrapMethodError("too many bootstrap method arguments"); - MethodType bsmType = bootstrapMethod.type(); - MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length); - MethodHandle typedBSM = bootstrapMethod.asType(invocationType); - MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT); - binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv); + case 0: + binding = bootstrapMethod.invoke(caller, name, type); + break; + case 1: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0]); + break; + case 2: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0], argv[1]); + break; + case 3: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0], argv[1], argv[2]); + break; + case 4: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0], argv[1], argv[2], argv[3]); + break; + case 5: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0], argv[1], argv[2], argv[3], argv[4]); + break; + case 6: + binding = bootstrapMethod.invoke(caller, name, type, + argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); + break; + default: + final int NON_SPREAD_ARG_COUNT = 3; // (caller, name, type) + if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY) + throw new BootstrapMethodError("too many bootstrap method arguments"); + MethodType bsmType = bootstrapMethod.type(); + MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length); + MethodHandle typedBSM = bootstrapMethod.asType(invocationType); + MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT); + binding = spreader.invokeExact(typedBSM, (Object) caller, (Object) name, (Object) type, argv); } } - //System.out.println("BSM for "+name+type+" => "+binding); if (binding instanceof CallSite) { site = (CallSite) binding; - } else { + } else { + // See the "Linking Exceptions" section for the invokedynamic + // instruction in JVMS 6.5. + // Throws a runtime exception defining the cause that is then + // in the "catch (Throwable ex)" a few lines below wrapped in + // BootstrapMethodError throw new ClassCastException("bootstrap method failed to produce a CallSite"); } - if (!site.getTarget().type().equals(type)) + if (!site.getTarget().type().equals(type)) { + // See the "Linking Exceptions" section for the invokedynamic + // instruction in JVMS 6.5. + // Throws a runtime exception defining the cause that is then + // in the "catch (Throwable ex)" a few lines below wrapped in + // BootstrapMethodError throw wrongTargetType(site.getTarget(), type); + } + } catch (Error e) { + // Pass through an Error, including BootstrapMethodError, any other + // form of linkage error, such as IllegalAccessError if the bootstrap + // method is inaccessible, or say ThreadDeath/OutOfMemoryError + // See the "Linking Exceptions" section for the invokedynamic + // instruction in JVMS 6.5. + throw e; } catch (Throwable ex) { - BootstrapMethodError bex; - if (ex instanceof BootstrapMethodError) - bex = (BootstrapMethodError) ex; - else - bex = new BootstrapMethodError("call site initialization exception", ex); - throw bex; + // Wrap anything else in BootstrapMethodError + throw new BootstrapMethodError("call site initialization exception", ex); } return site; } diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/package-info.java b/jdk/src/java.base/share/classes/java/lang/invoke/package-info.java index a6d8e41c48c..ba1d84a8911 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/package-info.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,20 +84,21 @@ * * Invocation is as if by * {@link java.lang.invoke.MethodHandle#invoke MethodHandle.invoke}. - * The returned result must be a {@link java.lang.invoke.CallSite CallSite} (or a subclass). + * The returned result must be a {@link java.lang.invoke.CallSite CallSite} + * (or a subclass), otherwise a + * {@link java.lang.BootstrapMethodError BootstrapMethodError} is thrown. * The type of the call site's target must be exactly equal to the type * derived from the dynamic call site's type descriptor and passed to - * the bootstrap method. - * The call site then becomes permanently linked to the dynamic call site. + * the bootstrap method, otherwise a {@code BootstrapMethodError} is thrown. + * On success the call site then becomes permanently linked to the dynamic call + * site. *

    - * As documented in the JVM specification, all failures arising from - * the linkage of a dynamic call site are reported - * by a {@link java.lang.BootstrapMethodError BootstrapMethodError}, - * which is thrown as the abnormal termination of the dynamic call - * site execution. - * If this happens, the same error will the thrown for all subsequent - * attempts to execute the dynamic call site. - * + * If an exception, {@code E} say, occurs when linking the call site then the + * linkage fails and terminates abnormally. {@code E} is rethrown if the type of + * {@code E} is {@code Error} or a subclass, otherwise a + * {@code BootstrapMethodError} that wraps {@code E} is thrown. + * If this happens, the same {@code Error} or subclass will the thrown for all + * subsequent attempts to execute the dynamic call site. *

    timing of linkage

    * A dynamic call site is linked just before its first execution. * The bootstrap method call implementing the linkage occurs within diff --git a/jdk/test/java/lang/invoke/8022701/InvokeSeveralWays.java b/jdk/test/java/lang/invoke/8022701/InvokeSeveralWays.java index 011ae7f43a5..c3d60b0374d 100644 --- a/jdk/test/java/lang/invoke/8022701/InvokeSeveralWays.java +++ b/jdk/test/java/lang/invoke/8022701/InvokeSeveralWays.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,18 +37,11 @@ public class InvokeSeveralWays { failures++; } catch (InvocationTargetException e) { Throwable c = e.getCause(); - if (BootstrapMethodError.class.isInstance(c)) { - c = c.getCause(); - if (expected.isInstance(c)) - System.out.println("EXPECTED: " + expected.getName() + ", "+ c); - else { - failures++; - System.out.println("FAIL: Unexpected wrapped exception " + c); - e.printStackTrace(System.out); - } - } else { + if (expected.isInstance(c)) + System.out.println("EXPECTED: " + expected.getName() + ", "+ c); + else { failures++; - System.out.println("FAIL: Exception from MethodHandle invocation not wrapped in BootstrapMethodError " + c); + System.out.println("FAIL: Unexpected wrapped exception " + c); e.printStackTrace(System.out); } } catch (Throwable e) { @@ -80,19 +73,14 @@ public class InvokeSeveralWays { Invoker.invoke(); System.out.println("FAIL: No exception throw, probably failed to load modified bytecodes for MethodSupplier"); failures++; - } catch (BootstrapMethodError e) { - Throwable c = e.getCause(); - if (expected.isInstance(c)) - System.out.println("EXPECTED: " + expected.getName() + ", "+ c); + } catch (Throwable e) { + if (expected.isInstance(e)) + System.out.println("EXPECTED: " + expected.getName() + ", "+ e); else { failures++; - System.out.println("FAIL: Unexpected exception has been caught " + c); + System.out.println("FAIL: Unexpected exception has been caught " + e); e.printStackTrace(System.out); } - } catch (Throwable e) { - failures++; - System.out.println("FAIL: Exception from MethodHandle invocation not wrapped in BootstrapMethodError " + e); - e.printStackTrace(System.out); } System.out.println(); try { From 0d6e939abfe6462f3b7463381fbb631dc563f9e0 Mon Sep 17 00:00:00 2001 From: Dmitrij Pochepko Date: Thu, 20 Oct 2016 16:53:35 +0300 Subject: [PATCH 018/402] 8155219: [TESTBUG] Rewrite compiler/ciReplay/TestVM.sh in java Reviewed-by: kvn --- test/jtreg-ext/requires/VMProps.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/jtreg-ext/requires/VMProps.java b/test/jtreg-ext/requires/VMProps.java index 644c8cd366c..5c088b6008a 100644 --- a/test/jtreg-ext/requires/VMProps.java +++ b/test/jtreg-ext/requires/VMProps.java @@ -59,6 +59,7 @@ public class VMProps implements Callable> { map.put("vm.bits", vmBits()); map.put("vm.flightRecorder", vmFlightRecorder()); map.put("vm.simpleArch", vmArch()); + map.put("vm.debug", vmDebug()); vmGC(map); // vm.gc.X = true/false dump(map); @@ -147,6 +148,13 @@ public class VMProps implements Callable> { return "false"; } + /** + * @return debug level value extracted from the "jdk.debug" property. + */ + protected String vmDebug() { + return "" + System.getProperty("jdk.debug").contains("debug"); + } + /** * For all existing GC sets vm.gc.X property. * Example vm.gc.G1=true means: From 5320830885ca1c535f911929dc67bbc8c1492dd9 Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Fri, 21 Oct 2016 15:40:47 +0200 Subject: [PATCH 019/402] 8168412: Reduce buffering in jtreg timeouthandler Reviewed-by: mlarsson --- .../share/classes/jdk/test/failurehandler/HtmlSection.java | 2 +- .../failurehandler/jtreg/GatherDiagnosticInfoObserver.java | 4 ++-- .../jtreg/GatherProcessInfoTimeoutHandler.java | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java index 0597fe7b206..d20b13360a5 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/HtmlSection.java @@ -49,7 +49,7 @@ public class HtmlSection { private HtmlSection(PrintWriter pw, String id, String name, HtmlSection rootSection) { this.pw = pw; - textWriter = new PrintWriter(new HtmlFilterWriter(pw)); + textWriter = new PrintWriter(new HtmlFilterWriter(pw), true); this.id = id; this.name = name; child = null; diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java index 5eb67163f80..7a14d3797fc 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java @@ -68,7 +68,7 @@ public class GatherDiagnosticInfoObserver implements Harness.Observer { boolean needClose = false; try { log = new PrintWriter(new FileWriter( - workDir.resolve(LOG_FILENAME).toFile(), true)); + workDir.resolve(LOG_FILENAME).toFile(), true), true); needClose = true; } catch (IOException e) { log = new PrintWriter(System.out); @@ -100,7 +100,7 @@ public class GatherDiagnosticInfoObserver implements Harness.Observer { EnvironmentInfoGatherer gatherer) { File output = workDir.resolve(ENVIRONMENT_OUTPUT).toFile(); try (HtmlPage html = new HtmlPage(new PrintWriter( - new FileWriter(output, true)))) { + new FileWriter(output, true), true))) { try (ElapsedTimePrinter timePrinter = new ElapsedTimePrinter(new Stopwatch(), name, log)) { gatherer.gatherEnvironmentInfo(html.getRootSection()); diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java index 10c0580dc50..767e86648b8 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherProcessInfoTimeoutHandler.java @@ -70,9 +70,9 @@ public class GatherProcessInfoTimeoutHandler extends TimeoutHandler { String name = getClass().getName(); PrintWriter actionsLog; try { - // try to open a separate file for aciton log + // try to open a separate file for action log actionsLog = new PrintWriter(new FileWriter( - workDir.resolve(LOG_FILENAME).toFile(), true)); + workDir.resolve(LOG_FILENAME).toFile(), true), true); } catch (IOException e) { // use jtreg log as a fallback actionsLog = log; @@ -84,7 +84,7 @@ public class GatherProcessInfoTimeoutHandler extends TimeoutHandler { File output = workDir.resolve(OUTPUT_FILENAME).toFile(); try { - PrintWriter pw = new PrintWriter(new FileWriter(output, true)); + PrintWriter pw = new PrintWriter(new FileWriter(output, true), true); runGatherer(name, workDir, actionsLog, pw, pid); } catch (IOException e) { actionsLog.printf("IOException: cannot open output file[%s] : %s", From b32098e9d5179133f424b9388485d05d825b3b61 Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Mon, 24 Oct 2016 09:07:57 +0200 Subject: [PATCH 020/402] 8168483: Remove jtreg timeout handler timeout Reviewed-by: dholmes, tbell --- nashorn/test/Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nashorn/test/Makefile b/nashorn/test/Makefile index 00e2e8649ef..6d6eb008577 100644 --- a/nashorn/test/Makefile +++ b/nashorn/test/Makefile @@ -130,7 +130,8 @@ ifneq ($(FAILURE_HANDLER_DIR), ) -timeoutHandlerDir:$(FAILURE_HANDLER_DIR_MIXED)/jtregFailureHandler.jar \ -observerDir:$(FAILURE_HANDLER_DIR_MIXED)/jtregFailureHandler.jar \ -timeoutHandler:jdk.test.failurehandler.jtreg.GatherProcessInfoTimeoutHandler \ - -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver + -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver \ + -timeoutHandlerTimeout:0 ifeq ($(UNAME_S), CYGWIN) JTREG_FAILURE_HANDLER_OPTIONS += -J-Djava.library.path="$(FAILURE_HANDLER_DIR_MIXED)" endif From 6594e9ed4071f2267b75d6629317a7a27eedf404 Mon Sep 17 00:00:00 2001 From: Staffan Larsen Date: Mon, 24 Oct 2016 09:12:40 +0200 Subject: [PATCH 021/402] 8168414: Various timeouthandler fixes Reviewed-by: mlarsson --- test/failure_handler/Makefile | 3 +- .../failurehandler/action/ActionHelper.java | 40 ++++++++++--------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/test/failure_handler/Makefile b/test/failure_handler/Makefile index 49352cbc762..d8c71964bdc 100644 --- a/test/failure_handler/Makefile +++ b/test/failure_handler/Makefile @@ -86,7 +86,7 @@ classes: require_env test: require_env build rm -rf "${RUN_DIR}" mkdir -p "${RUN_DIR}" - "${JTREG_HOME}"/bin/jtreg \ + "${JTREG_HOME}"/bin/jtreg \ -jdk:"${JAVA_HOME}" \ ${JTREG_TEST_OPTS} \ -timeout:0.1 -va -retain:all \ @@ -94,6 +94,7 @@ test: require_env build -agentvm \ -thd:"${TARGET_JAR}" \ -th:jdk.test.failurehandler.jtreg.GatherProcessInfoTimeoutHandler \ + -thtimeout:0 \ -od:"${TARGET_JAR}" \ -o:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver \ -w:"${RUN_DIR}/JTwork" \ diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java index 6a8ae037ea4..8b2d2757ce7 100644 --- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java +++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java @@ -164,7 +164,8 @@ public class ActionHelper { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); - log.printf("%s%n[%tF % Date: Tue, 25 Oct 2016 14:49:48 +0300 Subject: [PATCH 022/402] 8165500: TestJpsJar shouldn't jar all test.classpath directories Refactor test to better handle errors Reviewed-by: sspitsyn --- test/lib/jdk/test/lib/apps/LingeredApp.java | 69 ++++++++++++++------- 1 file changed, 47 insertions(+), 22 deletions(-) diff --git a/test/lib/jdk/test/lib/apps/LingeredApp.java b/test/lib/jdk/test/lib/apps/LingeredApp.java index ac375b62faf..8632a835695 100644 --- a/test/lib/jdk/test/lib/apps/LingeredApp.java +++ b/test/lib/jdk/test/lib/apps/LingeredApp.java @@ -67,13 +67,14 @@ import java.util.UUID; public class LingeredApp { private static final long spinDelay = 1000; - private static final int appWaitTime = 100; - private final String lockFileName; private long lockCreationTime; - private Process appProcess; private final ArrayList storedAppOutput; + protected Process appProcess; + protected static final int appWaitTime = 100; + protected final String lockFileName; + /* * Drain child process output, store it into string array */ @@ -255,14 +256,10 @@ public class LingeredApp { } /** - * Run the app - * - * @param vmArguments - * @throws IOException + * Analyze an environment and prepare a command line to + * run the app, app name should be added explicitly */ - public void runApp(List vmArguments) - throws IOException { - + public List runAppPrepare(List vmArguments) { // We should always use testjava or throw an exception, // so we can't use JDKToolFinder.getJDKTool("java"); // that falls back to compile java on error @@ -303,28 +300,52 @@ public class LingeredApp { String classpath = System.getProperty("test.class.path"); cmd.add((classpath == null) ? "." : classpath); - cmd.add(this.getAppName()); - cmd.add(lockFileName); + return cmd; + } - // Reporting + /** + * Assemble command line to a printable string + */ + public void printCommandLine(List cmd) { + // A bit of verbosity StringBuilder cmdLine = new StringBuilder(); for (String strCmd : cmd) { cmdLine.append("'").append(strCmd).append("' "); } - // A bit of verbosity System.out.println("Command line: [" + cmdLine.toString() + "]"); + } + + public void startGobblerPipe() { + // Create pipe reader for process, and read stdin and stderr to array of strings + InputGobbler gb = new InputGobbler(appProcess.getInputStream(), storedAppOutput); + gb.start(); + } + + /** + * Run the app. + * + * @param vmArguments + * @throws IOException + */ + public void runApp(List vmArguments) + throws IOException { + + List cmd = runAppPrepare(vmArguments); + + cmd.add(this.getAppName()); + cmd.add(lockFileName); + + printCommandLine(cmd); ProcessBuilder pb = new ProcessBuilder(cmd); // we don't expect any error output but make sure we are not stuck on pipe // pb.redirectErrorStream(false); + // ProcessBuilder.start can throw IOException pb.redirectError(ProcessBuilder.Redirect.INHERIT); - appProcess = pb.start(); - // Create pipe reader for process, and read stdin and stderr to array of strings - InputGobbler gb = new InputGobbler(appProcess.getInputStream(), storedAppOutput); - gb.start(); + startGobblerPipe(); } /** @@ -334,10 +355,14 @@ public class LingeredApp { */ public void stopApp() throws IOException { deleteLock(); - waitAppTerminate(); - int exitcode = appProcess.exitValue(); - if (exitcode != 0) { - throw new IOException("LingeredApp terminated with non-zero exit code " + exitcode); + // The startApp() of the derived app can throw + // an exception before the LA actually starts + if (appProcess != null) { + waitAppTerminate(); + int exitcode = appProcess.exitValue(); + if (exitcode != 0) { + throw new IOException("LingeredApp terminated with non-zero exit code " + exitcode); + } } } From f22ecd235aad16f05c05a2146ad720b4907c8957 Mon Sep 17 00:00:00 2001 From: Sharath Ballal Date: Fri, 28 Oct 2016 11:18:54 +0300 Subject: [PATCH 023/402] 8168397: sun/tools/jhsdb/HeapDumpTest.java timesout on MacOS X on non images build Remove BasicLauncherTest.java and HeapDumpTest.java from quarantine list. Reviewed-by: sla, dsamersoff --- jdk/test/ProblemList.txt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index ccdd124fb02..2aaf2505219 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -285,10 +285,6 @@ java/util/BitSet/BitSetStreamTest.java 8079538 generic- sun/tools/jcmd/TestJcmdSanity.java 8031482 windows-all -sun/tools/jhsdb/BasicLauncherTest.java 8159806 macosx-all - -sun/tools/jhsdb/HeapDumpTest.java 8168397 macosx-all - sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java 8057732 generic-all demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java 8151899 generic-all From ff33d165a6a99c9daab3f8cde0797ba256ffe7da Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Tue, 1 Nov 2016 17:20:45 -0700 Subject: [PATCH 024/402] 8163553: java.lang.LinkageError from test java/lang/ThreadGroup/Stop.java Reviewed-by: redestad --- .../java/lang/invoke/BoundMethodHandle.java | 22 ++++++++----------- .../lang/invoke/InvokerBytecodeGenerator.java | 2 +- .../classes/java/lang/invoke/LambdaForm.java | 6 ++++- .../java/lang/invoke/MethodHandle.java | 2 +- .../java/lang/invoke/MethodHandleNatives.java | 10 +++++---- .../java/lang/invoke/MethodHandleStatics.java | 6 ++--- .../java/lang/invoke/StringConcatFactory.java | 7 ++++-- 7 files changed, 30 insertions(+), 25 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java b/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java index 395e80ca6b0..cec436690b9 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java @@ -80,7 +80,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; default : throw newInternalError("unexpected xtype: " + xtype); } } catch (Throwable t) { - throw newInternalError(t); + throw uncaughtException(t); } } @@ -188,7 +188,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this); } } catch (Throwable ex) { - throw newInternalError(ex); + throw uncaughtException(ex); } throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i); } @@ -408,18 +408,14 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; */ static boolean speciesDataCachePopulated() { Class rootCls = BoundMethodHandle.class; - try { - for (Class c : rootCls.getDeclaredClasses()) { - if (rootCls.isAssignableFrom(c)) { - final Class cbmh = c.asSubclass(BoundMethodHandle.class); - SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh); - assert(d != null) : cbmh.getName(); - assert(d.clazz == cbmh); - assert(CACHE.get(d.typeChars) == d); - } + for (Class c : rootCls.getDeclaredClasses()) { + if (rootCls.isAssignableFrom(c)) { + final Class cbmh = c.asSubclass(BoundMethodHandle.class); + SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh); + assert(d != null) : cbmh.getName(); + assert(d.clazz == cbmh); + assert(CACHE.get(d.typeChars) == d); } - } catch (Throwable e) { - throw newInternalError(e); } return true; } diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java index ea6236aa2d9..d903d488211 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java @@ -1021,7 +1021,7 @@ class InvokerBytecodeGenerator { try { emptyArray = name.function.resolvedHandle().invoke(); } catch (Throwable ex) { - throw newInternalError(ex); + throw uncaughtException(ex); } assert(java.lang.reflect.Array.getLength(emptyArray) == 0); assert(emptyArray.getClass() == rtype); // exact typing diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java index bcc825bcf15..96b0a944800 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java @@ -855,7 +855,11 @@ class LambdaForm { System.out.println("LambdaForm compilation failed: " + this); bge.printStackTrace(System.out); } - } catch (Error | Exception e) { + } catch (Error e) { + // Pass through any error + throw e; + } catch (Exception e) { + // Wrap any exception throw newInternalError(this.toString(), e); } } diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandle.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandle.java index 13a3e0a990e..6265b874175 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandle.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandle.java @@ -957,7 +957,7 @@ assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray if (!fail) return needType; // elicit an error: this.asType(needType); - throw newInternalError("should not return", null); + throw newInternalError("should not return"); } private void spreadArrayChecks(Class arrayType, int arrayLength) { diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java index b364a3e5ace..1065b8d1482 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java @@ -379,11 +379,13 @@ class MethodHandleNatives { name, fixMethodType(callerClass, type), appendixResult); } } + } catch (Error e) { + // Pass through an Error, including say StackOverflowError or + // OutOfMemoryError + throw e; } catch (Throwable ex) { - if (ex instanceof LinkageError) - throw (LinkageError) ex; - else - throw new LinkageError(ex.getMessage(), ex); + // Wrap anything else in LinkageError + throw new LinkageError(ex.getMessage(), ex); } throw new LinkageError("no such method "+defc.getName()+"."+name+type); } diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java index 22408f1b55a..f05cdda8166 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java @@ -107,10 +107,10 @@ import java.util.Properties; /*non-public*/ static InternalError newInternalError(String message) { return new InternalError(message); } - /*non-public*/ static InternalError newInternalError(String message, Throwable cause) { + /*non-public*/ static InternalError newInternalError(String message, Exception cause) { return new InternalError(message, cause); } - /*non-public*/ static InternalError newInternalError(Throwable cause) { + /*non-public*/ static InternalError newInternalError(Exception cause) { return new InternalError(cause); } /*non-public*/ static RuntimeException newIllegalStateException(String message) { @@ -132,7 +132,7 @@ import java.util.Properties; /*non-public*/ static Error uncaughtException(Throwable ex) { if (ex instanceof Error) throw (Error) ex; if (ex instanceof RuntimeException) throw (RuntimeException) ex; - throw newInternalError("uncaught exception", ex); + throw new InternalError("uncaught exception", ex); } private static String message(String message, Object obj) { if (obj != null) message = message + ": " + obj; diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java b/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java index 4b336f4c6b1..6c94fb3eb36 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java @@ -723,6 +723,9 @@ public final class StringConcatFactory { default: throw new StringConcatException("Concatenation strategy " + STRATEGY + " is not implemented"); } + } catch (Error | StringConcatException e) { + // Pass through any error or existing StringConcatException + throw e; } catch (Throwable t) { throw new StringConcatException("Generator failed", t); } @@ -1092,9 +1095,9 @@ public final class StringConcatFactory { UNSAFE.ensureClassInitialized(innerClass); dumpIfEnabled(innerClass.getName(), classBytes); return Lookup.IMPL_LOOKUP.findStatic(innerClass, METHOD_NAME, args); - } catch (Throwable e) { + } catch (Exception e) { dumpIfEnabled(className + "$$FAILED", classBytes); - throw new StringConcatException("Error while spinning the class", e); + throw new StringConcatException("Exception while spinning the class", e); } } From 46ce08f254444e11aed3a4da1cdd98a0c0ba27c0 Mon Sep 17 00:00:00 2001 From: Prem Balakrishnan Date: Wed, 2 Nov 2016 08:46:41 +0530 Subject: [PATCH 025/402] 8159132: [PIT][TEST_BUG] java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java fails Reviewed-by: alexsch, aghaisas --- .../FileDialogIconTest.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java b/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java index 5ff6343640e..055386b170f 100644 --- a/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java +++ b/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java @@ -22,21 +22,28 @@ */ /* @test - * @bug 8157163 + * @bug 8157163 8159132 * @summary AWT FileDialog does not inherit icon image from parent Frame * @requires os.family=="windows" * @run main FileDialogIconTest */ -import javax.swing.*; -import java.awt.*; + +import java.awt.Color; +import java.awt.Dialog; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Image; import java.awt.image.BufferedImage; -import java.lang.reflect.InvocationTargetException; +import javax.swing.SwingUtilities; public class FileDialogIconTest { private static Frame frame; private static Dialog dialog; - public static void main(final String[] args) throws InterruptedException, InvocationTargetException, AWTException { + public static void main(final String[] args) throws Exception { Robot robot; Point p; try { @@ -51,9 +58,9 @@ public class FileDialogIconTest { dialog.setModal(false); dialog.setVisible(true); robot.waitForIdle(); - robot.delay(200); + robot.delay(1000); - p = new Point(10, 10); + p = new Point(20, 20); SwingUtilities.convertPointToScreen(p, dialog); Color color = robot.getPixelColor(p.x, p.y); if (!Color.RED.equals(color)) { From b86962aeb834687d8fee34fbcba12776225f0662 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 2 Nov 2016 17:14:57 +0300 Subject: [PATCH 026/402] 8168998: Incorrect implementation of equals in Encoding and Type in JavaSound Reviewed-by: prr, amenkov --- .../javax/sound/sampled/AudioFileFormat.java | 22 ++++---- .../javax/sound/sampled/AudioFormat.java | 22 ++++---- .../AudioFileFormat/TypeEqualsToNull.java | 50 +++++++++++++++++++ .../AudioFormat/EncodingEqualsToNull.java | 50 +++++++++++++++++++ 4 files changed, 120 insertions(+), 24 deletions(-) create mode 100644 jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java create mode 100644 jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java diff --git a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java index b88dfccb44b..fafddcd0f43 100644 --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ package javax.sound.sampled; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * An instance of the {@code AudioFileFormat} class describes an audio file, @@ -344,7 +345,7 @@ public class AudioFileFormat { * @param extension the string that commonly marks the file type * without leading dot */ - public Type(String name, String extension) { + public Type(final String name, final String extension) { this.name = name; this.extension = extension; } @@ -353,14 +354,14 @@ public class AudioFileFormat { * Finalizes the equals method. */ @Override - public final boolean equals(Object obj) { - if (toString() == null) { - return (obj != null) && (obj.toString() == null); + public final boolean equals(final Object obj) { + if (this == obj) { + return true; } - if (obj instanceof Type) { - return toString().equals(obj.toString()); + if (!(obj instanceof Type)) { + return false; } - return false; + return Objects.equals(name, ((Type) obj).name); } /** @@ -368,10 +369,7 @@ public class AudioFileFormat { */ @Override public final int hashCode() { - if (toString() == null) { - return 0; - } - return toString().hashCode(); + return name != null ? name.hashCode() : 0; } /** diff --git a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java index 474e1cf5516..38cadf49354 100644 --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ package javax.sound.sampled; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * {@code AudioFormat} is the class that specifies a particular arrangement of @@ -599,7 +600,7 @@ public class AudioFormat { * * @param name the name of the new type of encoding */ - public Encoding(String name) { + public Encoding(final String name) { this.name = name; } @@ -607,14 +608,14 @@ public class AudioFormat { * Finalizes the equals method. */ @Override - public final boolean equals(Object obj) { - if (toString() == null) { - return (obj != null) && (obj.toString() == null); + public final boolean equals(final Object obj) { + if (this == obj) { + return true; } - if (obj instanceof Encoding) { - return toString().equals(obj.toString()); + if (!(obj instanceof Encoding)) { + return false; } - return false; + return Objects.equals(name, ((Encoding) obj).name); } /** @@ -622,10 +623,7 @@ public class AudioFormat { */ @Override public final int hashCode() { - if (toString() == null) { - return 0; - } - return toString().hashCode(); + return name != null ? name.hashCode() : 0; } /** diff --git a/jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java b/jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java new file mode 100644 index 00000000000..5d37a137141 --- /dev/null +++ b/jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.sound.sampled.AudioFileFormat; + +/** + * @test + * @bug 8168998 + */ +public final class TypeEqualsToNull { + + public static void main(final String[] args) { + final AudioFileFormat.Type type; + try { + type = new AudioFileFormat.Type(null, null); + } catch (final Exception ignored) { + // behaviour of null is not specified so ignore possible exceptions + return; + } + final Object stub = new Object() { + @Override + public String toString() { + return null; + } + }; + if (stub.equals(type) || type.equals(stub)) { + throw new RuntimeException("Should not be equal"); + } + } +} diff --git a/jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java b/jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java new file mode 100644 index 00000000000..0a53cfa1edb --- /dev/null +++ b/jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.sound.sampled.AudioFormat; + +/** + * @test + * @bug 8168998 + */ +public final class EncodingEqualsToNull { + + public static void main(final String[] args) { + final AudioFormat.Encoding enc; + try { + enc = new AudioFormat.Encoding(null); + } catch (final Exception ignored) { + // behaviour of null is not specified so ignore possible exceptions + return; + } + final Object stub = new Object() { + @Override + public String toString() { + return null; + } + }; + if (stub.equals(enc) || enc.equals(stub)) { + throw new RuntimeException("Should not be equal"); + } + } +} From b968404588438a2544c0f7c662ebeb139d7dd64f Mon Sep 17 00:00:00 2001 From: Pete Brunet Date: Wed, 2 Nov 2016 09:44:01 -0700 Subject: [PATCH 027/402] 8167213: Re-examine the alternative to deliver include/bridge/AccessBridgeCalls.c Remove AccessBridgeCalls.c from the include directory Reviewed-by: prr, erikj, mchung, alexsch --- jdk/make/copy/Copy-jdk.accessibility.gmk | 5 +- .../launcher/Launcher-jdk.accessibility.gmk | 6 +- jdk/make/lib/Lib-jdk.accessibility.gmk | 6 +- .../{include => }/bridge/AccessBridgeCalls.c | 57 +++++++++---------- .../include/bridge/AccessBridgeCallbacks.h | 6 +- .../native/include/bridge/AccessBridgeCalls.h | 21 ++++++- 6 files changed, 57 insertions(+), 44 deletions(-) rename jdk/src/jdk.accessibility/windows/native/{include => }/bridge/AccessBridgeCalls.c (96%) diff --git a/jdk/make/copy/Copy-jdk.accessibility.gmk b/jdk/make/copy/Copy-jdk.accessibility.gmk index ec8623765bc..f3c136b8466 100644 --- a/jdk/make/copy/Copy-jdk.accessibility.gmk +++ b/jdk/make/copy/Copy-jdk.accessibility.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2104, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2104, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -30,8 +30,7 @@ include CopyCommon.gmk ifeq ($(OPENJDK_TARGET_OS), windows) TARGETS += $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCallbacks.h \ $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.h \ - $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgePackages.h \ - $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.c + $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgePackages.h $(INCLUDE_DST_OS_DIR)/bridge/%: \ $(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge/% diff --git a/jdk/make/launcher/Launcher-jdk.accessibility.gmk b/jdk/make/launcher/Launcher-jdk.accessibility.gmk index 6815e6d378d..914b9464909 100644 --- a/jdk/make/launcher/Launcher-jdk.accessibility.gmk +++ b/jdk/make/launcher/Launcher-jdk.accessibility.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) $$(eval $$(call SetupNativeCompilation, BUILD_JACCESSINSPECTOR$1, \ SRC := $(TOPDIR)/jaccessinspector $(TOPDIR)/common \ - $(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \ + $(TOPDIR)/toolscommon $(TOPDIR)/bridge, \ CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \ LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \ LIBS := advapi32.lib user32.lib, \ @@ -98,7 +98,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) $$(eval $$(call SetupNativeCompilation,BUILD_JACCESSWALKER$1, \ SRC := $(TOPDIR)/jaccesswalker $(TOPDIR)/common \ - $(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \ + $(TOPDIR)/toolscommon $(TOPDIR)/bridge, \ CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \ LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \ LIBS := advapi32.lib comctl32.lib gdi32.lib user32.lib, \ diff --git a/jdk/make/lib/Lib-jdk.accessibility.gmk b/jdk/make/lib/Lib-jdk.accessibility.gmk index 565b76a9e8a..542b20f925b 100644 --- a/jdk/make/lib/Lib-jdk.accessibility.gmk +++ b/jdk/make/lib/Lib-jdk.accessibility.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -48,7 +48,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) $(ACCESSBRIDGE_CFLAGS) \ $(addprefix -I,$(JAVA_AB_SRCDIR)) \ - -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \ + -I$(ROOT_SRCDIR)/include/bridge \ -DACCESSBRIDGE_ARCH_$2, \ LDFLAGS := $(LDFLAGS_JDKLIB) -subsystem:windows, \ LIBS := kernel32.lib user32.lib gdi32.lib \ @@ -78,7 +78,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) OPTIMIZATION := LOW, \ CFLAGS := $(filter-out -MD, $(CFLAGS_JDKLIB)) -MT $(ACCESSBRIDGE_CFLAGS) \ $(addprefix -I,$(WIN_AB_SRCDIR)) \ - -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \ + -I$(ROOT_SRCDIR)/include/bridge \ -DACCESSBRIDGE_ARCH_$2, \ LDFLAGS := $(LDFLAGS_JDKLIB) -subsystem:windows \ -def:$(ROOT_SRCDIR)/libwindowsaccessbridge/WinAccessBridge.DEF, \ diff --git a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.c b/jdk/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c similarity index 96% rename from jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.c rename to jdk/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c index dc3d1019b51..105f342afdb 100644 --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.c +++ b/jdk/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c @@ -1,30 +1,33 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * - * 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). + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: * - * 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. + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @(#)AccessBridgeCalls.c 1.25 05/08/22 + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* @@ -40,7 +43,6 @@ //#define ACCESSBRIDGE_64 #include "AccessBridgeCalls.h" -#include "AccessBridgeDebug.h" #ifdef __cplusplus extern "C" { @@ -52,21 +54,19 @@ extern "C" { BOOL theAccessBridgeInitializedFlag = FALSE; #define LOAD_FP(result, type, name) \ - PrintDebugString("LOAD_FP loading: %s ...", name); \ if ((theAccessBridge.result = \ (type) GetProcAddress(theAccessBridgeInstance, name)) == (type) 0) { \ - PrintDebugString("LOAD_FP failed: %s", name); \ return FALSE; \ } BOOL initializeAccessBridge() { -#ifdef ACCESSBRIDGE_ARCH_32 // For 32bit AT new bridge +#ifdef ACCESSBRIDGE_ARCH_32 // For 32 bit AT interfacing with Java on 64 bit OS theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-32"); #else -#ifdef ACCESSBRIDGE_ARCH_64 // For 64bit AT new bridge +#ifdef ACCESSBRIDGE_ARCH_64 // For 64 bit AT interfacing with Java on 64 bit OS theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-64"); -#else // legacy +#else // For 32 bit AT interfacing with Java on 32 bit OS theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE"); #endif #endif @@ -212,7 +212,6 @@ extern "C" { theAccessBridge.Windows_run(); theAccessBridgeInitializedFlag = TRUE; - PrintDebugString("theAccessBridgeInitializedFlag = TRUE"); return TRUE; } else { return FALSE; diff --git a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h index d7c62cf0828..3f907d5f9cd 100644 --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h +++ b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,10 +23,6 @@ * questions. */ -/* - * AccessBridgeCallbacks.h 1.17 05/03/21 - */ - /* * Header file defining callback typedefs for Windows routines * which are called from Java (responding to events, etc.). diff --git a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h index 51fa08c794a..46b42fd1c82 100644 --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h +++ b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,25 @@ * questions. */ +/* Note: In addition to this header file AccessBridgeCalls.c must be compiled and + * linked to your application. AccessBridgeCalls.c implements the Java Access + * Bridge API and also hides the complexities associated with interfacing to the + * associated Java Access Bridge DLL which is installed when Java is installed. + * + * AccessBridgeCalls.c is available for download from the OpenJDK repository using + * the following link: + * + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/raw-file/tip/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c + * + * Also note that the API is used in the jaccessinspector and jaccesswalker tools. + * The source for those tools is available in the OpenJDK repository at these links: + * + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/tip/src/jdk.accessibility/windows/native/jaccessinspector/jaccessinspector.cpp + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/tip/src/jdk.accessibility/windows/native/jaccesswalker/jaccesswalker.cpp + * + * + */ + /* * Wrapper functions around calls to the AccessBridge DLL */ From 599879e45fe2c2180c9193c5ae12a5b233ef3ec2 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Wed, 2 Nov 2016 11:07:16 -0700 Subject: [PATCH 028/402] 8164750: TIFF reading fails when ignoring metadata with BaselineTIFFTagSet removed Disallow not adding to metadata fields which are critical to reading the image data even when the BaselineTIFFTagSet has been removed from the TIFFImageReadParam and the ignoreMetadata flag is set. Reviewed-by: prr --- .../com/sun/imageio/plugins/tiff/TIFFIFD.java | 60 ++++++++ .../tiff/ReadWithoutBaselineTagSet.java | 139 ++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java diff --git a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java index 0a305c09726..1c194fb3b95 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java @@ -49,6 +49,52 @@ public class TIFFIFD extends TIFFDirectory { private long stripOrTileOffsetsPosition = -1; private long lastPosition = -1; + // + // A set of tag numbers corresponding to tags essential to decoding + // the image and metadata required to interpret its samples. + // + private static volatile Set essentialTags = null; + + private static void initializeEssentialTags() { + Set tags = essentialTags; + if (tags == null) { + essentialTags = tags = Set.of( + BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE, + BaselineTIFFTagSet.TAG_COLOR_MAP, + BaselineTIFFTagSet.TAG_COMPRESSION, + BaselineTIFFTagSet.TAG_EXTRA_SAMPLES, + BaselineTIFFTagSet.TAG_FILL_ORDER, + BaselineTIFFTagSet.TAG_ICC_PROFILE, + BaselineTIFFTagSet.TAG_IMAGE_LENGTH, + BaselineTIFFTagSet.TAG_IMAGE_WIDTH, + BaselineTIFFTagSet.TAG_JPEG_AC_TABLES, + BaselineTIFFTagSet.TAG_JPEG_DC_TABLES, + BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT, + BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, + BaselineTIFFTagSet.TAG_JPEG_PROC, + BaselineTIFFTagSet.TAG_JPEG_Q_TABLES, + BaselineTIFFTagSet.TAG_JPEG_RESTART_INTERVAL, + BaselineTIFFTagSet.TAG_JPEG_TABLES, + BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION, + BaselineTIFFTagSet.TAG_PLANAR_CONFIGURATION, + BaselineTIFFTagSet.TAG_PREDICTOR, + BaselineTIFFTagSet.TAG_REFERENCE_BLACK_WHITE, + BaselineTIFFTagSet.TAG_ROWS_PER_STRIP, + BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL, + BaselineTIFFTagSet.TAG_SAMPLE_FORMAT, + BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS, + BaselineTIFFTagSet.TAG_STRIP_OFFSETS, + BaselineTIFFTagSet.TAG_T4_OPTIONS, + BaselineTIFFTagSet.TAG_T6_OPTIONS, + BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS, + BaselineTIFFTagSet.TAG_TILE_LENGTH, + BaselineTIFFTagSet.TAG_TILE_OFFSETS, + BaselineTIFFTagSet.TAG_TILE_WIDTH, + BaselineTIFFTagSet.TAG_Y_CB_CR_COEFFICIENTS, + BaselineTIFFTagSet.TAG_Y_CB_CR_SUBSAMPLING + ); + } + } /** * Converts a {@code TIFFDirectory} to a {@code TIFFIFD}. @@ -507,6 +553,15 @@ public class TIFFIFD extends TIFFDirectory { List tagSetList = getTagSetList(); + boolean ensureEssentialTags = false; + TIFFTagSet baselineTagSet = null; + if (isPrimaryIFD && ignoreUnknownFields + && !tagSetList.contains(BaselineTIFFTagSet.getInstance())) { + ensureEssentialTags = true; + initializeEssentialTags(); + baselineTagSet = BaselineTIFFTagSet.getInstance(); + } + List entries = new ArrayList<>(); Object[] entryData = new Object[1]; // allocate once for later reuse. @@ -530,6 +585,11 @@ public class TIFFIFD extends TIFFDirectory { // Get the associated TIFFTag. TIFFTag tag = getTag(tagNumber, tagSetList); + if (tag == null && ensureEssentialTags + && essentialTags.contains(tagNumber)) { + tag = baselineTagSet.getTag(tagNumber); + } + // Ignore unknown fields, fields with unknown type, and fields // with count out of int range. if((tag == null && ignoreUnknownFields) diff --git a/jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java b/jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java new file mode 100644 index 00000000000..7624de01c40 --- /dev/null +++ b/jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8164750 + * @summary Verify reader does not fail when the BaselineTIFFTagSet is + * removed via the TIFFImageReadParam both when ignoring and + * not ignoring metadata. + */ + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.plugins.tiff.BaselineTIFFTagSet; +import javax.imageio.plugins.tiff.TIFFImageReadParam; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; +import javax.imageio.stream.MemoryCacheImageInputStream; +import javax.imageio.stream.MemoryCacheImageOutputStream; + +public class ReadWithoutBaselineTagSet { + private static final int WIDTH = 47; + private static final int HEIGHT = 53; + + private static final Map typeToCompression = + Map.of(BufferedImage.TYPE_3BYTE_BGR, + new String[] {null, "LZW", "JPEG", "ZLib", "PackBits"}, + BufferedImage.TYPE_BYTE_BINARY, + new String[] {null, "CCITT RLE", "CCITT T.4", "CCITT T.6", + "LZW", "PackBits"}, + BufferedImage.TYPE_BYTE_GRAY, + new String[] {null, "LZW", "JPEG", "ZLib", "PackBits"}, + BufferedImage.TYPE_USHORT_GRAY, + new String[] {null, "LZW", "ZLib", "PackBits"}); + + public static void main(String[] args) throws IOException { + test(); + } + + private static void test() throws IOException { + int failures = 0; + + for (int imageType : typeToCompression.keySet()) { + BufferedImage image = new BufferedImage(WIDTH, HEIGHT, imageType); + System.out.println("Image: " + image.toString()); + + for (String compression : typeToCompression.get(imageType)) { + System.out.println("Compression: " + + (compression == null ? "None" : compression)); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageOutputStream ios = new MemoryCacheImageOutputStream(output); + ImageWriter writer = + ImageIO.getImageWritersByFormatName("TIFF").next(); + ImageWriteParam wparam = writer.getDefaultWriteParam(); + if (compression == null) { + wparam.setCompressionMode(ImageWriteParam.MODE_DEFAULT); + } else { + wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + wparam.setCompressionType(compression); + } + writer.setOutput(ios); + writer.write(null, new IIOImage(image, null, null), wparam); + ios.flush(); + + ImageReader reader = + ImageIO.getImageReadersByFormatName("TIFF").next(); + ByteArrayInputStream input + = new ByteArrayInputStream(output.toByteArray()); + ImageInputStream iis = new MemoryCacheImageInputStream(input); + iis.mark(); + + TIFFImageReadParam rparam = new TIFFImageReadParam(); + rparam.removeAllowedTagSet(BaselineTIFFTagSet.getInstance()); + + reader.setInput(iis, false, false); + BufferedImage resultFalse = reader.read(0, rparam); + if (resultFalse.getWidth() != WIDTH + || resultFalse.getHeight() != HEIGHT) { + System.err.printf("Read image dimensions != %d x %d%n", + WIDTH, HEIGHT); + failures++; + } else { + System.out.println("ignoreMetadata == false test passed"); + } + + iis.reset(); + reader.setInput(iis, false, true); + BufferedImage resultTrue; + try { + resultTrue = reader.read(0, rparam); + if (resultTrue.getWidth() != WIDTH + || resultTrue.getHeight() != HEIGHT) { + System.err.printf("Read image dimensions != %d x %d%n", + WIDTH, HEIGHT); + failures++; + } else { + System.out.println("ignoreMetadata == true test passed"); + } + } catch (Exception e) { + e.printStackTrace(); + failures++; + } + } + } + + if (failures != 0) { + throw new RuntimeException("Test failed with " + + failures + " errors!"); + } + } +} From bc879dff7a5a4d8b083e03f1c96a5b6c797019f1 Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Wed, 2 Nov 2016 23:05:52 +0300 Subject: [PATCH 029/402] 8168881: javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java fails Reviewed-by: prr --- .../sampled/Clip/OpenNonIntegralNumberOfSampleframes.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java b/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java index 15b26416a10..b3198b8ab77 100644 --- a/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java +++ b/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java @@ -97,7 +97,8 @@ public final class OpenNonIntegralNumberOfSampleframes { System.err.println("af = " + af); System.err.println("bufferSize = " + bufferSize); throw new RuntimeException("Expected exception is not thrown"); - } catch (final LineUnavailableException ignored) { + } catch (IllegalArgumentException + | LineUnavailableException ignored) { // the test is not applicable } } From 8ae37850019d135f16ea933b24ed5052a605f966 Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Thu, 3 Nov 2016 03:49:42 +0300 Subject: [PATCH 030/402] 8143914: Provide Mac-specific fullscreen support Reviewed-by: serb, ssadetsky --- .../sun/lwawt/macosx/CPlatformWindow.java | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index cbbf3b193e9..d93b4bbcf21 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -25,10 +25,12 @@ package sun.lwawt.macosx; +import com.apple.eawt.FullScreenAdapter; +import com.apple.eawt.FullScreenUtilities; +import com.apple.eawt.event.FullScreenEvent; import java.awt.*; import java.awt.Dialog.ModalityType; import java.awt.event.*; -import java.awt.peer.WindowPeer; import java.beans.*; import java.lang.reflect.InvocationTargetException; @@ -44,6 +46,7 @@ import sun.util.logging.PlatformLogger; import com.apple.laf.*; import com.apple.laf.ClientPropertyApplicator.Property; import com.sun.awt.AWTUtilities; +import sun.lwawt.LWWindowPeer.PeerType; public class CPlatformWindow extends CFRetainedResource implements PlatformWindow { private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h); @@ -175,10 +178,24 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString())); }}, new Property(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) { - c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString())); + boolean zoomable = Boolean.parseBoolean(value.toString()); + if (c.target instanceof RootPaneContainer + && c.getPeer().getPeerType() == PeerType.FRAME) { + if (c.isInFullScreen && !zoomable) { + c.toggleFullScreen(); + } + } + c.setStyleBits(ZOOMABLE, zoomable); }}, new Property(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) { - c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString())); + boolean fullscrenable = Boolean.parseBoolean(value.toString()); + if (c.target instanceof RootPaneContainer + && c.getPeer().getPeerType() == PeerType.FRAME) { + if (c.isInFullScreen && !fullscrenable) { + c.toggleFullScreen(); + } + } + c.setStyleBits(FULLSCREENABLE, fullscrenable); }}, new Property(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) { nativeRevalidateNSWindowShadow(c.getNSWindowPtr()); @@ -210,6 +227,8 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo private volatile boolean isFullScreenMode; private boolean isFullScreenAnimationOn; + private volatile boolean isInFullScreen; + private Window target; private LWWindowPeer peer; protected CPlatformView contentView; @@ -308,6 +327,8 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo styleBits = SET(styleBits, RESIZABLE, resizable); if (!resizable) { styleBits = SET(styleBits, ZOOMABLE, false); + } else { + setCanFullscreen(true); } } @@ -680,9 +701,25 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo updateFocusabilityForAutoRequestFocus(true); } + private void setCanFullscreen(final boolean canFullScreen) { + if (target instanceof RootPaneContainer + && getPeer().getPeerType() == PeerType.FRAME) { + + if (isInFullScreen && !canFullScreen) { + toggleFullScreen(); + } + + final RootPaneContainer rpc = (RootPaneContainer) target; + rpc.getRootPane().putClientProperty( + CPlatformWindow.WINDOW_FULLSCREENABLE, canFullScreen); + } + } + @Override public void setResizable(final boolean resizable) { + setCanFullscreen(resizable); setStyleBits(RESIZABLE, resizable); + setStyleBits(ZOOMABLE, resizable); } @Override @@ -1074,6 +1111,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo } private void windowDidEnterFullScreen() { + isInFullScreen = true; isFullScreenAnimationOn = false; } @@ -1082,6 +1120,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo } private void windowDidExitFullScreen() { + isInFullScreen = false; isFullScreenAnimationOn = false; } } From e935e7cb1ebfa44d7abc5ac05a2f8dd517266ebe Mon Sep 17 00:00:00 2001 From: Amit Sapre Date: Thu, 3 Nov 2016 12:04:40 +0530 Subject: [PATCH 031/402] 8006078: [findbugs] java.lang.management.ThreadInfo returns mutable objects Cloned the array before returning to caller. Reviewed-by: dholmes, fparain --- .../share/classes/java/lang/management/ThreadInfo.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jdk/src/java.management/share/classes/java/lang/management/ThreadInfo.java b/jdk/src/java.management/share/classes/java/lang/management/ThreadInfo.java index c859d337c69..edf758e8731 100644 --- a/jdk/src/java.management/share/classes/java/lang/management/ThreadInfo.java +++ b/jdk/src/java.management/share/classes/java/lang/management/ThreadInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -554,7 +554,7 @@ public class ThreadInfo { * @return an array of {@code StackTraceElement} objects of the thread. */ public StackTraceElement[] getStackTrace() { - return stackTrace; + return stackTrace.clone(); } /** @@ -868,7 +868,7 @@ public class ThreadInfo { * @since 1.6 */ public MonitorInfo[] getLockedMonitors() { - return lockedMonitors; + return lockedMonitors.clone(); } /** @@ -885,7 +885,7 @@ public class ThreadInfo { * @since 1.6 */ public LockInfo[] getLockedSynchronizers() { - return lockedSynchronizers; + return lockedSynchronizers.clone(); } private static final StackTraceElement[] NO_STACK_TRACE = From bf4ed44178a2f15f70ad843ac89874c79c799100 Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Thu, 3 Nov 2016 11:51:31 +0300 Subject: [PATCH 032/402] 8159432: [PIT][macosx] StackOverflow in closed/java/awt/Dialog/DialogDeadlock/DialogDeadlockTest Reviewed-by: serb, azvegint --- .../java/awt/DefaultKeyboardFocusManager.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java b/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java index a3f33974c3b..9bbbf2f7862 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java +++ b/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java @@ -75,6 +75,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { private LinkedList enqueuedKeyEvents = new LinkedList(); private LinkedList typeAheadMarkers = new LinkedList(); private boolean consumeNextKeyTyped; + private Component restoreFocusTo; static { AWTAccessor.setDefaultKeyboardFocusManagerAccessor( @@ -145,19 +146,24 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { } private boolean restoreFocus(Window aWindow, Component vetoedComponent, boolean clearOnFailure) { + restoreFocusTo = null; Component toFocus = KeyboardFocusManager.getMostRecentFocusOwner(aWindow); if (toFocus != null && toFocus != vetoedComponent) { - Component heavyweight = getHeavyweight(aWindow); - if (heavyweight != null) { - setNativeFocusOwner(heavyweight); - Toolkit.getEventQueue().createSecondaryLoop( - () -> getGlobalFocusedWindow() != aWindow, null, 50) - .enter(); - } - if (getGlobalFocusedWindow() == aWindow && - doRestoreFocus(toFocus, vetoedComponent, false)) { + if (getHeavyweight(aWindow) != getNativeFocusOwner()) { + // cannot restore focus synchronously + if (!toFocus.isShowing() || !toFocus.canBeFocusOwner()) { + toFocus = toFocus.getNextFocusCandidate(); + } + if (toFocus != null && toFocus != vetoedComponent) { + if (!toFocus.requestFocus(false, + FocusEvent.Cause.ROLLBACK)) { + restoreFocusTo = toFocus; + } + return true; + } + } else if (doRestoreFocus(toFocus, vetoedComponent, false)) { return true; } } @@ -423,6 +429,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { // may cause deadlock, thus we don't synchronize this block. Component toFocus = KeyboardFocusManager. getMostRecentFocusOwner(newFocusedWindow); + boolean isFocusRestore = restoreFocusTo != null && + toFocus == restoreFocusTo; if ((toFocus == null) && newFocusedWindow.isFocusableWindow()) { @@ -441,7 +449,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { tempLost, toFocus); } if (tempLost != null) { - tempLost.requestFocusInWindow(FocusEvent.Cause.ACTIVATION); + tempLost.requestFocusInWindow( + isFocusRestore && tempLost == toFocus ? + FocusEvent.Cause.ROLLBACK : + FocusEvent.Cause.ACTIVATION); } if (toFocus != null && toFocus != tempLost) { @@ -450,6 +461,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { toFocus.requestFocusInWindow(FocusEvent.Cause.ACTIVATION); } } + restoreFocusTo = null; Window realOppositeWindow = this.realOppositeWindowWR.get(); if (realOppositeWindow != we.getOppositeWindow()) { @@ -499,6 +511,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { } case FocusEvent.FOCUS_GAINED: { + restoreFocusTo = null; FocusEvent fe = (FocusEvent)e; Component oldFocusOwner = getGlobalFocusOwner(); Component newFocusOwner = fe.getComponent(); From 047d30b2a959381f20d2e8a7f6cf129c71724a72 Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Thu, 3 Nov 2016 12:13:59 +0300 Subject: [PATCH 033/402] 8062525: JInternalFrame can't show correctly with the specical option "-esa -ea -Xcheck:jni -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel" Reviewed-by: serb --- .../com/sun/java/swing/plaf/gtk/Metacity.java | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index b8b77f5ec93..b92bce09a7c 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ import com.sun.java.swing.plaf.gtk.GTKConstants.ArrowType; import com.sun.java.swing.plaf.gtk.GTKConstants.ShadowType; import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import javax.swing.plaf.synth.*; import java.awt.*; @@ -40,7 +41,6 @@ import java.security.*; import java.util.*; import javax.swing.*; -import javax.swing.border.*; import javax.xml.parsers.*; import org.xml.sax.SAXException; @@ -226,12 +226,8 @@ class Metacity implements SynthConstants { JComponent titlePane = (JComponent)button.getParent(); Container titlePaneParent = titlePane.getParent(); - JInternalFrame jif; - if (titlePaneParent instanceof JInternalFrame) { - jif = (JInternalFrame)titlePaneParent; - } else if (titlePaneParent instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)titlePaneParent).getInternalFrame(); - } else { + JInternalFrame jif = findInternalFrame(titlePaneParent); + if (jif == null) { return; } @@ -332,6 +328,19 @@ class Metacity implements SynthConstants { } } + JInternalFrame findInternalFrame(Component comp) { + if (comp.getParent() instanceof BasicInternalFrameTitlePane) { + comp = comp.getParent(); + } + if (comp instanceof JInternalFrame) { + return (JInternalFrame)comp; + } else if (comp instanceof JInternalFrame.JDesktopIcon) { + return ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); + } + assert false : "cannot find the internal frame"; + return null; + } + void paintFrameBorder(SynthContext context, Graphics g, int x0, int y0, int width, int height) { updateFrameGeometry(context); @@ -343,13 +352,8 @@ class Metacity implements SynthConstants { return; } - JInternalFrame jif = null; - if (comp instanceof JInternalFrame) { - jif = (JInternalFrame)comp; - } else if (comp instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); - } else { - assert false : "component is not JInternalFrame or JInternalFrame.JDesktopIcon"; + JInternalFrame jif = findInternalFrame(comp); + if (jif == null) { return; } @@ -1467,13 +1471,8 @@ class Metacity implements SynthConstants { JComponent comp = context.getComponent(); JComponent titlePane = findChild(comp, "InternalFrame.northPane"); - JInternalFrame jif = null; - if (comp instanceof JInternalFrame) { - jif = (JInternalFrame)comp; - } else if (comp instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); - } else { - assert false : "component is not JInternalFrame or JInternalFrame.JDesktopIcon"; + JInternalFrame jif = findInternalFrame(comp); + if (jif == null) { return; } From 15205febe766a055143a52df34d46e372768b62e Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Thu, 3 Nov 2016 18:43:55 +0300 Subject: [PATCH 034/402] 8164032: JViewport backing store image is not scaled on HiDPI display Reviewed-by: serb --- .../share/classes/javax/swing/JViewport.java | 117 +++++++- .../JViewPortBackingStoreImageTest.java | 258 ++++++++++++++++++ 2 files changed, 373 insertions(+), 2 deletions(-) create mode 100644 jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java b/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java index d416dd7c39d..491d16306ea 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java @@ -27,6 +27,12 @@ package javax.swing; import java.awt.*; import java.awt.event.*; +import java.awt.geom.AffineTransform; +import static java.awt.geom.AffineTransform.TYPE_FLIP; +import static java.awt.geom.AffineTransform.TYPE_MASK_SCALE; +import static java.awt.geom.AffineTransform.TYPE_TRANSLATION; +import java.awt.image.AbstractMultiResolutionImage; +import java.awt.image.ImageObserver; import java.awt.peer.ComponentPeer; import java.beans.BeanProperty; import java.beans.Transient; @@ -37,6 +43,8 @@ import javax.swing.border.*; import javax.accessibility.*; import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; import sun.awt.AWTAccessor; @@ -739,7 +747,43 @@ public class JViewport extends JComponent implements Accessible g.clipRect(0, 0, viewBounds.width, viewBounds.height); } - if (backingStoreImage == null) { + boolean recreateBackingStoreImage = (backingStoreImage == null); + int scaledWidth = width; + int scaledHeight = height; + + if (g instanceof Graphics2D) { + double sw = width; + double sh = height; + Graphics2D g2d = (Graphics2D) g; + AffineTransform tx = g2d.getTransform(); + int type = tx.getType(); + if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP)) == 0) { + // skip + } else if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP | TYPE_MASK_SCALE)) == 0) { + sw = Math.abs(width * tx.getScaleX()); + sh = Math.abs(height * tx.getScaleY()); + } else { + sw = Math.abs(width * Math.hypot(tx.getScaleX(), tx.getShearY())); + sh = Math.abs(height * Math.hypot(tx.getShearX(), tx.getScaleY())); + } + + scaledWidth = (int) Math.ceil(sw); + scaledHeight = (int) Math.ceil(sh); + + if (!recreateBackingStoreImage) { + if (backingStoreImage instanceof BackingStoreMultiResolutionImage) { + BackingStoreMultiResolutionImage mrImage + = (BackingStoreMultiResolutionImage) backingStoreImage; + recreateBackingStoreImage = (mrImage.scaledWidth != scaledWidth + || mrImage.scaledHeight != scaledHeight); + } else { + recreateBackingStoreImage = (width != scaledWidth + || height != scaledHeight); + } + } + } + + if (recreateBackingStoreImage) { // Backing store is enabled but this is the first call to paint. // Create the backing store, paint it and then copy to g. // The backing store image will be created with the size of @@ -747,7 +791,8 @@ public class JViewport extends JComponent implements Accessible // same size, otherwise when scrolling the backing image // the region outside of the clipped region will not be painted, // and result in empty areas. - backingStoreImage = createImage(width, height); + backingStoreImage = createScaledImage(width, height, + scaledWidth, scaledHeight); Rectangle clip = g.getClipBounds(); if (clip.width != width || clip.height != height) { if (!isOpaque()) { @@ -815,6 +860,74 @@ public class JViewport extends JComponent implements Accessible scrollUnderway = false; } + private Image createScaledImage(final int width, final int height, + int scaledWidth, int scaledHeight) + { + if (scaledWidth == width && scaledHeight == height) { + return createImage(width, height); + } + + Image rvImage = createImage(scaledWidth, scaledHeight); + + return new BackingStoreMultiResolutionImage(width, height, + scaledWidth, scaledHeight, rvImage); + } + + static class BackingStoreMultiResolutionImage + extends AbstractMultiResolutionImage { + + private final int width; + private final int height; + private final int scaledWidth; + private final int scaledHeight; + private final Image rvImage; + + public BackingStoreMultiResolutionImage(int width, int height, + int scaledWidth, int scaledHeight, Image rvImage) { + this.width = width; + this.height = height; + this.scaledWidth = scaledWidth; + this.scaledHeight = scaledHeight; + this.rvImage = rvImage; + } + + @Override + public int getWidth(ImageObserver observer) { + return width; + } + + @Override + public int getHeight(ImageObserver observer) { + return height; + } + + @Override + protected Image getBaseImage() { + return rvImage; + } + + @Override + public Graphics getGraphics() { + Graphics graphics = rvImage.getGraphics(); + if (graphics instanceof Graphics2D) { + double sx = (double) scaledWidth / width; + double sy = (double) scaledHeight / height; + ((Graphics2D) graphics).scale(sx, sy); + } + return graphics; + } + + @Override + public Image getResolutionVariant(double w, double h) { + return rvImage; + } + + @Override + public java.util.List getResolutionVariants() { + return Collections.unmodifiableList(Arrays.asList(rvImage)); + } + } + /** * Sets the bounds of this viewport. If the viewport's width diff --git a/jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java b/jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java new file mode 100644 index 00000000000..f69408facb2 --- /dev/null +++ b/jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.HashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.Style; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyleContext; + +/* + * @test + * @bug 8164032 8156217 + * @summary JViewport backing store image is not scaled on HiDPI display + * @run main/manual JViewPortBackingStoreImageTest + */ +public class JViewPortBackingStoreImageTest { + + private static volatile boolean testResult = false; + private static volatile CountDownLatch countDownLatch; + private static final String INSTRUCTIONS = "INSTRUCTIONS:\n\n" + + "Verify text is drawn with high resolution and text selection " + + "is not shifted when JViewPort is used on HiDPI display.\n\n" + + "If the display does not support HiDPI mode press PASS.\n\n" + + "1. Check that the text does not have low resolution.\n" + + "If no, press FAIL.\n\n" + + "2. Select the current text from the end to the beginning.\n" + + "\n" + + "If the text is slightly shiftted from one side to another\n" + + "and back during selection press Fail.\n" + + "Otherwise, press Pass."; + + private static DefaultStyledDocument doc; + private static StyleContext styles; + private static HashMap contentAttributes; + + public static void main(String args[]) throws Exception { + countDownLatch = new CountDownLatch(1); + + SwingUtilities.invokeLater(JViewPortBackingStoreImageTest::createUI); + countDownLatch.await(15, TimeUnit.MINUTES); + + if (!testResult) { + throw new RuntimeException("Test fails!"); + } + } + + private static void createUI() { + + try { + UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + } catch (Exception e) { + throw new RuntimeException(e); + } + + final JFrame mainFrame = new JFrame(); + GridBagLayout layout = new GridBagLayout(); + JPanel mainControlPanel = new JPanel(layout); + JPanel resultButtonPanel = new JPanel(layout); + + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.gridx = 0; + gbc.gridy = 0; + gbc.insets = new Insets(5, 15, 5, 15); + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(createComponent(), gbc); + + JTextArea instructionTextArea = new JTextArea(); + instructionTextArea.setText(INSTRUCTIONS); + instructionTextArea.setEditable(false); + instructionTextArea.setBackground(Color.white); + + gbc.gridx = 0; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(instructionTextArea, gbc); + + JButton passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.addActionListener((ActionEvent e) -> { + testResult = true; + mainFrame.dispose(); + countDownLatch.countDown(); + + }); + + JButton failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + mainFrame.dispose(); + countDownLatch.countDown(); + } + }); + + gbc.gridx = 0; + gbc.gridy = 0; + + resultButtonPanel.add(passButton, gbc); + + gbc.gridx = 1; + gbc.gridy = 0; + resultButtonPanel.add(failButton, gbc); + + gbc.gridx = 0; + gbc.gridy = 2; + mainControlPanel.add(resultButtonPanel, gbc); + + mainFrame.add(mainControlPanel); + mainFrame.pack(); + + mainFrame.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent e) { + mainFrame.dispose(); + countDownLatch.countDown(); + } + }); + mainFrame.setVisible(true); + } + + private static JComponent createComponent() { + createStyles(); + for (int i = 0; i < data.length; i++) { + Paragraph p = data[i]; + addParagraph(p); + } + + JTextPane textPane = new JTextPane(doc); + + JScrollPane scroller = new JScrollPane(); + JViewport port = scroller.getViewport(); + port.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); + port.add(textPane); + + return scroller; + } + + static void createStyles() { + styles = new StyleContext(); + doc = new DefaultStyledDocument(styles); + contentAttributes = new HashMap<>(); + + // no attributes defined + Style s = styles.addStyle(null, null); + contentAttributes.put("none", s); + + Style def = styles.getStyle(StyleContext.DEFAULT_STYLE); + + Style heading = styles.addStyle("heading", def); + StyleConstants.setFontFamily(heading, "SansSerif"); + StyleConstants.setBold(heading, true); + StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER); + StyleConstants.setSpaceAbove(heading, 10); + StyleConstants.setSpaceBelow(heading, 10); + StyleConstants.setFontSize(heading, 18); + + // Title + Style sty = styles.addStyle("title", heading); + StyleConstants.setFontSize(sty, 32); + + // author + sty = styles.addStyle("author", heading); + StyleConstants.setItalic(sty, true); + StyleConstants.setSpaceBelow(sty, 25); + } + + static void addParagraph(Paragraph p) { + try { + Style s = null; + for (int i = 0; i < p.data.length; i++) { + AttributedContent run = p.data[i]; + s = contentAttributes.get(run.attr); + doc.insertString(doc.getLength(), run.content, s); + } + + Style ls = styles.getStyle(p.logical); + doc.setLogicalStyle(doc.getLength() - 1, ls); + doc.insertString(doc.getLength(), "\n", null); + } catch (BadLocationException e) { + throw new RuntimeException(e); + } + } + + private static Paragraph[] data = new Paragraph[]{ + new Paragraph("title", new AttributedContent[]{ + new AttributedContent("none", "ALICE'S ADVENTURES IN WONDERLAND") + }), + new Paragraph("author", new AttributedContent[]{ + new AttributedContent("none", "Lewis Carroll") + }), + new Paragraph("heading", new AttributedContent[]{ + new AttributedContent("alice", " ") + })}; + + static class Paragraph { + + Paragraph(String logical, AttributedContent[] data) { + this.logical = logical; + this.data = data; + } + String logical; + AttributedContent[] data; + } + + static class AttributedContent { + + AttributedContent(String attr, String content) { + this.attr = attr; + this.content = content; + } + String attr; + String content; + } +} From f6a0e771fe0136c376f1de75e342f7ad0586a5f3 Mon Sep 17 00:00:00 2001 From: Ajit Ghaisas Date: Fri, 4 Nov 2016 14:03:33 +0530 Subject: [PATCH 035/402] 8160146: Resolve disabled GCC warning 'deprecated-declarations' for libawt_xawt Reviewed-by: erikj, serb --- jdk/make/lib/Awt2dLibraries.gmk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index 4212cd9f652..ed402abecf5 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -356,7 +356,7 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) $(X_CFLAGS), \ WARNINGS_AS_ERRORS_xlc := false, \ DISABLED_WARNINGS_gcc := type-limits pointer-to-int-cast \ - deprecated-declarations unused-result maybe-uninitialized format \ + unused-result maybe-uninitialized format \ format-security int-to-pointer-cast parentheses, \ DISABLED_WARNINGS_solstudio := E_DECLARATION_IN_CODE \ E_ASSIGNMENT_TYPE_MISMATCH E_NON_CONST_INIT, \ From f57398c41ad4bb60cbb0c409ca9c889a89fc38f4 Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Fri, 4 Nov 2016 17:27:56 +0530 Subject: [PATCH 036/402] 8040635: [macosx] Printing a shape filled with a texture doesn't work under Mac OS X Reviewed-by: prr, jdv --- .../classes/sun/java2d/OSXSurfaceData.java | 2 +- .../PrinterJob/TexturePaintPrintingTest.java | 210 ++++++++++++++++++ 2 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java diff --git a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java index e59e932a8fe..236a36eeb33 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java +++ b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java @@ -672,7 +672,7 @@ public abstract class OSXSurfaceData extends BufImgSurfaceData { TexturePaint color = (TexturePaint) sg2d.paint; this.fGraphicsStatesInt.put(kColorStateIndex, kColorTexture); texturePaintImage = color.getImage(); - SurfaceData textureSurfaceData = BufImgSurfaceData.createData(texturePaintImage); + SurfaceData textureSurfaceData = OSXOffScreenSurfaceData.createNewSurface(texturePaintImage); this.fGraphicsStatesInt.put(kColorWidthIndex, texturePaintImage.getWidth()); this.fGraphicsStatesInt.put(kColorHeightIndex, texturePaintImage.getHeight()); Rectangle2D anchor = color.getAnchorRect(); diff --git a/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java b/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java new file mode 100644 index 00000000000..8ac81c8bbad --- /dev/null +++ b/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8040635 + * @summary Verifies if TexturePaint is printed in osx + * @run main/manual TexturePaintPrintingTest + */ +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.TexturePaint; +import java.awt.event.ActionEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import static java.awt.print.Printable.NO_SUCH_PAGE; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; + +public class TexturePaintPrintingTest extends Component implements Printable { + private static void printTexture() { + f = new JFrame("Texture Printing Test"); + f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + final TexturePaintPrintingTest gpt = new TexturePaintPrintingTest(); + Container c = f.getContentPane(); + c.add(BorderLayout.CENTER, gpt); + + final JButton print = new JButton("Print"); + print.addActionListener(new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(gpt); + final boolean doPrint = job.printDialog(); + if (doPrint) { + try { + job.print(); + } catch (PrinterException ex) { + throw new RuntimeException(ex); + } + } + } + }); + c.add(print, BorderLayout.SOUTH); + + f.pack(); + f.setVisible(true); + } + + public Dimension getPreferredSize() { + return new Dimension(500,500); + } + + public void paint(Graphics g) { + doPaint((Graphics2D)g); + } + + public int print( Graphics graphics, PageFormat format, int index ) { + Graphics2D g2d = (Graphics2D)graphics; + g2d.translate(format.getImageableX(), format.getImageableY()); + doPaint(g2d); + return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE; + } + + static final float DIM = 100; + public void doPaint(Graphics2D g2d) { + BufferedImage patternImage = new BufferedImage(2,2,BufferedImage.TYPE_INT_ARGB); + Graphics gImage = patternImage.getGraphics(); + gImage.setColor(Color.WHITE); + gImage.drawLine(0,1,1,0); + gImage.setColor(Color.BLACK); + gImage.drawLine(0,0,1,1); + gImage.dispose(); + + Rectangle2D.Double shape = new Rectangle2D.Double(0,0,DIM*6/5, DIM*8/5); + g2d.setPaint(new TexturePaint(patternImage, new Rectangle2D.Double(0,0, + DIM*6/50, DIM*8/50))); + g2d.fill(shape); + g2d.setPaint(Color.BLACK); + g2d.draw(shape); + } + + public static synchronized void pass() { + testPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public static synchronized void fail() { + testPassed = false; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + private static Thread mainThread; + private static boolean testPassed; + private static boolean testGeneratedInterrupt; + private static JFrame f = null; + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + //createUI(); + doTest(TexturePaintPrintingTest::printTexture); + } + }); + mainThread = Thread.currentThread(); + try { + Thread.sleep(120000); + } catch (InterruptedException e) { + if (!testPassed && testGeneratedInterrupt) { + throw new RuntimeException("TexturePaint did not print"); + } + } + if (!testGeneratedInterrupt) { + throw new RuntimeException("user has not executed the test"); + } + } + + private static void doTest(Runnable action) { + String description + = " A TexturePaint graphics will be shown on console.\n" + + " The same graphics is sent to printer.\n" + + " Please verify if TexturePaint shading is printed.\n" + + " If none is printed, press FAIL else press PASS"; + + final JDialog dialog = new JDialog(); + dialog.setTitle("printSelectionTest"); + JTextArea textArea = new JTextArea(description); + textArea.setEditable(false); + final JButton testButton = new JButton("Start Test"); + final JButton passButton = new JButton("PASS"); + passButton.setEnabled(false); + passButton.addActionListener((e) -> { + f.dispose(); + dialog.dispose(); + pass(); + }); + final JButton failButton = new JButton("FAIL"); + failButton.setEnabled(false); + failButton.addActionListener((e) -> { + f.dispose(); + dialog.dispose(); + fail(); + }); + testButton.addActionListener((e) -> { + testButton.setEnabled(false); + action.run(); + passButton.setEnabled(true); + failButton.setEnabled(true); + }); + JPanel mainPanel = new JPanel(new BorderLayout()); + mainPanel.add(textArea, BorderLayout.CENTER); + JPanel buttonPanel = new JPanel(new FlowLayout()); + buttonPanel.add(testButton); + buttonPanel.add(passButton); + buttonPanel.add(failButton); + mainPanel.add(buttonPanel, BorderLayout.SOUTH); + dialog.add(mainPanel); + + dialog.pack(); + dialog.setVisible(true); + dialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + System.out.println("main dialog closing"); + testGeneratedInterrupt = false; + mainThread.interrupt(); + } + }); + } +} From 099928305c06bf2289cbf7169762be12ff5bcc5c Mon Sep 17 00:00:00 2001 From: Ambarish Rapte Date: Fri, 4 Nov 2016 21:55:19 +0530 Subject: [PATCH 037/402] 8160766: [TEST_BUG] java/awt/Focus/DisposedWindow Reviewed-by: serb, aghaisas --- .../DisposeDialogNotActivateOwnerTest.java | 260 +++++------------- 1 file changed, 63 insertions(+), 197 deletions(-) diff --git a/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java b/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java index 4ccb28d433f..c88744edf15 100644 --- a/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java +++ b/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,237 +22,103 @@ */ /* - test - @bug 6386592 - @summary Tests that disposing a dialog doesn't activate its invisible owner. - @author anton.tarasov@sun.com: area=awt.focus - @run applet DisposeDialogNotActivateOwnerTest.html + @test + @key headful + @bug 6386592 8160766 + @summary Tests that disposing a dialog doesn't activate its invisible owner. */ -import java.awt.*; -import java.awt.event.*; -import java.applet.Applet; +import java.awt.AWTException; +import java.awt.Button; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.InputEvent; -public class DisposeDialogNotActivateOwnerTest extends Applet { +public class DisposeDialogNotActivateOwnerTest { Robot robot; - - Frame frame = new Frame("Owner Frame"); - Dialog dialog = new Dialog(new Frame(), "Owned Dialog"); - Button frameButton = new Button("button"); - - static boolean passed = false; + Frame frame; + Frame dialogInvisibleOwner; + Dialog dialog; + Button frameButton; + static volatile boolean buttonReceivedFocus = false; public static void main(String[] args) { - DisposeDialogNotActivateOwnerTest app = new DisposeDialogNotActivateOwnerTest(); - app.init(); - app.start(); + DisposeDialogNotActivateOwnerTest test = + new DisposeDialogNotActivateOwnerTest(); + test.performTest(); + test.dispose(); } - public void init() { + public DisposeDialogNotActivateOwnerTest() { try { robot = new Robot(); } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); + throw new RuntimeException("Error: unable to create robot"); } - // Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - Sysout.createDialogWithInstructions(new String[] - {"This is automatic test. Simply wait until it is done." - }); - frame.setBounds(800, 50, 200, 100); + dialogInvisibleOwner = new Frame("Dialog Invisible Owner Frame"); + dialog = new Dialog(dialogInvisibleOwner, "Owned Dialog"); + + frame = new Frame("A Frame"); + frameButton = new Button("button"); + frameButton.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + buttonReceivedFocus = true; + } + }); + frame.setBounds(0, 0, 400, 200); frame.add(frameButton); - dialog.setBounds(800, 300, 200, 100); + dialog.setBounds(100, 50, 200, 100); } - public void start() { - - frameButton.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - passed = true; - } - }); - + public void performTest() { frame.setVisible(true); robot.waitForIdle(); - - // make sure the frame is focused - clickOn(frame); + clickOnTitle(frame); + robot.waitForIdle(); + robot.delay(200); if (!frame.isFocused()) { - throw new RuntimeException("Error: a frame didn't get initial focus."); + dispose(); + throw new RuntimeException("Error: frame didn't get initial focus"); } dialog.setVisible(true); robot.waitForIdle(); - - // make sure the dialog is focused + robot.delay(200); if (!dialog.isFocused()) { - throw new RuntimeException("Error: a dialog didn't get initial focus."); + dispose(); + throw new RuntimeException("Error: dialog didn't get initial focus"); } dialog.dispose(); robot.waitForIdle(); - - if (passed) { - Sysout.println("Test passed."); - } else { - throw new RuntimeException("Test failed: a dialog activates invisible owner when disposed!"); + robot.delay(200); + if (!buttonReceivedFocus) { + dispose(); + throw new RuntimeException( + "Test failed: Dialog activates invisible owner when disposed!"); } } - void clickOn(Component c) { + public void dispose() { + frame.dispose(); + dialog.dispose(); + dialogInvisibleOwner.dispose(); + } + + void clickOnTitle(Component c) { Point p = c.getLocationOnScreen(); Dimension d = c.getSize(); - - if (c instanceof Frame) { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); - } else { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); - } - + robot.mouseMove(p.x + (int)(d.getWidth() / 2), + p.y + ((Frame)c).getInsets().top / 2); robot.mousePress(InputEvent.BUTTON1_MASK); robot.delay(20); robot.mouseRelease(InputEvent.BUTTON1_MASK); - - robot.waitForIdle(); } } - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class From 9ecae6db4874e742db26813ab9d52296fa2fe18e Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Fri, 4 Nov 2016 15:31:38 -0700 Subject: [PATCH 038/402] 8154093: [TIFF] NPE when reading LZW-compressed image LZW decompressor was ignoring the value of the FillOrder field. Reviewed-by: prr --- .../plugins/tiff/TIFFFaxDecompressor.java | 18 ++++++----- .../imageio/plugins/tiff/TIFFImageReader.java | 9 +++++- .../plugins/tiff/TIFFLZWDecompressor.java | 31 ++++++++++++++----- 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java index 9d522366d86..c0279b134f8 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,8 @@ class TIFFFaxDecompressor extends TIFFDecompressor { 0xff // 8 }; - // Table to be used when fillOrder = 2, for flipping bytes. + // Table to be used for flipping bytes when fillOrder is + // BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT (2). static byte flipTable[] = { 0, -128, 64, -64, 32, -96, 96, -32, 16, -112, 80, -48, 48, -80, 112, -16, @@ -597,7 +598,8 @@ class TIFFFaxDecompressor extends TIFFDecompressor { TIFFField f; f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER); - this.fillOrder = f == null ? 1 : f.getAsInt(0); + this.fillOrder = f == null ? + BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT : f.getAsInt(0); f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION); this.compression = f == null ? @@ -612,7 +614,7 @@ class TIFFFaxDecompressor extends TIFFDecompressor { f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_T6_OPTIONS); this.t6Options = f == null ? 0 : f.getAsInt(0); } else { - this.fillOrder = 1; // MSB-to-LSB + this.fillOrder = BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT; this.compression = BaselineTIFFTagSet.COMPRESSION_CCITT_RLE; // RLE @@ -1458,7 +1460,7 @@ class TIFFFaxDecompressor extends TIFFDecompressor { int l = data.length - 1; int bp = this.bytePointer; - if (fillOrder == 1) { + if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT) { b = data[bp]; if (bp == l) { @@ -1471,7 +1473,7 @@ class TIFFFaxDecompressor extends TIFFDecompressor { next = data[bp + 1]; next2next = data[bp + 2]; } - } else if (fillOrder == 2) { + } else if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT) { b = flipTable[data[bp] & 0xff]; if (bp == l) { @@ -1527,14 +1529,14 @@ class TIFFFaxDecompressor extends TIFFDecompressor { int l = data.length - 1; int bp = this.bytePointer; - if (fillOrder == 1) { + if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } - } else if (fillOrder == 2) { + } else if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; diff --git a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java index 0a872faa0c5..91778e7e097 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java @@ -1174,7 +1174,14 @@ public class TIFFImageReader extends ImageReader { int predictor = ((predictorField == null) ? BaselineTIFFTagSet.PREDICTOR_NONE : predictorField.getAsInt(0)); - this.decompressor = new TIFFLZWDecompressor(predictor); + + TIFFField fillOrderField + = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER); + int fillOrder = ((fillOrderField == null) + ? BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT + : fillOrderField.getAsInt(0)); + + this.decompressor = new TIFFLZWDecompressor(predictor, fillOrder); } else if (compression == BaselineTIFFTagSet.COMPRESSION_JPEG) { this.decompressor = new TIFFJPEGDecompressor(); diff --git a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java index 340179f7e8d..423b97c8e0a 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java @@ -30,6 +30,10 @@ import javax.imageio.plugins.tiff.BaselineTIFFTagSet; class TIFFLZWDecompressor extends TIFFDecompressor { + private static final int CLEAR_CODE = 256; + private static final int EOI_CODE = 257; + private static final int FIRST_CODE = 258; + private static final int andTable[] = { 511, 1023, @@ -39,6 +43,10 @@ class TIFFLZWDecompressor extends TIFFDecompressor { private int predictor; + // whether to reverse the bits in each byte of the input data, i.e., + // convert right-to-left fill order (lsb) to left-to-right (msb). + private boolean flipBits; + private byte[] srcData; private byte[] dstData; @@ -51,7 +59,8 @@ class TIFFLZWDecompressor extends TIFFDecompressor { private int nextData = 0; private int nextBits = 0; - public TIFFLZWDecompressor(int predictor) throws IIOException { + public TIFFLZWDecompressor(int predictor, int fillOrder) + throws IIOException { super(); if (predictor != BaselineTIFFTagSet.PREDICTOR_NONE && @@ -62,6 +71,8 @@ class TIFFLZWDecompressor extends TIFFDecompressor { } this.predictor = predictor; + + flipBits = fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT; } public void decodeRaw(byte[] b, @@ -88,6 +99,12 @@ class TIFFLZWDecompressor extends TIFFDecompressor { byte[] sdata = new byte[byteCount]; stream.readFully(sdata); + if (flipBits) { + for (int i = 0; i < byteCount; i++) { + sdata[i] = TIFFFaxDecompressor.flipTable[sdata[i] & 0xff]; + } + } + int bytesPerRow = (srcWidth*bitsPerPixel + 7)/8; byte[] buf; int bufOffset; @@ -133,11 +150,11 @@ class TIFFLZWDecompressor extends TIFFDecompressor { int code, oldCode = 0; byte[] string; - while ((code = getNextCode()) != 257) { - if (code == 256) { + while ((code = getNextCode()) != EOI_CODE) { + if (code == CLEAR_CODE) { initializeStringTable(); code = getNextCode(); - if (code == 257) { + if (code == EOI_CODE) { break; } @@ -186,12 +203,12 @@ class TIFFLZWDecompressor extends TIFFDecompressor { public void initializeStringTable() { stringTable = new byte[4096][]; - for (int i = 0; i < 256; i++) { + for (int i = 0; i < CLEAR_CODE; i++) { stringTable[i] = new byte[1]; stringTable[i][0] = (byte)i; } - tableIndex = 258; + tableIndex = FIRST_CODE; bitsToGet = 9; } @@ -281,7 +298,7 @@ class TIFFLZWDecompressor extends TIFFDecompressor { return code; } catch (ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. - return 257; + return EOI_CODE; } } } From 6dc331a5e3e5e32f563d4d13138d7e66040761e9 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Fri, 4 Nov 2016 15:59:59 -0700 Subject: [PATCH 039/402] 8168316: Suppress deprecation warnings for Applet classes in java.desktop Reviewed-by: serb, psadhukhan --- .../macosx/classes/com/apple/laf/AquaInternalFrameUI.java | 1 + .../share/classes/com/sun/java/swing/SwingUtilities3.java | 2 ++ .../classes/com/sun/media/sound/JavaSoundAudioClip.java | 1 + jdk/src/java.desktop/share/classes/java/awt/Component.java | 2 ++ .../share/classes/java/beans/AppletInitializer.java | 1 + jdk/src/java.desktop/share/classes/java/beans/Beans.java | 5 +++-- .../java.desktop/share/classes/javax/swing/JComponent.java | 5 +++++ jdk/src/java.desktop/share/classes/javax/swing/JTable.java | 1 + .../share/classes/javax/swing/KeyboardManager.java | 1 + .../java.desktop/share/classes/javax/swing/PopupFactory.java | 5 +++++ .../share/classes/javax/swing/RepaintManager.java | 3 +++ .../share/classes/javax/swing/SwingUtilities.java | 5 +++++ .../share/classes/javax/swing/ToolTipManager.java | 2 ++ .../classes/javax/swing/plaf/basic/BasicPopupMenuUI.java | 2 ++ .../share/classes/sun/applet/AppletAudioClip.java | 1 + .../java.desktop/share/classes/sun/applet/AppletPanel.java | 2 +- .../java.desktop/share/classes/sun/applet/AppletViewer.java | 3 +-- .../share/classes/sun/applet/AppletViewerPanel.java | 1 + .../java.desktop/share/classes/sun/awt/EmbeddedFrame.java | 1 + 19 files changed, 39 insertions(+), 5 deletions(-) diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java index 74b40511795..fd6bccf2260 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java @@ -431,6 +431,7 @@ public class AquaInternalFrameUI extends BasicInternalFrameUI implements SwingCo } @Override + @SuppressWarnings("deprecation") public void mouseReleased(final MouseEvent e) { if (didForwardEvent(e)) return; diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java index 6b2891aa517..c6968c2ebc9 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -88,6 +88,7 @@ public class SwingUtilities3 { * or {@code Applet} * @param isRequested the value to set vsyncRequested state to */ + @SuppressWarnings("deprecation") public static void setVsyncRequested(Container rootContainer, boolean isRequested) { assert (rootContainer instanceof Applet) || (rootContainer instanceof Window); @@ -104,6 +105,7 @@ public class SwingUtilities3 { * @param rootContainer topmost container. Should be either Window or Applet * @return {@code true} if vsync painting is requested for {@code rootContainer} */ + @SuppressWarnings("deprecation") public static boolean isVsyncRequested(Container rootContainer) { assert (rootContainer instanceof Applet) || (rootContainer instanceof Window); return Boolean.TRUE == vsyncedMap.get(rootContainer); diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java index 28f26796169..3cb26ab5497 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java @@ -55,6 +55,7 @@ import javax.sound.sampled.UnsupportedAudioFileException; * @author Arthur van Hoff, Kara Kytle, Jan Borgersen * @author Florian Bomers */ +@SuppressWarnings("deprecation") public final class JavaSoundAudioClip implements AudioClip, MetaEventListener, LineListener { private static final boolean DEBUG = false; diff --git a/jdk/src/java.desktop/share/classes/java/awt/Component.java b/jdk/src/java.desktop/share/classes/java/awt/Component.java index 05fbfabe80f..dca2674c2fd 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Component.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Component.java @@ -4016,6 +4016,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * {@code true}. * @see #createBuffers(int, BufferCapabilities) */ + @SuppressWarnings("deprecation") protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps) throws AWTException { @@ -8133,6 +8134,7 @@ public abstract class Component implements ImageObserver, MenuContainer, return res; } + @SuppressWarnings("deprecation") final Component getNextFocusCandidate() { Container rootAncestor = getTraversalRoot(); Component comp = this; diff --git a/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java b/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java index c28f67434fd..50c54643209 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java +++ b/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java @@ -44,6 +44,7 @@ import java.beans.beancontext.BeanContext; */ +@SuppressWarnings("deprecation") public interface AppletInitializer { /** diff --git a/jdk/src/java.desktop/share/classes/java/beans/Beans.java b/jdk/src/java.desktop/share/classes/java/beans/Beans.java index 5d252e81e1e..43e5c42ffd0 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/Beans.java +++ b/jdk/src/java.desktop/share/classes/java/beans/Beans.java @@ -154,7 +154,7 @@ public class Beans { * @exception IOException if an I/O error occurs. * @since 1.2 */ - + @SuppressWarnings("deprecation") public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) throws IOException, ClassNotFoundException { @@ -501,7 +501,7 @@ class ObjectInputStreamWithLoader extends ObjectInputStream * Package private support class. This provides a default AppletContext * for beans which are applets. */ - +@SuppressWarnings("deprecation") class BeansAppletContext implements AppletContext { Applet target; Hashtable imageCache = new Hashtable<>(); @@ -586,6 +586,7 @@ class BeansAppletContext implements AppletContext { * Package private support class. This provides an AppletStub * for beans which are applets. */ +@SuppressWarnings("deprecation") class BeansAppletStub implements AppletStub { transient boolean active; transient Applet target; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java b/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java index 74abca7dc54..02813cbcbf3 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java @@ -555,6 +555,7 @@ public abstract class JComponent extends Container implements Serializable, * @see #setComponentPopupMenu * @since 1.5 */ + @SuppressWarnings("deprecation") public JPopupMenu getComponentPopupMenu() { if(!getInheritsPopupMenu()) { @@ -2913,6 +2914,7 @@ public abstract class JComponent extends Container implements Serializable, * @param pressed true if the key is pressed * @return true if there is a key binding for e */ + @SuppressWarnings("deprecation") boolean processKeyBindings(KeyEvent e, boolean pressed) { if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) { return false; @@ -4457,6 +4459,7 @@ public abstract class JComponent extends Container implements Serializable, * return value for this method * @see #getVisibleRect */ + @SuppressWarnings("deprecation") static final void computeVisibleRect(Component c, Rectangle visibleRect) { Container p = c.getParent(); Rectangle bounds = c.getBounds(); @@ -4625,6 +4628,7 @@ public abstract class JComponent extends Container implements Serializable, * or null if not in any container */ @BeanProperty(bound = false) + @SuppressWarnings("deprecation") public Container getTopLevelAncestor() { for(Container p = this; p != null; p = p.getParent()) { if(p instanceof Window || p instanceof Applet) { @@ -5032,6 +5036,7 @@ public abstract class JComponent extends Container implements Serializable, this.paintingChild = paintingChild; } + @SuppressWarnings("deprecation") void _paintImmediately(int x, int y, int w, int h) { Graphics g; Container c; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JTable.java b/jdk/src/java.desktop/share/classes/javax/swing/JTable.java index 6e081429dad..94391d6e46b 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JTable.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JTable.java @@ -6043,6 +6043,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable this.focusManager = fm; } + @SuppressWarnings("deprecation") public void propertyChange(PropertyChangeEvent ev) { if (!isEditing() || getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) { return; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java b/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java index 8bec79a4ba5..e083576d819 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java @@ -137,6 +137,7 @@ class KeyboardManager { /** * Find the top focusable Window, Applet, or InternalFrame */ + @SuppressWarnings("deprecation") private static Container getTopAncestor(JComponent c) { for(Container p = c.getParent(); p != null; p = p.getParent()) { if (p instanceof Window && ((Window)p).isFocusableWindow() || diff --git a/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java b/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java index e3d80064b86..d45390709cc 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java @@ -614,6 +614,7 @@ public class PopupFactory { * Returns true if popup can fit the screen and the owner's top parent. * It determines can popup be lightweight or mediumweight. */ + @SuppressWarnings("deprecation") boolean fitsOnScreen() { boolean result = false; Component component = getComponent(); @@ -783,6 +784,8 @@ public class PopupFactory { component.removeAll(); recycleLightWeightPopup(this); } + + @SuppressWarnings("deprecation") public void show() { Container parent = null; @@ -938,6 +941,8 @@ public class PopupFactory { rootPane.getContentPane().removeAll(); recycleMediumWeightPopup(this); } + + @SuppressWarnings("deprecation") public void show() { Component component = getComponent(); Container parent = null; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java b/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java index c9d265a4614..1db490608b7 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java @@ -408,6 +408,7 @@ public class RepaintManager * * @see JComponent#repaint */ + @SuppressWarnings("deprecation") private void addDirtyRegion0(Container c, int x, int y, int w, int h) { /* Special cases we don't have to bother with. */ @@ -521,10 +522,12 @@ public class RepaintManager * @see JApplet#repaint * @since 1.6 */ + @SuppressWarnings("deprecation") public void addDirtyRegion(Applet applet, int x, int y, int w, int h) { addDirtyRegion0(applet, x, y, w, h); } + @SuppressWarnings("deprecation") void scheduleHeavyWeightPaints() { Map hws; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java b/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java index 9900c9b7e0e..abd6b055887 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java @@ -416,6 +416,7 @@ public class SwingUtilities implements SwingConstants * @param p a Point object (converted to the new coordinate system) * @param c a Component object */ + @SuppressWarnings("deprecation") public static void convertPointToScreen(Point p,Component c) { Rectangle b; int x,y; @@ -455,6 +456,7 @@ public class SwingUtilities implements SwingConstants * @param p a Point object (converted to the new coordinate system) * @param c a Component object */ + @SuppressWarnings("deprecation") public static void convertPointFromScreen(Point p,Component c) { Rectangle b; int x,y; @@ -1655,6 +1657,7 @@ public class SwingUtilities implements SwingConstants * @param c the component * @return the first ancestor of c that's a Window or the last Applet ancestor */ + @SuppressWarnings("deprecation") public static Component getRoot(Component c) { Component applet = null; for(Component p = c; p != null; p = p.getParent()) { @@ -1695,6 +1698,7 @@ public class SwingUtilities implements SwingConstants * @return true if a binding has found and processed * @since 1.4 */ + @SuppressWarnings("deprecation") public static boolean processKeyBindings(KeyEvent event) { if (event != null) { if (event.isConsumed()) { @@ -2209,6 +2213,7 @@ public class SwingUtilities implements SwingConstants * @see java.awt.Component#isVisible() * @since 1.7 */ + @SuppressWarnings("deprecation") static Container getValidateRoot(Container c, boolean visibleOnly) { Container root = null; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java index b9a602b44ba..c645d936b11 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java @@ -753,6 +753,7 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener // Returns: 0 no adjust // -1 can't fit // >0 adjust value by amount returned + @SuppressWarnings("deprecation") private int getPopupFitWidth(Rectangle popupRectInScreen, Component invoker){ if (invoker != null){ Container parent; @@ -778,6 +779,7 @@ public class ToolTipManager extends MouseAdapter implements MouseMotionListener // Returns: 0 no adjust // >0 adjust by value return + @SuppressWarnings("deprecation") private int getPopupFitHeight(Rectangle popupRectInScreen, Component invoker){ if (invoker != null){ Container parent; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java index 1b6c56c2fc0..737d4d0d2b2 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java @@ -926,6 +926,7 @@ public class BasicPopupMenuUI extends PopupMenuUI { } } + @SuppressWarnings("deprecation") boolean isInPopup(Component src) { for (Component c=src; c!=null; c=c.getParent()) { if (c instanceof Applet || c instanceof Window) { @@ -1143,6 +1144,7 @@ public class BasicPopupMenuUI extends PopupMenuUI { } } + @SuppressWarnings("deprecation") public void stateChanged(ChangeEvent ev) { if (!(UIManager.getLookAndFeel() instanceof BasicLookAndFeel)) { uninstall(); diff --git a/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java b/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java index 95d28325e59..a2469a3f99f 100644 --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java @@ -41,6 +41,7 @@ import com.sun.media.sound.JavaSoundAudioClip; * @author Arthur van Hoff, Kara Kytle */ +@SuppressWarnings("deprecation") public class AppletAudioClip implements AudioClip { // url that this AudioClip is based on diff --git a/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java b/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java index d03e5be0527..fc8eaac0845 100644 --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java @@ -54,7 +54,7 @@ import sun.security.util.SecurityConstants; * * @author Arthur van Hoff */ -@SuppressWarnings("serial") // JDK implementation class +@SuppressWarnings({"serial", "deprecation"}) // JDK implementation class public abstract class AppletPanel extends Panel implements AppletStub, Runnable { diff --git a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java index d613fc94341..f11804dddab 100644 --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java @@ -117,7 +117,7 @@ final class StdAppletViewerFactory implements AppletViewerFactory { * (The document named appletviewertags.html in the JDK's docs/tooldocs directory, * once the JDK docs have been installed.) */ -@SuppressWarnings("serial") // JDK implementation class +@SuppressWarnings({"serial", "deprecation"}) // JDK-implementation class public class AppletViewer extends Frame implements AppletContext, Printable { /** @@ -157,7 +157,6 @@ public class AppletViewer extends Frame implements AppletContext, Printable { /** * Create the applet viewer. */ - @SuppressWarnings("deprecation") public AppletViewer(int x, int y, URL doc, Hashtable atts, PrintStream statusMsgStream, AppletViewerFactory factory) { this.factory = factory; diff --git a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java index 1a8354c0035..c0aaf07ad03 100644 --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java @@ -197,6 +197,7 @@ class AppletViewerPanel extends AppletPanel { * Get the applet context. For now this is * also implemented by the AppletPanel class. */ + @SuppressWarnings("deprecation") public AppletContext getAppletContext() { return (AppletContext)getParent(); } diff --git a/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java b/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java index d096d8c5e7d..38060aa55a6 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java @@ -499,6 +499,7 @@ public abstract class EmbeddedFrame extends Frame * @return the parent applet or {@ null} * @since 1.6 */ + @SuppressWarnings("deprecation") public static Applet getAppletIfAncestorOf(Component comp) { Container parent = comp.getParent(); Applet applet = null; From 57dc20d5414da9d926eff9bf7054d98102ce7f38 Mon Sep 17 00:00:00 2001 From: Semyon Sadetsky Date: Mon, 7 Nov 2016 10:36:52 +0300 Subject: [PATCH 040/402] 8153522: Update JLightweightFrame to allow non-integer (and X/Y) scales Reviewed-by: alexsch --- .../sun/lwawt/macosx/CPlatformLWWindow.java | 3 +- .../classes/sun/awt/LightweightFrame.java | 38 +++++- .../classes/sun/swing/JLightweightFrame.java | 111 +++++++++++------- .../classes/sun/swing/LightweightContent.java | 48 +++++++- 4 files changed, 155 insertions(+), 45 deletions(-) diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java index a056df5cc10..1f42ab9de68 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java @@ -196,7 +196,8 @@ public class CPlatformLWWindow extends CPlatformWindow { getLocalGraphicsEnvironment(); LWLightweightFramePeer peer = (LWLightweightFramePeer)getPeer(); - int scale = ((LightweightFrame)peer.getTarget()).getScaleFactor(); + int scale =(int) Math.round(((LightweightFrame)peer.getTarget()) + .getScaleFactorX()); Rectangle bounds = ((LightweightFrame)peer.getTarget()).getHostBounds(); for (GraphicsDevice d : ge.getScreenDevices()) { diff --git a/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java b/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java index 5ddeca23ef4..fe5f9c7d9fe 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -141,16 +141,51 @@ public abstract class LightweightFrame extends Frame { * * @return the scale factor * @see #notifyDisplayChanged(int) + * @Depricated replaced by {@link #getScaleFactorX()} and + * {@link #getScaleFactorY} */ + @Deprecated(since = "9") public abstract int getScaleFactor(); + /** + * Returns the scale factor of this frame along x coordinate. The default + * value is 1. + * + * @return the x coordinate scale factor + * @see #notifyDisplayChanged(double, double) + * @since 9 + */ + public abstract double getScaleFactorX(); + + /** + * Returns the scale factor of this frame along y coordinate. The default + * value is 1. + * + * @return the y coordinate scale factor + * @see #notifyDisplayChanged(double, double) + * @since 9 + */ + public abstract double getScaleFactorY(); + /** * Called when display of the hosted frame is changed. * * @param scaleFactor the scale factor + * @Depricated replaced by {@link #notifyDisplayChanged(double, double)} */ + @Deprecated(since = "9") public abstract void notifyDisplayChanged(int scaleFactor); + /** + * Called when display of the hosted frame is changed. + * + * @param scaleFactorX the scale factor + * @param scaleFactorY the scale factor + * @since 9 + */ + public abstract void notifyDisplayChanged(double scaleFactorX, + double scaleFactorY); + /** * Host window absolute bounds. */ @@ -202,4 +237,5 @@ public abstract class LightweightFrame extends Frame { * Removes a drop target from the lightweight frame. */ public abstract void removeDropTarget(DropTarget dt); + } diff --git a/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java b/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java index 0a7066d4439..450a62c57fe 100644 --- a/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java +++ b/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,18 +25,7 @@ package sun.swing; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.MouseInfo; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Window; +import java.awt.*; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragGestureRecognizer; @@ -46,6 +35,7 @@ import java.awt.dnd.InvalidDnDOperationException; import java.awt.dnd.peer.DragSourceContextPeer; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; +import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; @@ -89,7 +79,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan private BufferedImage bbImage; - private volatile int scaleFactor = 1; + private volatile double scaleFactorX; + private volatile double scaleFactorY; /** * {@code copyBufferEnabled}, true by default, defines the following strategy. @@ -124,6 +115,10 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan */ public JLightweightFrame() { super(); + AffineTransform defaultTransform = + getGraphicsConfiguration().getDefaultTransform(); + scaleFactorX = defaultTransform.getScaleX(); + scaleFactorY = defaultTransform.getScaleY(); copyBufferEnabled = "true".equals(AccessController. doPrivileged(new GetPropertyAction("swing.jlf.copyBufferEnabled", "true"))); @@ -157,8 +152,9 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan } Point p = SwingUtilities.convertPoint(c, x, y, jlf); Rectangle r = new Rectangle(p.x, p.y, w, h).intersection( - new Rectangle(0, 0, bbImage.getWidth() / scaleFactor, - bbImage.getHeight() / scaleFactor)); + new Rectangle(0, 0, + (int)Math.round(bbImage.getWidth() / scaleFactorX), + (int)Math.round(bbImage.getHeight() / scaleFactorY))); if (!r.isEmpty()) { notifyImageUpdated(r.x, r.y, r.width, r.height); @@ -212,7 +208,7 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan g.setBackground(getBackground()); g.setColor(getForeground()); g.setFont(getFont()); - g.scale(scaleFactor, scaleFactor); + g.scale(scaleFactorX, scaleFactorY); return g; } @@ -237,28 +233,52 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan } @Override + @SuppressWarnings("deprecation") public int getScaleFactor() { - return scaleFactor; + return (int)scaleFactorX; + } + + @Override + public double getScaleFactorX() { + return scaleFactorX; + } + + @Override + public double getScaleFactorY() { + return scaleFactorY; } @Override public void notifyDisplayChanged(final int scaleFactor) { - if (scaleFactor != this.scaleFactor) { + notifyDisplayChanged(scaleFactor, scaleFactor); + } + + @Override + public void notifyDisplayChanged(final double scaleFactorX, + final double scaleFactorY) { + if (Double.compare(scaleFactorX, this.scaleFactorX) != 0 || + Double.compare(scaleFactorY, this.scaleFactorY) != 0) { if (!copyBufferEnabled) content.paintLock(); try { if (bbImage != null) { - resizeBuffer(getWidth(), getHeight(), scaleFactor); + resizeBuffer(getWidth(), getHeight(), scaleFactorX, + scaleFactorY); } } finally { if (!copyBufferEnabled) content.paintUnlock(); } - this.scaleFactor = scaleFactor; + this.scaleFactorX = scaleFactorX; + this.scaleFactorY = scaleFactorY; + + if(isVisible()) { + final Object peer = + AWTAccessor.getComponentAccessor().getPeer(this); + if (peer instanceof DisplayChangedListener) { + ((DisplayChangedListener) peer).displayChanged(); + } + repaint(); + } } - final Object peer = AWTAccessor.getComponentAccessor().getPeer(this); - if (peer instanceof DisplayChangedListener) { - ((DisplayChangedListener) peer).displayChanged(); - } - repaint(); } @Override @@ -270,7 +290,8 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan } } - private void syncCopyBuffer(boolean reset, int x, int y, int w, int h, int scale) { + private void syncCopyBuffer(boolean reset, int x, int y, int w, int h, + double scaleX, double scaleY) { content.paintLock(); try { int[] srcBuffer = ((DataBufferInt)bbImage.getRaster().getDataBuffer()).getData(); @@ -279,14 +300,14 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan } int linestride = bbImage.getWidth(); - x *= scale; - y *= scale; - w *= scale; - h *= scale; + int startX = (int)Math.floor(x * scaleX); + int startY = (int)Math.floor(y * scaleY); + int width = (int)Math.ceil((x + w) * scaleX) - startX; + int height = (int)Math.ceil((y + h) * scaleY) - startY; - for (int i=0; i + * The method reports a reference to the pixel data buffer, the content + * image bounds within the buffer and the line stride of the buffer. + * These values have the following correlation. + * The {@code width} and {@code height} matches the layout size of the + * content (the component returned from the {@link #getComponent} method). + * The {@code x} and {@code y} is the origin of the content, {@code (0, 0)} + * in the layout coordinate space of the content, appearing at + * {@code data[y * scaleY * linestride + x * scaleX]} in the buffer. + * A pixel with indices {@code (i, j)}, where {@code (0 <= i < width)} and + * {@code (0 <= j < height)}, in the layout coordinate space of the content + * is represented by a {@code scaleX * scaleY} square of pixels in the + * physical coordinate space of the buffer. The top-left corner of the + * square has the following physical coordinate in the buffer: + * {@code data[(y + j) * scaleY * linestride + (x + i) * scaleX]}. + * + * @param data the content pixel data buffer of INT_ARGB_PRE type + * @param x the logical x coordinate of the image + * @param y the logical y coordinate of the image + * @param width the logical width of the image + * @param height the logical height of the image + * @param linestride the line stride of the pixel buffer + * @param scaleX the x coordinate scale factor of the pixel buffer + * @param scaleY the y coordinate scale factor of the pixel buffer + * @since 9 + */ + @SuppressWarnings("deprecation") + default public void imageBufferReset(int[] data, + int x, int y, + int width, int height, + int linestride, + double scaleX, double scaleY) + { + imageBufferReset(data, x, y, width, height, linestride, + (int)Math.round(scaleX)); + } + /** * The default implementation for #imageBufferReset uses a hard-coded value * of 1 for the scale factor. Both the old and the new methods provide * default implementations in order to allow a client application to run * with any JDK version without breaking backward compatibility. */ + @SuppressWarnings("deprecation") default public void imageBufferReset(int[] data, int x, int y, int width, int height, From 36bb41faf936be792e48168e162f85e89e17c5ba Mon Sep 17 00:00:00 2001 From: Alexander Scherbatiy Date: Mon, 7 Nov 2016 11:22:53 +0300 Subject: [PATCH 041/402] 8168992: Add floating point implementation for new BasicGraphicsUtils text related methods use floating point API Reviewed-by: serb, ssadetsky --- .../swing/plaf/basic/BasicGraphicsUtils.java | 6 +- .../classes/javax/swing/text/Utilities.java | 2 +- .../classes/sun/swing/SwingUtilities2.java | 68 +++- .../8132119/bug8132119.java | 339 ++++++++++++++++++ 4 files changed, 401 insertions(+), 14 deletions(-) create mode 100644 jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java diff --git a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java index fa6c0c9c61a..2760b1dcfd2 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java @@ -403,7 +403,7 @@ public class BasicGraphicsUtils */ public static void drawString(JComponent c, Graphics2D g, String string, float x, float y) { - SwingUtilities2.drawString(c, g, string, (int) x, (int) y); + SwingUtilities2.drawString(c, g, string, x, y, true); } /** @@ -439,7 +439,7 @@ public class BasicGraphicsUtils public static void drawStringUnderlineCharAt(JComponent c, Graphics2D g, String string, int underlinedIndex, float x, float y) { SwingUtilities2.drawStringUnderlineCharAt(c, g, string, underlinedIndex, - (int) x, (int) y); + x, y, true); } /** @@ -482,6 +482,6 @@ public class BasicGraphicsUtils * @since 9 */ public static float getStringWidth(JComponent c, FontMetrics fm, String string) { - return SwingUtilities2.stringWidth(c, fm, string); + return SwingUtilities2.stringWidth(c, fm, string, true); } } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java b/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java index 940abb47c2c..7fc2cd11cd0 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java @@ -107,7 +107,7 @@ public class Utilities { TabExpander e, int startOffset) { - return drawTabbedText(s, (int) x, (int) y, (Graphics) g, e, startOffset); + return drawTabbedText(null, s, x, y, g, e, startOffset, null, true); } /** diff --git a/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java b/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java index 74085dd91c3..5bf01c5f99d 100644 --- a/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java +++ b/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java @@ -318,7 +318,21 @@ public class SwingUtilities2 { * @param fm FontMetrics used to measure the String width * @param string String to get the width of */ - public static int stringWidth(JComponent c, FontMetrics fm, String string){ + public static int stringWidth(JComponent c, FontMetrics fm, String string) { + return (int) stringWidth(c, fm, string, false); + } + + /** + * Returns the width of the passed in String. + * If the passed String is {@code null}, returns zero. + * + * @param c JComponent that will display the string, may be null + * @param fm FontMetrics used to measure the String width + * @param string String to get the width of + * @param useFPAPI use floating point API + */ + public static float stringWidth(JComponent c, FontMetrics fm, String string, + boolean useFPAPI){ if (string == null || string.equals("")) { return 0; } @@ -333,9 +347,9 @@ public class SwingUtilities2 { if (needsTextLayout) { TextLayout layout = createTextLayout(c, string, fm.getFont(), fm.getFontRenderContext()); - return (int) layout.getAdvance(); + return layout.getAdvance(); } else { - return fm.stringWidth(string); + return getFontStringWidth(string, fm, useFPAPI); } } @@ -426,6 +440,21 @@ public class SwingUtilities2 { */ public static void drawString(JComponent c, Graphics g, String text, int x, int y) { + drawString(c, g, text, x, y, false); + } + + /** + * Draws the string at the specified location. + * + * @param c JComponent that will display the string, may be null + * @param g Graphics to draw the text to + * @param text String to display + * @param x X coordinate to draw the text at + * @param y Y coordinate to draw the text at + * @param useFPAPI use floating point API + */ + public static void drawString(JComponent c, Graphics g, String text, + float x, float y, boolean useFPAPI) { // c may be null // All non-editable widgets that draw strings call into this @@ -509,7 +538,7 @@ public class SwingUtilities2 { g2.getFontRenderContext()); layout.draw(g2, x, y); } else { - g.drawString(text, x, y); + g2.drawString(text, x, y); } if (oldAAValue != null) { @@ -530,7 +559,7 @@ public class SwingUtilities2 { } } - g.drawString(text, x, y); + g.drawString(text, (int) x, (int) y); } /** @@ -544,17 +573,36 @@ public class SwingUtilities2 { * @param x X coordinate to draw the text at * @param y Y coordinate to draw the text at */ + public static void drawStringUnderlineCharAt(JComponent c,Graphics g, - String text, int underlinedIndex, int x,int y) { + String text, int underlinedIndex, int x, int y) { + drawStringUnderlineCharAt(c, g, text, underlinedIndex, x, y, false); + } + /** + * Draws the string at the specified location underlining the specified + * character. + * + * @param c JComponent that will display the string, may be null + * @param g Graphics to draw the text to + * @param text String to display + * @param underlinedIndex Index of a character in the string to underline + * @param x X coordinate to draw the text at + * @param y Y coordinate to draw the text at + * @param useFPAPI use floating point API + */ + public static void drawStringUnderlineCharAt(JComponent c, Graphics g, + String text, int underlinedIndex, + float x, float y, + boolean useFPAPI) { if (text == null || text.length() <= 0) { return; } - SwingUtilities2.drawString(c, g, text, x, y); + SwingUtilities2.drawString(c, g, text, x, y, useFPAPI); int textLength = text.length(); if (underlinedIndex >= 0 && underlinedIndex < textLength ) { - int underlineRectY = y; + float underlineRectY = y; int underlineRectHeight = 1; - int underlineRectX = 0; + float underlineRectX = 0; int underlineRectWidth = 0; boolean isPrinting = isPrinting(g); boolean needsTextLayout = isPrinting; @@ -594,7 +642,7 @@ public class SwingUtilities2 { underlineRectWidth = rect.width; } } - g.fillRect(underlineRectX, underlineRectY + 1, + g.fillRect((int) underlineRectX, (int) underlineRectY + 1, underlineRectWidth, underlineRectHeight); } } diff --git a/jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java b/jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java new file mode 100644 index 00000000000..d0f4a567a30 --- /dev/null +++ b/jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.font.FontRenderContext; +import java.awt.font.NumericShaper; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.awt.image.BufferedImage; +import java.util.HashMap; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.basic.BasicGraphicsUtils; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/** + * @test + * @bug 8132119 8168992 + * @author Alexandr Scherbatiy + * @summary Provide public API for text related methods in SwingBasicGraphicsUtils2 + */ +public class bug8132119 { + + private static final int WIDTH = 50; + private static final int HEIGHT = 50; + private static final Color DRAW_COLOR = Color.RED; + private static final Color BACKGROUND_COLOR = Color.GREEN; + private static final NumericShaper NUMERIC_SHAPER = NumericShaper.getShaper( + NumericShaper.ARABIC); + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(bug8132119::testStringMethods); + } + + private static void testStringMethods() { + setMetalLAF(); + testStringWidth(); + testStringClip(); + testDrawEmptyString(); + testDrawString(false); + testDrawString(true); + checkNullArguments(); + } + + private static void testStringWidth() { + + String str = "12345678910\u036F"; + JComponent comp = createComponent(str); + Font font = comp.getFont(); + FontMetrics fontMetrics = comp.getFontMetrics(font); + float stringWidth = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str); + + if (stringWidth == fontMetrics.stringWidth(str)) { + throw new RuntimeException("Numeric shaper is not used!"); + } + + if (stringWidth != getLayoutWidth(str, font, NUMERIC_SHAPER)) { + throw new RuntimeException("Wrong text width!"); + } + } + + private static void testStringClip() { + + String str = "1234567890"; + JComponent comp = createComponent(str); + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + + int width = (int) BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str); + + String clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width); + checkClippedString(str, clip, str); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width + 1); + checkClippedString(str, clip, str); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, -1); + checkClippedString(str, clip, "..."); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, 0); + checkClippedString(str, clip, "..."); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, + str, width - width / str.length()); + int endIndex = str.length() - 3; + checkClippedString(str, clip, str.substring(0, endIndex) + "..."); + } + + private static void checkClippedString(String str, String res, String golden) { + if (!golden.equals(res)) { + throw new RuntimeException(String.format("The string '%s' is not " + + "properly clipped. The result is '%s' instead of '%s'", + str, res, golden)); + } + } + + private static void testDrawEmptyString() { + JLabel label = new JLabel(); + BufferedImage buffImage = createBufferedImage(50, 50); + Graphics2D g2 = buffImage.createGraphics(); + g2.setColor(DRAW_COLOR); + BasicGraphicsUtils.drawString(null, g2, null, 0, 0); + BasicGraphicsUtils.drawString(label, g2, null, 0, 0); + BasicGraphicsUtils.drawString(null, g2, "", 0, 0); + BasicGraphicsUtils.drawString(label, g2, "", 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g2, null, 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(label, g2, null, 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g2, "", 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(label, g2, "", 3, 0, 0); + g2.dispose(); + checkImageIsEmpty(buffImage); + } + + private static void testDrawString(boolean underlined) { + String str = "AOB"; + JComponent comp = createComponent(str); + + BufferedImage buffImage = createBufferedImage(WIDTH, HEIGHT); + Graphics2D g2 = buffImage.createGraphics(); + + g2.setColor(DRAW_COLOR); + g2.setFont(comp.getFont()); + + FontMetrics fontMetrices = comp.getFontMetrics(comp.getFont()); + float width = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, str); + float x = (WIDTH - width) / 2; + int y = 3 * HEIGHT / 4; + + if (underlined) { + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g2, str, 1, x, y); + } else { + BasicGraphicsUtils.drawString(comp, g2, str, x, y); + } + g2.dispose(); + + float xx = (WIDTH - width / 8) / 2; + checkImageContainsSymbol(buffImage, (int) xx, underlined ? 3 : 2); + } + + private static void checkNullArguments() { + + Graphics2D g = null; + try { + String text = "Test"; + JComponent component = new JLabel(text); + BufferedImage img = createBufferedImage(100, 100); + g = img.createGraphics(); + checkNullArguments(component, g, text); + } finally { + g.dispose(); + } + } + + private static void checkNullArguments(JComponent comp, Graphics2D g, + String text) { + + checkNullArgumentsDrawString(comp, g, text); + checkNullArgumentsDrawStringUnderlineCharAt(comp, g, text); + checkNullArgumentsGetClippedString(comp, text); + checkNullArgumentsGetStringWidth(comp, text); + } + + private static void checkNullArgumentsDrawString(JComponent comp, Graphics2D g, + String text) { + + float x = 50; + float y = 50; + BasicGraphicsUtils.drawString(null, g, text, x, y); + BasicGraphicsUtils.drawString(comp, g, null, x, y); + + try { + BasicGraphicsUtils.drawString(comp, null, text, x, y); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsDrawStringUnderlineCharAt( + JComponent comp, Graphics2D g, String text) { + + int x = 50; + int y = 50; + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g, text, 1, x, y); + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g, null, 1, x, y); + + try { + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, null, text, 1, x, y); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsGetClippedString( + JComponent comp, String text) { + + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + + BasicGraphicsUtils.getClippedString(null, fontMetrics, text, 1); + String result = BasicGraphicsUtils.getClippedString(comp, fontMetrics, null, 1); + if (!"".equals(result)) { + throw new RuntimeException("Empty string is not returned!"); + } + + try { + BasicGraphicsUtils.getClippedString(comp, null, text, 1); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsGetStringWidth(JComponent comp, + String text) { + + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + BasicGraphicsUtils.getStringWidth(null, fontMetrics, text); + float result = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, null); + + if (result != 0) { + throw new RuntimeException("The string length is not 0"); + } + + try { + BasicGraphicsUtils.getStringWidth(comp, null, text); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void setMetalLAF() { + try { + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static JComponent createComponent(String str) { + JComponent comp = new JLabel(str); + comp.setSize(WIDTH, HEIGHT); + comp.putClientProperty(TextAttribute.NUMERIC_SHAPING, NUMERIC_SHAPER); + comp.setFont(getFont()); + return comp; + } + + private static Font getFont() { + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + String[] fontNames = ge.getAvailableFontFamilyNames(); + String fontName = fontNames[0]; + for (String name : fontNames) { + if ("Arial".equals(name)) { + fontName = name; + break; + } + } + return new Font(fontName, Font.PLAIN, 28); + } + + private static float getLayoutWidth(String text, Font font, NumericShaper shaper) { + HashMap map = new HashMap(); + map.put(TextAttribute.FONT, font); + map.put(TextAttribute.NUMERIC_SHAPING, shaper); + FontRenderContext frc = new FontRenderContext(null, false, false); + TextLayout layout = new TextLayout(text, map, frc); + return layout.getAdvance(); + } + + private static void checkImageIsEmpty(BufferedImage buffImage) { + int background = BACKGROUND_COLOR.getRGB(); + + for (int i = 0; i < buffImage.getWidth(); i++) { + for (int j = 0; j < buffImage.getHeight(); j++) { + if (background != buffImage.getRGB(i, j)) { + throw new RuntimeException("Image is not empty!"); + } + } + } + } + + private static void checkImageContainsSymbol(BufferedImage buffImage, + int x, int intersections) { + int background = BACKGROUND_COLOR.getRGB(); + boolean isBackground = true; + int backgroundChangesCount = 0; + + for (int y = 0; y < buffImage.getHeight(); y++) { + if (!(isBackground ^ (background != buffImage.getRGB(x, y)))) { + isBackground = !isBackground; + backgroundChangesCount++; + } + } + if (backgroundChangesCount != intersections * 2) { + throw new RuntimeException("String is not properly drawn!"); + } + } + + private static BufferedImage createBufferedImage(int width, int height) { + BufferedImage bufffImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + + Graphics2D g = bufffImage.createGraphics(); + g.setColor(BACKGROUND_COLOR); + g.fillRect(0, 0, width, height); + g.dispose(); + return bufffImage; + } +} From 9fc6d8f3aa093f75bb0fa1dde9fbaf597217cd7e Mon Sep 17 00:00:00 2001 From: Manajit Halder Date: Mon, 7 Nov 2016 14:35:21 +0530 Subject: [PATCH 042/402] 7153700: [macosx] add support for MouseMotionListener to the TrayIcon Reviewed-by: serb, aniyogi --- .../native/libawt_lwawt/awt/CTrayIcon.h | 3 +++ .../native/libawt_lwawt/awt/CTrayIcon.m | 21 ++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h index 19b50d176bf..49e0e7d8645 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h @@ -26,6 +26,7 @@ #include #import #import +#import #import "CPopupMenu.h" @@ -64,12 +65,14 @@ extern "C" { @public AWTTrayIcon *trayIcon; NSImage* image; + NSTrackingArea *trackingArea; BOOL isHighlighted; } -(id)initWithTrayIcon:(AWTTrayIcon *)theTrayIcon; -(void)setHighlighted:(BOOL)aFlag; -(void)setImage:(NSImage*)anImage; -(void)setTrayIcon:(AWTTrayIcon*)theTrayIcon; +-(void)addTrackingArea; @end //AWTTrayIconView diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m index 0cc9e84eb0d..8057972d301 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m @@ -171,12 +171,27 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize, BOOL autosize) { [self setTrayIcon: theTrayIcon]; isHighlighted = NO; image = nil; - + trackingArea = nil; + + [self addTrackingArea]; + return self; } +- (void)addTrackingArea { + NSTrackingAreaOptions options = NSTrackingMouseMoved | + NSTrackingInVisibleRect | + NSTrackingActiveAlways; + trackingArea = [[NSTrackingArea alloc] initWithRect: CGRectZero + options: options + owner: self + userInfo: nil]; + [self addTrackingArea:trackingArea]; +} + -(void) dealloc { [image release]; + [trackingArea release]; [super dealloc]; } @@ -269,6 +284,10 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize, BOOL autosize) { [trayIcon deliverJavaMouseEvent: event]; } +- (void) mouseMoved: (NSEvent *)event { + [trayIcon deliverJavaMouseEvent: event]; +} + - (void) rightMouseDown:(NSEvent *)event { [trayIcon deliverJavaMouseEvent: event]; } From 680aa95dbb2a97f20a9ba6d59ab8bfb1c1ce75d5 Mon Sep 17 00:00:00 2001 From: Jim Laskey Date: Mon, 7 Nov 2016 14:36:27 -0400 Subject: [PATCH 043/402] 8155756: Better context for some jlink exceptions Reviewed-by: mchung --- .../share/classes/jdk/tools/jlink/internal/DirArchive.java | 2 +- .../share/classes/jdk/tools/jlink/internal/TaskHelper.java | 2 +- .../share/classes/jdk/tools/jlink/resources/jlink.properties | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/DirArchive.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/DirArchive.java index 7b8c2c88655..84fee1b4710 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/DirArchive.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/DirArchive.java @@ -92,7 +92,7 @@ public class DirArchive implements Archive { public DirArchive(Path dirPath, Consumer log) { Objects.requireNonNull(dirPath); if (!Files.isDirectory(dirPath)) { - throw new IllegalArgumentException("Not a directory"); + throw new IllegalArgumentException(dirPath + " is not a directory"); } chop = dirPath.toString().length() + 1; this.moduleName = Objects.requireNonNull(dirPath.getFileName()).toString(); diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java index f5f74001d9c..083bf048724 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java @@ -212,7 +212,7 @@ public final class TaskHelper { mainOptions.add(new PlugOption(true, (task, opt, arg) -> { Path path = Paths.get(arg); if (!Files.exists(path) || !Files.isDirectory(path)) { - throw newBadArgs("err.image.must.exist"); + throw newBadArgs("err.image.must.exist", path); } existingImage = path.toAbsolutePath(); }, true, POST_PROCESS)); diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties index 556e0b20c66..ac4a86293a6 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties @@ -91,7 +91,7 @@ err.modulepath.must.be.specified:--module-path must be specified err.mods.must.be.specified:no modules specified to {0} err.path.not.found=path not found: {0} err.path.not.valid=invalid path: {0} -err.image.must.exist=image does not exist or is not a directory +err.image.must.exist=image {0} does not exist or is not a directory err.existing.image.invalid=existing image is not valid err.file.not.found=cannot find file: {0} err.file.error=cannot access file: {0} From 94dc40142581cf1be28d245d8738440977f56d11 Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Tue, 15 Nov 2016 15:52:27 +0300 Subject: [PATCH 044/402] 8169710: com/sun/nio/sctp tests has undeclared dependency on jdk.sctp module Reviewed-by: dfuchs, chegar --- jdk/test/com/sun/nio/sctp/TEST.properties | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 jdk/test/com/sun/nio/sctp/TEST.properties diff --git a/jdk/test/com/sun/nio/sctp/TEST.properties b/jdk/test/com/sun/nio/sctp/TEST.properties new file mode 100644 index 00000000000..3989427b278 --- /dev/null +++ b/jdk/test/com/sun/nio/sctp/TEST.properties @@ -0,0 +1,2 @@ +modules = jdk.sctp + From 5efdbcb1fb920588f32bea2eeacc84928bf22c3d Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 16 Nov 2016 19:52:20 +0530 Subject: [PATCH 045/402] 8153038: The set of jlink plugins enabled by default should be the same via CLI or jlink API Reviewed-by: jlaskey --- .../jdk/tools/jlink/internal/Jlink.java | 21 +++++++++++++++++++ .../packager/AppRuntimeImageBuilder.java | 2 -- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java index 615b7a8349c..6ad2f8dfe42 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java @@ -27,6 +27,7 @@ package jdk.tools.jlink.internal; import java.lang.reflect.Layer; import java.nio.ByteOrder; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @@ -278,6 +279,13 @@ public final class Jlink { */ public void build(JlinkConfiguration config, PluginsConfiguration pluginsConfig) { Objects.requireNonNull(config); + if (pluginsConfig == null) { + pluginsConfig = new PluginsConfiguration(); + } + + // add all auto-enabled plugins from boot layer + pluginsConfig = addAutoEnabledPlugins(pluginsConfig); + try { JlinkTask.createImage(config, pluginsConfig); } catch (Exception ex) { @@ -285,6 +293,19 @@ public final class Jlink { } } + private PluginsConfiguration addAutoEnabledPlugins(PluginsConfiguration pluginsConfig) { + List plugins = new ArrayList<>(pluginsConfig.getPlugins()); + List bootPlugins = PluginRepository.getPlugins(Layer.boot()); + for (Plugin bp : bootPlugins) { + if (Utils.isAutoEnabled(bp)) { + bp.configure(Collections.emptyMap()); + plugins.add(bp); + } + } + return new PluginsConfiguration(plugins, pluginsConfig.getImageBuilder(), + pluginsConfig.getLastSorterPluginName()); + } + /** * Post process the image with a plugin configuration. * diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java index 0d2adf63221..5b06d8135f2 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java @@ -118,8 +118,6 @@ public final class AppRuntimeImageBuilder { null)); } - plugins.add(Jlink.newPlugin("installed-modules", Collections.emptyMap(), null)); - // build the image Jlink.PluginsConfiguration pluginConfig = new Jlink.PluginsConfiguration( plugins, new DefaultImageBuilder(outputDir), null); From b440aed6910cf148718b78e9b332365e474d7002 Mon Sep 17 00:00:00 2001 From: Jim Laskey Date: Wed, 16 Nov 2016 10:52:08 -0400 Subject: [PATCH 046/402] 8169505: Update changes by JDK-8159393 to reflect CCC review Reviewed-by: sundar --- .../tools/jlink/resources/jlink.properties | 7 +- jdk/test/tools/jlink/JLinkSigningTest.java | 64 ++++++++----------- 2 files changed, 33 insertions(+), 38 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties index ac4a86293a6..33454bc6ccb 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties @@ -63,7 +63,10 @@ main.opt.save-opts=\ \ --save-opts Save jlink options in the given file main.opt.ignore-signing-information=\ -\ --ignore-signing-information Ignore signing information in modular JARs +\ --ignore-signing-information Suppress a fatal error when signed modular JARs \ +\ are linked in the image. The signature related \ +\ files of the signed modular JARs are not copied \ +\ to the runtime image. main.msg.bug=\ An exception has occurred in jlink. \ @@ -110,6 +113,6 @@ err.bom.generation=bom file generation failed: {0} err.not.modular.format=selected module {0} ({1}) not in jmod or modular JAR format err.signing=signed modular JAR {0} is currently not supported,\ \ use --ignore-signing-information to suppress error -warn.signing=signed modular JAR {0} is currently not supported +warn.signing=WARNING: signed modular JAR {0} is currently not supported warn.invalid.arg=invalid classname or pathname not exist: {0} warn.split.package=package {0} defined in {1} {2} diff --git a/jdk/test/tools/jlink/JLinkSigningTest.java b/jdk/test/tools/jlink/JLinkSigningTest.java index 169d3904c41..34b4dbcbdaa 100644 --- a/jdk/test/tools/jlink/JLinkSigningTest.java +++ b/jdk/test/tools/jlink/JLinkSigningTest.java @@ -26,24 +26,31 @@ * @bug 8159393 * @summary Test signed jars involved in image creation * @modules java.base/jdk.internal.jimage - * jdk.jlink/jdk.tools.jlink.internal - * jdk.compiler/com.sun.tools.javac * java.base/sun.security.tools.keytool + * jdk.compiler/com.sun.tools.javac * jdk.jartool/sun.security.tools.jarsigner * jdk.jartool/sun.tools.jar + * jdk.jlink/jdk.tools.jlink.internal * @run main/othervm JLinkSigningTest */ import java.io.File; import java.io.IOException; -import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.spi.ToolProvider; public class JLinkSigningTest { + private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar") + .orElseThrow(() -> new RuntimeException("jar tool not found")); + private static final ToolProvider JAVAC_TOOL = ToolProvider.findFirst("javac") + .orElseThrow(() -> new RuntimeException("javac tool not found")); + private static final ToolProvider JLINK_TOOL = ToolProvider.findFirst("jlink") + .orElseThrow(() -> new RuntimeException("jlink tool not found")); + static final String[] MODULE_INFO = { "module test {", "}", @@ -61,22 +68,29 @@ public class JLinkSigningTest { System.out.println(command + " " + String.join(" ", Arrays.asList(args))); } - static void javac(String[] args) { - report("javac", args); - com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main(); + static void jar(String[] args) { + report("jar", args); + JAR_TOOL.run(System.out, System.err, args); + } - if (javac.compile(args) != 0) { - throw new RuntimeException("javac failed"); + static void jarsigner(String[] args) { + report("jarsigner", args); + + try { + sun.security.tools.jarsigner.Main.main(args); + } catch (Exception ex) { + throw new RuntimeException("jarsigner not found"); } } - static void jar(String[] args) { - report("jar", args); - sun.tools.jar.Main jar = new sun.tools.jar.Main(System.out, System.err, "jar"); + static void javac(String[] args) { + report("javac", args); + JAVAC_TOOL.run(System.out, System.err, args); + } - if (!jar.run(args)) { - throw new RuntimeException("jar failed"); - } + static void jlink(String[] args) { + report("jlink", args); + JLINK_TOOL.run(System.out, System.err, args); } static void keytool(String[] args) { @@ -89,28 +103,6 @@ public class JLinkSigningTest { } } - static void jarsigner(String[] args) { - report("jarsigner", args); - - try { - sun.security.tools.jarsigner.Main.main(args); - } catch (Exception ex) { - throw new RuntimeException("jarsigner failed"); - } - } - - static void jlink(String[] args) { - report("jlink", args); - - try { - jdk.tools.jlink.internal.Main.run(new PrintWriter(System.out, true), - new PrintWriter(System.err, true), - args); - } catch (Exception ex) { - throw new RuntimeException("jlink failed"); - } - } - public static void main(String[] args) { final String JAVA_HOME = System.getProperty("java.home"); Path moduleInfoJavaPath = Paths.get("module-info.java"); From f3cb8c41dceb450160eb23433bc3c64e17d4ee79 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Wed, 16 Nov 2016 15:40:06 +0000 Subject: [PATCH 047/402] 8169068: Add a new method: java.net.Authenticator.getDefault() Reviewed-by: chegar --- .../share/classes/java/net/Authenticator.java | 31 +++++++- .../Authenticator/GetAuthenticatorTest.java | 76 +++++++++++++++++++ 2 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/net/Authenticator/GetAuthenticatorTest.java diff --git a/jdk/src/java.base/share/classes/java/net/Authenticator.java b/jdk/src/java.base/share/classes/java/net/Authenticator.java index 8b59db010f3..81a87c79987 100644 --- a/jdk/src/java.base/share/classes/java/net/Authenticator.java +++ b/jdk/src/java.base/share/classes/java/net/Authenticator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -130,6 +130,35 @@ class Authenticator { theAuthenticator = a; } + /** + * Gets the default authenticator. + * First, if there is a security manager, its {@code checkPermission} + * method is called with a + * {@code NetPermission("requestPasswordAuthentication")} permission. + * This may result in a java.lang.SecurityException. + * Then the default authenticator, if set, is returned. + * Otherwise, {@code null} is returned. + * + * @return The default authenticator, if set, {@code null} otherwise. + * + * @throws SecurityException + * if a security manager exists and its + * {@code checkPermission} method doesn't allow + * requesting password authentication. + * @since 9 + * @see SecurityManager#checkPermission + * @see java.net.NetPermission + */ + public static Authenticator getDefault() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + NetPermission requestPermission + = new NetPermission("requestPasswordAuthentication"); + sm.checkPermission(requestPermission); + } + return theAuthenticator; + } + /** * Ask the authenticator that has been registered with the system * for a password. diff --git a/jdk/test/java/net/Authenticator/GetAuthenticatorTest.java b/jdk/test/java/net/Authenticator/GetAuthenticatorTest.java new file mode 100644 index 00000000000..d36236ba32f --- /dev/null +++ b/jdk/test/java/net/Authenticator/GetAuthenticatorTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.lang.ref.Reference; +import java.net.Authenticator; +import java.net.NetPermission; +import java.net.PasswordAuthentication; +import java.security.AccessControlException; + +/** + * @test + * @bug 8169068 + * @summary Basic test for Authenticator.getDefault() + * @run main/othervm GetAuthenticatorTest + */ +public class GetAuthenticatorTest { + + static final class MyAuthenticator extends Authenticator { + + MyAuthenticator () { + super (); + } + + @Override + public PasswordAuthentication getPasswordAuthentication () { + System.out.println ("Auth called"); + return (new PasswordAuthentication ("user", + "passwordNotCheckedAnyway".toCharArray())); + } + + } + + public static void main (String args[]) throws Exception { + Authenticator defaultAuth = Authenticator.getDefault(); + if (defaultAuth != null) { + throw new RuntimeException("Unexpected authenticator: null expected"); + } + MyAuthenticator auth = new MyAuthenticator(); + Authenticator.setDefault(auth); + defaultAuth = Authenticator.getDefault(); + if (defaultAuth != auth) { + throw new RuntimeException("Unexpected authenticator: auth expected"); + } + System.setSecurityManager(new SecurityManager()); + try { + defaultAuth = Authenticator.getDefault(); + throw new RuntimeException("Expected security exception not raised"); + } catch (AccessControlException s) { + System.out.println("Got expected exception: " + s); + if (!s.getPermission().equals(new NetPermission("requestPasswordAuthentication"))) { + throw new RuntimeException("Unexpected permission check: " + s.getPermission()); + } + } + System.out.println("Test passed with default authenticator " + + defaultAuth); + } +} From 2eff7e6a9a8a51f06c500e20fc6acc88a8c66366 Mon Sep 17 00:00:00 2001 From: Jamil Nimeh Date: Wed, 16 Nov 2016 08:29:58 -0800 Subject: [PATCH 048/402] 8043252: Debug of access control is obfuscated - NullPointerException in ProtectionDomain Protect against null return value from Permission.getActions in ProtectionDomain's toString method. Reviewed-by: weijun, mullan --- .../java/security/ProtectionDomain.java | 3 +- .../ProtectionDomain/NullGetActions.java | 75 +++++++++++++++++++ .../ProtectionDomain/NullGetActions.policy | 3 + 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/security/ProtectionDomain/NullGetActions.java create mode 100644 jdk/test/java/security/ProtectionDomain/NullGetActions.policy diff --git a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java index 1f614d250f2..ecb12785591 100644 --- a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java +++ b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java @@ -32,6 +32,7 @@ import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import jdk.internal.misc.JavaSecurityAccess; import jdk.internal.misc.JavaSecurityProtectionDomainAccess; @@ -524,7 +525,7 @@ public class ProtectionDomain { // have some side effects so this manual // comparison is sufficient. if (pdpName.equals(pp.getName()) && - pdpActions.equals(pp.getActions())) { + Objects.equals(pdpActions, pp.getActions())) { plVector.remove(i); break; } diff --git a/jdk/test/java/security/ProtectionDomain/NullGetActions.java b/jdk/test/java/security/ProtectionDomain/NullGetActions.java new file mode 100644 index 00000000000..4986395d5f9 --- /dev/null +++ b/jdk/test/java/security/ProtectionDomain/NullGetActions.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8043252 + * @summary Debug of access control is obfuscated - NullPointerException in + * ProtectionDomain + * @run main/othervm/java.security.policy=NullGetActions.policy NullGetActions + */ + +import java.net.*; +import java.security.*; + +public class NullGetActions { + + public static void main(String[] args) throws Exception { + Permissions permset = new Permissions(); + permset.add(new EvilPermission("java.let.me.do.stuff")); + + Policy.getPolicy(); + ProtectionDomain protDom = new ProtectionDomain( + new CodeSource(new URL("http://bar"), + (java.security.cert.Certificate[])null), permset, + null, null); + + System.out.println("Protection Domain:\n" + protDom); + } + + public static class EvilPermission extends Permission { + public EvilPermission(String name) { + super(name); + } + + @Override + public String getActions() { + return null; + } + + @Override + public boolean equals(Object obj) { + return (obj == this); + } + + @Override + public int hashCode() { + return 42; + } + + @Override + public boolean implies(Permission permission) { + return false; + } + } +} diff --git a/jdk/test/java/security/ProtectionDomain/NullGetActions.policy b/jdk/test/java/security/ProtectionDomain/NullGetActions.policy new file mode 100644 index 00000000000..87c88439050 --- /dev/null +++ b/jdk/test/java/security/ProtectionDomain/NullGetActions.policy @@ -0,0 +1,3 @@ +grant { + permission java.security.SecurityPermission "getPolicy"; +}; From 16a386fb56fa4604c2fa87a46e152e1278e5ea01 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 16 Nov 2016 11:20:34 -0800 Subject: [PATCH 049/402] 8169803: Remove OpenNonIntegralNumberOfSampleframes.java from the problem list Reviewed-by: serb --- jdk/test/ProblemList.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 42066777eee..f3ec6cdbdae 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -227,8 +227,6 @@ javax/sound/sampled/Clip/Drain/ClipDrain.java 7062792 generic-all javax/sound/sampled/Mixers/DisabledAssertionCrash.java 7067310 generic-all -javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java 8168881 generic-all - ############################################################################ # jdk_imageio From 3d0c012270a3f1c561502ed4541112c7328f2986 Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Wed, 16 Nov 2016 12:50:29 -0800 Subject: [PATCH 050/402] 8168969: Merge SSLSocketSample and SSLSocketTemplate Reviewed-by: xuelei --- .../net/ssl/templates/SSLSocketSample.java | 404 ---------- .../net/ssl/templates/SSLSocketTemplate.java | 687 +++++++++++++----- jdk/test/javax/net/ssl/templates/SSLTest.java | 549 -------------- .../https/HttpsClient/ProxyAuthTest.java | 12 +- .../https/HttpsClient/ServerIdentityTest.java | 16 +- .../AnonCipherWithWantClientAuth.java | 18 +- 6 files changed, 523 insertions(+), 1163 deletions(-) delete mode 100644 jdk/test/javax/net/ssl/templates/SSLSocketSample.java delete mode 100644 jdk/test/javax/net/ssl/templates/SSLTest.java diff --git a/jdk/test/javax/net/ssl/templates/SSLSocketSample.java b/jdk/test/javax/net/ssl/templates/SSLSocketSample.java deleted file mode 100644 index 38a082a041e..00000000000 --- a/jdk/test/javax/net/ssl/templates/SSLSocketSample.java +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// Please run in othervm mode. SunJSSE does not support dynamic system -// properties, no way to re-use system properties in samevm/agentvm mode. - -/* - * @test - * @bug 8161106 - * @summary Improve SSLSocket test template - * @run main/othervm SSLSocketSample - */ - -import java.io.*; -import javax.net.ssl.*; -import java.net.*; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Template to help speed your client/server tests. - */ -public final class SSLSocketSample { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private static final boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - private static final String pathToStores = "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - /* - * Turn on SSL debugging? - */ - private static final boolean debug = false; - - /* - * Is the server ready to serve? - */ - private static final CountDownLatch serverCondition = new CountDownLatch(1); - - /* - * Is the client ready to handshake? - */ - private static final CountDownLatch clientCondition = new CountDownLatch(1); - - /* - * What's the server port? Use any free port by default - */ - private volatile int serverPort = 0; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - */ - void doServerSide() throws Exception { - SSLServerSocket sslServerSocket; - - // kick start the server side service - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - // Signal the client, the server is ready to accept connection. - serverCondition.countDown(); - - - // Try to accept a connection in 30 seconds. - SSLSocket sslSocket; - try { - sslServerSocket.setSoTimeout(30000); - sslSocket = (SSLSocket)sslServerSocket.accept(); - } catch (SocketTimeoutException ste) { - sslServerSocket.close(); - - // Ignore the test case if no connection within 30 seconds. - System.out.println( - "No incoming client connection in 30 seconds. " + - "Ignore in server side."); - return; - } - - // handle the connection - try { - // Is it the expected client connection? - // - // Naughty test cases or third party routines may try to - // connection to this server port unintentionally. In - // order to mitigate the impact of unexpected client - // connections and avoid intermittent failure, it should - // be checked that the accepted connection is really linked - // to the expected client. - boolean clientIsReady = - clientCondition.await(30L, TimeUnit.SECONDS); - - if (clientIsReady) { - // Run the application in server side. - runServerApplication(sslSocket); - } else { // Otherwise, ignore - // We don't actually care about plain socket connections - // for TLS communication testing generally. Just ignore - // the test if the accepted connection is not linked to - // the expected client or the client connection timeout - // in 30 seconds. - System.out.println( - "The client is not the expected one or timeout. " + - "Ignore in server side."); - } - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - } - - /* - * Define the server side application of the test for the specified socket. - */ - void runServerApplication(SSLSocket socket) throws Exception { - // here comes the test logic - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - /* - * Define the client side of the test. - */ - void doClientSide() throws Exception { - - // Wait for server to get started. - // - // The server side takes care of the issue if the server cannot - // get started in 90 seconds. The client side would just ignore - // the test case if the serer is not ready. - boolean serverIsReady = - serverCondition.await(90L, TimeUnit.SECONDS); - if (!serverIsReady) { - System.out.println( - "The server is not ready yet in 90 seconds. " + - "Ignore in client side."); - return; - } - - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) { - try { - sslSocket.connect( - new InetSocketAddress("localhost", serverPort), 15000); - } catch (IOException ioe) { - // The server side may be impacted by naughty test cases or - // third party routines, and cannot accept connections. - // - // Just ignore the test if the connection cannot be - // established. - System.out.println( - "Cannot make a connection in 15 seconds. " + - "Ignore in client side."); - return; - } - - // OK, here the client and server get connected. - - // Signal the server, the client is ready to communicate. - clientCondition.countDown(); - - // There is still a chance in theory that the server thread may - // wait client-ready timeout and then quit. The chance should - // be really rare so we don't consider it until it becomes a - // real problem. - - // Run the application in client side. - runClientApplication(sslSocket); - } - } - - /* - * Define the server side application of the test for the specified socket. - */ - void runClientApplication(SSLSocket socket) throws Exception { - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - private volatile Exception serverException = null; - private volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new SSLSocketSample(); - } - - private Thread clientThread = null; - private Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketSample() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.out.println("Server died: " + e); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - System.out.println("Server failed: " + e); - serverException = e; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.out.println("Client died: " + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - System.out.println("Client failed: " + e); - clientException = e; - } - } - } -} diff --git a/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java b/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java index 12dfcaacae5..9b4c65536d2 100644 --- a/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java +++ b/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java @@ -21,251 +21,561 @@ * questions. */ -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; +import java.security.KeyStore; +import java.security.Security; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +/** + * This class defines a framework for JSSE tests. + * + * Please run in othervm mode. SunJSSE does not support dynamic system + * properties, no way to re-use system properties in samevm/agentvm mode. + */ /* * @test * @bug 1234567 - * @summary Use this template to help speed your client/server tests. + * @summary Use this class for JSSE tests * @run main/othervm SSLSocketTemplate * @author Brad Wetmore */ -import java.io.*; -import javax.net.ssl.*; - public class SSLSocketTemplate { + public static final String TEST_SRC = System.getProperty("test.src", "."); + /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. + * Where do we find the keystores? */ + public static final String PATH_TO_STORES = "../etc"; + public static final String KEY_STORE_FILE = "keystore"; + public static final String TRUST_STORE_FILE = "truststore"; + public static final String PASSWORD = "passphrase"; + + public static final int FREE_PORT = 0; + + // in seconds + public static final long CLIENT_SIGNAL_TIMEOUT = 30L; + public static final long SERVER_SIGNAL_TIMEOUT = 90L; + + // in millis + public static final int CLIENT_TIMEOUT = 15000; + public static final int SERVER_TIMEOUT = 30000; /* * Should we run the client or server in a separate thread? * Both sides can throw exceptions, but do you have a preference * as to which side should be the main thread. */ - static boolean separateServerThread = false; + private boolean separateServerThread = false; /* - * Where do we find the keystores? + * What's the server port? Use any free port by default */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; + private volatile int serverPort; + + private volatile Exception serverException; + private volatile Exception clientException; + + private Thread clientThread; + private Thread serverThread; + + private Peer serverPeer; + private Peer clientPeer; + + private Application serverApplication; + private Application clientApplication; + + private SSLContext context; /* * Is the server ready to serve? */ - volatile static boolean serverReady = false; + private final CountDownLatch serverReadyCondition = new CountDownLatch(1); /* - * Turn on SSL debugging? + * Is the client ready to handshake? */ - static boolean debug = false; + private final CountDownLatch clientReadyCondition = new CountDownLatch(1); /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... + * Is the server done? + */ + private final CountDownLatch serverDoneCondition = new CountDownLatch(1); + + /* + * Is the client done? + */ + private final CountDownLatch clientDoneCondition = new CountDownLatch(1); + + /* + * Public API. + */ + + public static interface Peer { + void run(SSLSocketTemplate test) throws Exception; + } + + public static interface Application { + void run(SSLSocket socket, SSLSocketTemplate test) throws Exception; + } + + public static void debug() { + debug("ssl"); + } + + public static void debug(String mode) { + System.setProperty("javax.net.debug", mode); + } + + public static void setup(String keyFilename, String trustFilename, + String password) { + + System.setProperty("javax.net.ssl.keyStore", keyFilename); + System.setProperty("javax.net.ssl.keyStorePassword", password); + System.setProperty("javax.net.ssl.trustStore", trustFilename); + System.setProperty("javax.net.ssl.trustStorePassword", password); + } + + public static void setup() throws Exception { + String keyFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" + + KEY_STORE_FILE; + String trustFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" + + TRUST_STORE_FILE; + + setup(keyFilename, trustFilename, PASSWORD); + } + + public static void print(String message, Throwable... errors) { + synchronized (System.out) { + System.out.println(message); + for (Throwable e : errors) { + e.printStackTrace(System.out); + } + } + } + + public static KeyStore loadJksKeyStore(String filename, String password) + throws Exception { + + return loadKeyStore(filename, password, "JKS"); + } + + public static KeyStore loadKeyStore(String filename, String password, + String type) throws Exception { + + KeyStore keystore = KeyStore.getInstance(type); + FileInputStream fis = new FileInputStream(filename); + try { + keystore.load(fis, password.toCharArray()); + } finally { + fis.close(); + } + return keystore; + } + + // Try to accept a connection in 30 seconds. + public static SSLSocket accept(SSLServerSocket sslServerSocket) + throws IOException { + + return accept(sslServerSocket, SERVER_TIMEOUT); + } + + public static SSLSocket accept(SSLServerSocket sslServerSocket, int timeout) + throws IOException { + + try { + sslServerSocket.setSoTimeout(timeout); + return (SSLSocket) sslServerSocket.accept(); + } catch (SocketTimeoutException ste) { + print("Warning: ", ste); + return null; + } + } + + public SSLSocketTemplate setSeparateServerThread( + boolean separateServerThread) { + + this.separateServerThread = separateServerThread; + return this; + } + + public SSLSocketTemplate setServerPort(int serverPort) { + this.serverPort = serverPort; + return this; + } + + public int getServerPort() { + return serverPort; + } + + public SSLSocketTemplate setSSLContext(SSLContext context) { + this.context = context; + return this; + } + + public SSLContext getSSLContext() { + return context; + } + + public SSLServerSocketFactory getSSLServerSocketFactory() { + if (context != null) { + return context.getServerSocketFactory(); + } + + return (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + } + + public SSLSocketFactory getSSLSocketFactory() { + if (context != null) { + return context.getSocketFactory(); + } + + return (SSLSocketFactory) SSLSocketFactory.getDefault(); + } + + public void signalServerReady() { + serverReadyCondition.countDown(); + } + + public void signalServerDone() { + serverDoneCondition.countDown(); + } + + public boolean waitForClientSignal(long timeout, TimeUnit unit) + throws InterruptedException { + + return clientReadyCondition.await(timeout, unit); + } + + public boolean waitForClientSignal() throws InterruptedException { + return waitForClientSignal(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public boolean waitForClientDone(long timeout, TimeUnit unit) + throws InterruptedException { + + return clientDoneCondition.await(timeout, unit); + } + + public boolean waitForClientDone() throws InterruptedException { + return waitForClientDone(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public void signalClientReady() { + clientReadyCondition.countDown(); + } + + public void signalClientDone() { + clientDoneCondition.countDown(); + } + + public boolean waitForServerSignal(long timeout, TimeUnit unit) + throws InterruptedException { + + return serverReadyCondition.await(timeout, unit); + } + + public boolean waitForServerSignal() throws InterruptedException { + return waitForServerSignal(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public boolean waitForServerDone(long timeout, TimeUnit unit) + throws InterruptedException { + + return serverDoneCondition.await(timeout, unit); + } + + public boolean waitForServerDone() throws InterruptedException { + return waitForServerDone(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public SSLSocketTemplate setServerPeer(Peer serverPeer) { + this.serverPeer = serverPeer; + return this; + } + + public Peer getServerPeer() { + return serverPeer; + } + + public SSLSocketTemplate setServerApplication( + Application serverApplication) { + + this.serverApplication = serverApplication; + return this; + } + + public Application getServerApplication() { + return serverApplication; + } + + public SSLSocketTemplate setClientPeer(Peer clientPeer) { + this.clientPeer = clientPeer; + return this; + } + + public Peer getClientPeer() { + return clientPeer; + } + + public SSLSocketTemplate setClientApplication( + Application clientApplication) { + + this.clientApplication = clientApplication; + return this; + } + + public Application getClientApplication() { + return clientApplication; + } + + public void runTest() throws Exception { + if (separateServerThread) { + startServer(true, this); + startClient(false, this); + serverThread.join(); + } else { + startClient(true, this); + startServer(false, this); + clientThread.join(); + } + + if (clientException != null || serverException != null) { + throw new RuntimeException("Test failed"); + } + } + + public SSLSocketTemplate() { + serverPeer = new Peer() { + + @Override + public void run(SSLSocketTemplate test) throws Exception { + doServerSide(test); + } + }; + + clientPeer = new Peer() { + + @Override + public void run(SSLSocketTemplate test) throws Exception { + doClientSide(test); + } + }; + + serverApplication = new Application() { + + @Override + public void run(SSLSocket socket, SSLSocketTemplate test) + throws Exception { + + runServerApplication(socket); + } + + }; + + clientApplication = new Application() { + + @Override + public void run(SSLSocket socket, SSLSocketTemplate test) + throws Exception { + + runClientApplication(socket); + } + }; + } + + public static void main(String args[]) throws Exception { + // reset the security property to make sure that the algorithms + // and keys used in this test are not disabled. + Security.setProperty("jdk.tls.disabledAlgorithms", ""); + + // MD5 is used in this test case, don't disable MD5 algorithm. + Security.setProperty( + "jdk.certpath.disabledAlgorithms", "MD2, RSA keySize < 1024"); + + setup(); + + new SSLSocketTemplate().runTest(); + } + + /* + * Private part. */ /* * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - try (SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort)) { + private static void doServerSide(SSLSocketTemplate test) throws Exception { + SSLServerSocket sslServerSocket; - serverPort = sslServerSocket.getLocalPort(); + // kick start the server side service + SSLServerSocketFactory sslssf = test.getSSLServerSocketFactory(); + sslServerSocket = (SSLServerSocket)sslssf.createServerSocket(FREE_PORT); - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; + test.setServerPort(sslServerSocket.getLocalPort()); + print("Server is listening on port " + test.getServerPort()); - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + // Signal the client, the server is ready to accept connection. + test.signalServerReady(); - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } + // Try to accept a connection in 30 seconds. + SSLSocket sslSocket = accept(sslServerSocket); + if (sslSocket == null) { + // Ignore the test case if no connection within 30 seconds. + print("No incoming client connection in 30 seconds. " + + "Ignore in server side."); + return; } + print("Server accepted connection"); + + // handle the connection + try { + // Is it the expected client connection? + // + // Naughty test cases or third party routines may try to + // connection to this server port unintentionally. In + // order to mitigate the impact of unexpected client + // connections and avoid intermittent failure, it should + // be checked that the accepted connection is really linked + // to the expected client. + boolean clientIsReady = test.waitForClientSignal(); + + if (clientIsReady) { + // Run the application in server side. + print("Run server application"); + test.getServerApplication().run(sslSocket, test); + } else { // Otherwise, ignore + // We don't actually care about plain socket connections + // for TLS communication testing generally. Just ignore + // the test if the accepted connection is not linked to + // the expected client or the client connection timeout + // in 30 seconds. + print("The client is not the expected one or timeout. " + + "Ignore in server side."); + } + } finally { + sslSocket.close(); + sslServerSocket.close(); + } + + test.signalServerDone(); + } + + /* + * Define the server side application of the test for the specified socket. + */ + private static void runServerApplication(SSLSocket socket) + throws Exception { + + // here comes the test logic + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); + + sslIS.read(); + sslOS.write(85); + sslOS.flush(); } /* * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. */ - void doClientSide() throws Exception { + private static void doClientSide(SSLSocketTemplate test) throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); + // Wait for server to get started. + // + // The server side takes care of the issue if the server cannot + // get started in 90 seconds. The client side would just ignore + // the test case if the serer is not ready. + boolean serverIsReady = test.waitForServerSignal(); + if (!serverIsReady) { + print("The server is not ready yet in 90 seconds. " + + "Ignore in client side."); + return; } - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - try (SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort)) { - - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new SSLSocketTemplate(); - } - - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketTemplate() throws Exception { - Exception startException = null; + SSLSocketFactory sslsf = test.getSSLSocketFactory(); + SSLSocket sslSocket = (SSLSocket)sslsf.createSocket(); try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); + try { + sslSocket.connect( + new InetSocketAddress("localhost", + test.getServerPort()), CLIENT_TIMEOUT); + print("Client connected to server"); + } catch (IOException ioe) { + // The server side may be impacted by naughty test cases or + // third party routines, and cannot accept connections. + // + // Just ignore the test if the connection cannot be + // established. + print("Cannot make a connection in 15 seconds. " + + "Ignore in client side.", ioe); + return; } - } catch (Exception e) { - startException = e; + + // OK, here the client and server get connected. + + // Signal the server, the client is ready to communicate. + test.signalClientReady(); + + // There is still a chance in theory that the server thread may + // wait client-ready timeout and then quit. The chance should + // be really rare so we don't consider it until it becomes a + // real problem. + + // Run the application in client side. + print("Run client application"); + test.getClientApplication().run(sslSocket, test); + } finally { + sslSocket.close(); } - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! + test.signalClientDone(); } - void startServer(boolean newThread) throws Exception { + /* + * Define the client side application of the test for the specified socket. + */ + private static void runClientApplication(SSLSocket socket) + throws Exception { + + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); + + sslOS.write(280); + sslOS.flush(); + sslIS.read(); + } + + private void startServer(boolean newThread, SSLSocketTemplate test) + throws Exception { + if (newThread) { serverThread = new Thread() { + @Override public void run() { try { - doServerSide(); + serverPeer.run(test); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ - System.err.println("Server died..."); - serverReady = true; + print("Server died ...", e); serverException = e; } } @@ -273,27 +583,29 @@ public class SSLSocketTemplate { serverThread.start(); } else { try { - doServerSide(); + serverPeer.run(test); } catch (Exception e) { + print("Server failed ...", e); serverException = e; - } finally { - serverReady = true; } } } - void startClient(boolean newThread) throws Exception { + private void startClient(boolean newThread, SSLSocketTemplate test) + throws Exception { + if (newThread) { clientThread = new Thread() { + @Override public void run() { try { - doClientSide(); + clientPeer.run(test); } catch (Exception e) { /* * Our client thread just died. */ - System.err.println("Client died..."); + print("Client died ...", e); clientException = e; } } @@ -301,8 +613,9 @@ public class SSLSocketTemplate { clientThread.start(); } else { try { - doClientSide(); + clientPeer.run(test); } catch (Exception e) { + print("Client failed ...", e); clientException = e; } } diff --git a/jdk/test/javax/net/ssl/templates/SSLTest.java b/jdk/test/javax/net/ssl/templates/SSLTest.java deleted file mode 100644 index 61ab7ae0a15..00000000000 --- a/jdk/test/javax/net/ssl/templates/SSLTest.java +++ /dev/null @@ -1,549 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; -import java.security.KeyStore; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -/** - * Helper class for JSSE tests. - * - * Please run in othervm mode. SunJSSE does not support dynamic system - * properties, no way to re-use system properties in samevm/agentvm mode. - */ -public class SSLTest { - - public static final String TEST_SRC = System.getProperty("test.src", "."); - - /* - * Where do we find the keystores? - */ - public static final String PATH_TO_STORES = "../etc"; - public static final String KEY_STORE_FILE = "keystore"; - public static final String TRUST_STORE_FILE = "truststore"; - public static final String PASSWORD = "passphrase"; - - public static final int FREE_PORT = 0; - - // in seconds - public static final long CLIENT_SIGNAL_TIMEOUT = 30L; - public static final long SERVER_SIGNAL_TIMEOUT = 90L; - - // in millis - public static final int CLIENT_TIMEOUT = 15000; - public static final int SERVER_TIMEOUT = 30000; - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private boolean separateServerThread = false; - - /* - * What's the server port? Use any free port by default - */ - private volatile int serverPort; - - private volatile Exception serverException; - private volatile Exception clientException; - - private Thread clientThread; - private Thread serverThread; - - private Peer serverPeer; - private Peer clientPeer; - - private Application serverApplication; - private Application clientApplication; - - private SSLContext context; - - /* - * Is the server ready to serve? - */ - private final CountDownLatch serverReadyCondition = new CountDownLatch(1); - - /* - * Is the client ready to handshake? - */ - private final CountDownLatch clientReadyCondition = new CountDownLatch(1); - - /* - * Is the server done? - */ - private final CountDownLatch serverDoneCondition = new CountDownLatch(1); - - /* - * Is the client done? - */ - private final CountDownLatch clientDoneCondition = new CountDownLatch(1); - - /* - * Public API. - */ - - public static interface Peer { - void run(SSLTest test) throws Exception; - } - - public static interface Application { - void run(SSLSocket socket, SSLTest test) throws Exception; - } - - public static void debug() { - debug("ssl"); - } - - public static void debug(String mode) { - System.setProperty("javax.net.debug", mode); - } - - public static void setup(String keyFilename, String trustFilename, - String password) { - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", password); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", password); - } - - public static void setup() throws Exception { - String keyFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" - + KEY_STORE_FILE; - String trustFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" - + TRUST_STORE_FILE; - - setup(keyFilename, trustFilename, PASSWORD); - } - - public static void print(String message, Throwable... errors) { - synchronized (System.out) { - System.out.println(message); - Arrays.stream(errors).forEach(e -> e.printStackTrace(System.out)); - } - } - - public static KeyStore loadJksKeyStore(String filename, String password) - throws Exception { - - return loadKeyStore(filename, password, "JKS"); - } - - public static KeyStore loadKeyStore(String filename, String password, - String type) throws Exception { - - KeyStore keystore = KeyStore.getInstance(type); - try (FileInputStream fis = new FileInputStream(filename)) { - keystore.load(fis, password.toCharArray()); - } - return keystore; - } - - // Try to accept a connection in 30 seconds. - public static SSLSocket accept(SSLServerSocket sslServerSocket) - throws IOException { - - return accept(sslServerSocket, SERVER_TIMEOUT); - } - - public static SSLSocket accept(SSLServerSocket sslServerSocket, int timeout) - throws IOException { - - try { - sslServerSocket.setSoTimeout(timeout); - return (SSLSocket) sslServerSocket.accept(); - } catch (SocketTimeoutException ste) { - sslServerSocket.close(); - return null; - } - } - - public SSLTest setSeparateServerThread(boolean separateServerThread) { - this.separateServerThread = separateServerThread; - return this; - } - - public SSLTest setServerPort(int serverPort) { - this.serverPort = serverPort; - return this; - } - - public int getServerPort() { - return serverPort; - } - - public SSLTest setSSLContext(SSLContext context) { - this.context = context; - return this; - } - - public SSLContext getSSLContext() { - return context; - } - - public SSLServerSocketFactory getSSLServerSocketFactory() { - if (context != null) { - return context.getServerSocketFactory(); - } - - return (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - } - - public SSLSocketFactory getSSLSocketFactory() { - if (context != null) { - return context.getSocketFactory(); - } - - return (SSLSocketFactory) SSLSocketFactory.getDefault(); - } - - public void signalServerReady() { - serverReadyCondition.countDown(); - } - - public void signalServerDone() { - serverDoneCondition.countDown(); - } - - public boolean waitForClientSignal(long timeout, TimeUnit unit) - throws InterruptedException { - - return clientReadyCondition.await(timeout, unit); - } - - public boolean waitForClientSignal() throws InterruptedException { - return waitForClientSignal(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public boolean waitForClientDone(long timeout, TimeUnit unit) - throws InterruptedException { - - return clientDoneCondition.await(timeout, unit); - } - - public boolean waitForClientDone() throws InterruptedException { - return waitForClientDone(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public void signalClientReady() { - clientReadyCondition.countDown(); - } - - public void signalClientDone() { - clientDoneCondition.countDown(); - } - - public boolean waitForServerSignal(long timeout, TimeUnit unit) - throws InterruptedException { - - return serverReadyCondition.await(timeout, unit); - } - - public boolean waitForServerSignal() throws InterruptedException { - return waitForServerSignal(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public boolean waitForServerDone(long timeout, TimeUnit unit) - throws InterruptedException { - - return serverDoneCondition.await(timeout, unit); - } - - public boolean waitForServerDone() throws InterruptedException { - return waitForServerDone(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public SSLTest setServerPeer(Peer serverPeer) { - this.serverPeer = serverPeer; - return this; - } - - public Peer getServerPeer() { - return serverPeer; - } - - public SSLTest setServerApplication(Application serverApplication) { - this.serverApplication = serverApplication; - return this; - } - - public Application getServerApplication() { - return serverApplication; - } - - public SSLTest setClientPeer(Peer clientPeer) { - this.clientPeer = clientPeer; - return this; - } - - public Peer getClientPeer() { - return clientPeer; - } - - public SSLTest setClientApplication(Application clientApplication) { - this.clientApplication = clientApplication; - return this; - } - - public Application getClientApplication() { - return clientApplication; - } - - public void runTest() throws Exception { - if (separateServerThread) { - startServer(true, this); - startClient(false, this); - serverThread.join(); - } else { - startClient(true, this); - startServer(false, this); - clientThread.join(); - } - - if (clientException != null || serverException != null) { - throw new RuntimeException("Test failed"); - } - } - - public SSLTest() { - serverPeer = (test) -> doServerSide(test); - clientPeer = (test) -> doClientSide(test); - serverApplication = (socket, test) -> runServerApplication(socket); - clientApplication = (socket, test) -> runClientApplication(socket); - } - - /* - * Private part. - */ - - - /* - * Define the server side of the test. - */ - private static void doServerSide(SSLTest test) throws Exception { - SSLServerSocket sslServerSocket; - - // kick start the server side service - SSLServerSocketFactory sslssf = test.getSSLServerSocketFactory(); - sslServerSocket = (SSLServerSocket)sslssf.createServerSocket(FREE_PORT); - - test.setServerPort(sslServerSocket.getLocalPort()); - print("Server is listening on port " + test.getServerPort()); - - // Signal the client, the server is ready to accept connection. - test.signalServerReady(); - - // Try to accept a connection in 30 seconds. - SSLSocket sslSocket = accept(sslServerSocket); - if (sslSocket == null) { - // Ignore the test case if no connection within 30 seconds. - print("No incoming client connection in 30 seconds. " - + "Ignore in server side."); - return; - } - print("Server accepted connection"); - - // handle the connection - try { - // Is it the expected client connection? - // - // Naughty test cases or third party routines may try to - // connection to this server port unintentionally. In - // order to mitigate the impact of unexpected client - // connections and avoid intermittent failure, it should - // be checked that the accepted connection is really linked - // to the expected client. - boolean clientIsReady = test.waitForClientSignal(); - - if (clientIsReady) { - // Run the application in server side. - print("Run server application"); - test.getServerApplication().run(sslSocket, test); - } else { // Otherwise, ignore - // We don't actually care about plain socket connections - // for TLS communication testing generally. Just ignore - // the test if the accepted connection is not linked to - // the expected client or the client connection timeout - // in 30 seconds. - print("The client is not the expected one or timeout. " - + "Ignore in server side."); - } - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - - test.signalServerDone(); - } - - /* - * Define the server side application of the test for the specified socket. - */ - private static void runServerApplication(SSLSocket socket) - throws Exception { - - // here comes the test logic - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - /* - * Define the client side of the test. - */ - private static void doClientSide(SSLTest test) throws Exception { - - // Wait for server to get started. - // - // The server side takes care of the issue if the server cannot - // get started in 90 seconds. The client side would just ignore - // the test case if the serer is not ready. - boolean serverIsReady = test.waitForServerSignal(); - if (!serverIsReady) { - print("The server is not ready yet in 90 seconds. " - + "Ignore in client side."); - return; - } - - SSLSocketFactory sslsf = test.getSSLSocketFactory(); - try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) { - try { - sslSocket.connect( - new InetSocketAddress("localhost", - test.getServerPort()), CLIENT_TIMEOUT); - print("Client connected to server"); - } catch (IOException ioe) { - // The server side may be impacted by naughty test cases or - // third party routines, and cannot accept connections. - // - // Just ignore the test if the connection cannot be - // established. - print("Cannot make a connection in 15 seconds. " - + "Ignore in client side.", ioe); - return; - } - - // OK, here the client and server get connected. - - // Signal the server, the client is ready to communicate. - test.signalClientReady(); - - // There is still a chance in theory that the server thread may - // wait client-ready timeout and then quit. The chance should - // be really rare so we don't consider it until it becomes a - // real problem. - - // Run the application in client side. - print("Run client application"); - test.getClientApplication().run(sslSocket, test); - } - - test.signalClientDone(); - } - - /* - * Define the client side application of the test for the specified socket. - */ - private static void runClientApplication(SSLSocket socket) - throws Exception { - - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - private void startServer(boolean newThread, SSLTest test) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - serverPeer.run(test); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - print("Server died ...", e); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - serverPeer.run(test); - } catch (Exception e) { - print("Server failed ...", e); - serverException = e; - } - } - } - - private void startClient(boolean newThread, SSLTest test) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - clientPeer.run(test); - } catch (Exception e) { - /* - * Our client thread just died. - */ - print("Client died ...", e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - clientPeer.run(test); - } catch (Exception e) { - print("Client failed ...", e); - clientException = e; - } - } - } -} diff --git a/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java b/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java index 4e4b8379bad..a2f3fb034fa 100644 --- a/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java +++ b/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java @@ -63,7 +63,7 @@ import static java.nio.charset.StandardCharsets.US_ASCII; * authentication proxy */ -public class ProxyAuthTest { +public class ProxyAuthTest extends SSLSocketTemplate { /* * Where do we find the keystores? */ @@ -96,13 +96,13 @@ public class ProxyAuthTest { expectSuccess = args[0].equals("succeed"); String keyFilename = - SSLTest.TEST_SRC + "/" + pathToStores + "/" + keyStoreFile; + TEST_SRC + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = - SSLTest.TEST_SRC + "/" + pathToStores + "/" + trustStoreFile; + TEST_SRC + "/" + pathToStores + "/" + trustStoreFile; - SSLTest.setup(keyFilename, trustFilename, passwd); + setup(keyFilename, trustFilename, passwd); - new SSLTest() + new SSLSocketTemplate() .setServerApplication((socket, test) -> { DataOutputStream out = new DataOutputStream( socket.getOutputStream()); @@ -164,7 +164,7 @@ public class ProxyAuthTest { .runTest(); } - static void doClientSide(SSLTest test) throws IOException { + static void doClientSide(SSLSocketTemplate test) throws IOException { // Wait for server to get started. // diff --git a/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java b/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java index 8543f9dd904..8554885d9fe 100644 --- a/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java +++ b/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java @@ -45,20 +45,20 @@ import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; -public class ServerIdentityTest { +public class ServerIdentityTest extends SSLSocketTemplate { private static final String PASSWORD = "changeit"; public static void main(String[] args) throws Exception { final String keystore = args[0]; - String keystoreFilename = SSLTest.TEST_SRC + "/" + keystore; + String keystoreFilename = TEST_SRC + "/" + keystore; - SSLTest.setup(keystoreFilename, keystoreFilename, PASSWORD); + setup(keystoreFilename, keystoreFilename, PASSWORD); SSLContext context = SSLContext.getInstance("SSL"); KeyManager[] kms = new KeyManager[1]; - KeyStore ks = SSLTest.loadJksKeyStore(keystoreFilename, PASSWORD); + KeyStore ks = loadJksKeyStore(keystoreFilename, PASSWORD); KeyManager km = new MyKeyManager(ks, PASSWORD.toCharArray()); kms[0] = km; context.init(kms, null, null); @@ -70,7 +70,7 @@ public class ServerIdentityTest { */ System.out.println("Testing " + keystore); - new SSLTest() + new SSLSocketTemplate() .setSSLContext(context) .setServerApplication((socket, test) -> { BufferedWriter bw = new BufferedWriter( @@ -79,12 +79,12 @@ public class ServerIdentityTest { bw.flush(); Thread.sleep(2000); socket.getSession().invalidate(); - SSLTest.print("Server application is done"); + print("Server application is done"); }) .setClientPeer((test) -> { boolean serverIsReady = test.waitForServerSignal(); if (!serverIsReady) { - SSLTest.print( + print( "The server is not ready, ignore on client side."); return; } @@ -100,7 +100,7 @@ public class ServerIdentityTest { ((HttpURLConnection) url.openConnection()) .getInputStream().close(); - SSLTest.print("Client is done"); + print("Client is done"); }).runTest(); } } diff --git a/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java b/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java index a380342616d..bb134aa4224 100644 --- a/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java +++ b/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java @@ -42,7 +42,7 @@ import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; -public class AnonCipherWithWantClientAuth { +public class AnonCipherWithWantClientAuth extends SSLSocketTemplate { /* * Where do we find the keystores? @@ -62,16 +62,16 @@ public class AnonCipherWithWantClientAuth { String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; - SSLTest.setup(keyFilename, trustFilename, passwd); + setup(keyFilename, trustFilename, passwd); - new SSLTest() + new SSLSocketTemplate() .setServerPeer(test -> { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(SSLTest.FREE_PORT); + (SSLServerSocket) sslssf.createServerSocket(FREE_PORT); test.setServerPort(sslServerSocket.getLocalPort()); - SSLTest.print("Server is listening on port " + print("Server is listening on port " + test.getServerPort()); String ciphers[] = { @@ -85,14 +85,14 @@ public class AnonCipherWithWantClientAuth { test.signalServerReady(); // Try to accept a connection in 30 seconds. - SSLSocket sslSocket = SSLTest.accept(sslServerSocket); + SSLSocket sslSocket = accept(sslServerSocket); if (sslSocket == null) { // Ignore the test case if no connection within 30 seconds. - SSLTest.print("No incoming client connection in 30 seconds." + print("No incoming client connection in 30 seconds." + " Ignore in server side."); return; } - SSLTest.print("Server accepted connection"); + print("Server accepted connection"); // handle the connection try { @@ -108,7 +108,7 @@ public class AnonCipherWithWantClientAuth { if (clientIsReady) { // Run the application in server side. - SSLTest.print("Run server application"); + print("Run server application"); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); From 4bcf62b9d10edb7b3ccf1a1bd2d3fd4cdec47516 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 16 Nov 2016 14:26:12 -0800 Subject: [PATCH 051/402] 8132097: Stream.generate should use a covariant Supplier as parameter Reviewed-by: forax, martin --- jdk/src/java.base/share/classes/java/util/stream/Stream.java | 2 +- .../share/classes/java/util/stream/StreamSpliterators.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/stream/Stream.java b/jdk/src/java.base/share/classes/java/util/stream/Stream.java index 1ec21ed2b57..225664042a6 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/Stream.java +++ b/jdk/src/java.base/share/classes/java/util/stream/Stream.java @@ -1327,7 +1327,7 @@ public interface Stream extends BaseStream> { * @param s the {@code Supplier} of generated elements * @return a new infinite sequential unordered {@code Stream} */ - public static Stream generate(Supplier s) { + public static Stream generate(Supplier s) { Objects.requireNonNull(s); return StreamSupport.stream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); diff --git a/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java b/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java index 8236255d5ef..4606ce30306 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java +++ b/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java @@ -1346,9 +1346,9 @@ class StreamSpliterators { } static final class OfRef extends InfiniteSupplyingSpliterator { - final Supplier s; + final Supplier s; - OfRef(long size, Supplier s) { + OfRef(long size, Supplier s) { super(size); this.s = s; } From ce32d2aec8981f7d4730dd39c12a1ec283c72c54 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 16 Nov 2016 14:26:14 -0800 Subject: [PATCH 052/402] 8072784: Better spliterator implementation for BitSet.stream() Reviewed-by: martin --- .../share/classes/java/util/BitSet.java | 167 +++++++++++++++--- .../java/util/BitSet/BitSetStreamTest.java | 85 +++++---- ...SpliteratorTraversingAndSplittingTest.java | 30 ++++ 3 files changed, 223 insertions(+), 59 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/BitSet.java b/jdk/src/java.base/share/classes/java/util/BitSet.java index f65035f0601..4e35b34ae9f 100644 --- a/jdk/src/java.base/share/classes/java/util/BitSet.java +++ b/jdk/src/java.base/share/classes/java/util/BitSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; +import java.util.function.IntConsumer; import java.util.stream.IntStream; import java.util.stream.StreamSupport; @@ -1217,32 +1218,156 @@ public class BitSet implements Cloneable, java.io.Serializable { * @since 1.8 */ public IntStream stream() { - class BitSetIterator implements PrimitiveIterator.OfInt { - int next = nextSetBit(0); + class BitSetSpliterator implements Spliterator.OfInt { + private int index; // current bit index for a set bit + private int fence; // -1 until used; then one past last bit index + private int est; // size estimate + private boolean root; // true if root and not split + // root == true then size estimate is accurate + // index == -1 or index >= fence if fully traversed + // Special case when the max bit set is Integer.MAX_VALUE - @Override - public boolean hasNext() { - return next != -1; + BitSetSpliterator(int origin, int fence, int est, boolean root) { + this.index = origin; + this.fence = fence; + this.est = est; + this.root = root; + } + + private int getFence() { + int hi; + if ((hi = fence) < 0) { + // Round up fence to maximum cardinality for allocated words + // This is sufficient and cheap for sequential access + // When splitting this value is lowered + hi = fence = (wordsInUse >= wordIndex(Integer.MAX_VALUE)) + ? Integer.MAX_VALUE + : wordsInUse << ADDRESS_BITS_PER_WORD; + est = cardinality(); + index = nextSetBit(0); + } + return hi; } @Override - public int nextInt() { - if (next != -1) { - int ret = next; - next = (next == Integer.MAX_VALUE) ? -1 : nextSetBit(next+1); - return ret; - } else { - throw new NoSuchElementException(); + public boolean tryAdvance(IntConsumer action) { + Objects.requireNonNull(action); + + int hi = getFence(); + int i = index; + if (i < 0 || i >= hi) { + // Check if there is a final bit set for Integer.MAX_VALUE + if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) { + index = -1; + action.accept(Integer.MAX_VALUE); + return true; + } + return false; + } + + index = nextSetBit(i + 1, wordIndex(hi - 1)); + action.accept(i); + return true; + } + + @Override + public void forEachRemaining(IntConsumer action) { + Objects.requireNonNull(action); + + int hi = getFence(); + int i = index; + int v = wordIndex(hi - 1); + index = -1; + while (i >= 0 && i < hi) { + action.accept(i); + i = nextSetBit(i + 1, v); + } + // Check if there is a final bit set for Integer.MAX_VALUE + if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) { + action.accept(Integer.MAX_VALUE); } } - } - return StreamSupport.intStream( - () -> Spliterators.spliterator( - new BitSetIterator(), cardinality(), - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), - Spliterator.SIZED | Spliterator.SUBSIZED | - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, - false); + @Override + public OfInt trySplit() { + int hi = getFence(); + int lo = index; + if (lo < 0) { + return null; + } + + // Lower the fence to be the upper bound of last bit set + // The index is the first bit set, thus this spliterator + // covers one bit and cannot be split, or two or more + // bits + hi = fence = (hi < Integer.MAX_VALUE || !get(Integer.MAX_VALUE)) + ? previousSetBit(hi - 1) + 1 + : Integer.MAX_VALUE; + + // Find the mid point + int mid = (lo + hi) >>> 1; + if (lo >= mid) { + return null; + } + + // Raise the index of this spliterator to be the next set bit + // from the mid point + index = nextSetBit(mid, wordIndex(hi - 1)); + root = false; + + // Don't lower the fence (mid point) of the returned spliterator, + // traversal or further splitting will do that work + return new BitSetSpliterator(lo, mid, est >>>= 1, false); + } + + @Override + public long estimateSize() { + getFence(); // force init + return est; + } + + @Override + public int characteristics() { + // Only sized when root and not split + return (root ? Spliterator.SIZED : 0) | + Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED; + } + + @Override + public Comparator getComparator() { + return null; + } + } + return StreamSupport.intStream(new BitSetSpliterator(0, -1, 0, true), false); } + + /** + * Returns the index of the first bit that is set to {@code true} + * that occurs on or after the specified starting index and up to and + * including the specified word index + * If no such bit exists then {@code -1} is returned. + * + * @param fromIndex the index to start checking from (inclusive) + * @param toWordIndex the last word index to check (inclusive) + * @return the index of the next set bit, or {@code -1} if there + * is no such bit + */ + private int nextSetBit(int fromIndex, int toWordIndex) { + int u = wordIndex(fromIndex); + // Check if out of bounds + if (u > toWordIndex) + return -1; + + long word = words[u] & (WORD_MASK << fromIndex); + + while (true) { + if (word != 0) + return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); + // Check if out of bounds + if (++u > toWordIndex) + return -1; + word = words[u]; + } + } + } diff --git a/jdk/test/java/util/BitSet/BitSetStreamTest.java b/jdk/test/java/util/BitSet/BitSetStreamTest.java index d4e2d8d4919..87f9f05a753 100644 --- a/jdk/test/java/util/BitSet/BitSetStreamTest.java +++ b/jdk/test/java/util/BitSet/BitSetStreamTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,25 +60,6 @@ public class BitSetStreamTest { public int getAsInt() { int s = n1; n1 = n2; n2 = s + n1; return s; } } - private static final Object[][] testcases = new Object[][] { - { "none", IntStream.empty() }, - { "index 0", IntStream.of(0) }, - { "index 255", IntStream.of(255) }, - { "every bit", IntStream.range(0, 255) }, - { "step 2", IntStream.range(0, 255).map(f -> f * 2) }, - { "step 3", IntStream.range(0, 255).map(f -> f * 3) }, - { "step 5", IntStream.range(0, 255).map(f -> f * 5) }, - { "step 7", IntStream.range(0, 255).map(f -> f * 7) }, - { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) }, - { "max int", IntStream.of(Integer.MAX_VALUE) }, - { "25 fibs", IntStream.generate(new Fibs()).limit(25) } - }; - - @DataProvider(name = "cases") - public static Object[][] produceCases() { - return testcases; - } - @Test public void testFibs() { Fibs f = new Fibs(); @@ -93,22 +74,46 @@ public class BitSetStreamTest { assertEquals(987, Fibs.fibs(16)); } + + @DataProvider(name = "cases") + public static Object[][] produceCases() { + return new Object[][] { + { "none", IntStream.empty() }, + { "index 0", IntStream.of(0) }, + { "index 255", IntStream.of(255) }, + { "index 0 and 255", IntStream.of(0, 255) }, + { "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE) }, + { "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1) }, + { "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE) }, + { "every bit", IntStream.range(0, 255) }, + { "step 2", IntStream.range(0, 255).map(f -> f * 2) }, + { "step 3", IntStream.range(0, 255).map(f -> f * 3) }, + { "step 5", IntStream.range(0, 255).map(f -> f * 5) }, + { "step 7", IntStream.range(0, 255).map(f -> f * 7) }, + { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) }, + { "25 fibs", IntStream.generate(new Fibs()).limit(25) } + }; + } + @Test(dataProvider = "cases") public void testBitsetStream(String name, IntStream data) { - BitSet bs = new BitSet(); - long setBits = data.distinct() - .peek(i -> bs.set(i)) - .count(); + BitSet bs = data.collect(BitSet::new, BitSet::set, BitSet::or); - assertEquals(bs.cardinality(), setBits); - assertEquals(bs.cardinality(), bs.stream().reduce(0, (s, i) -> s+1)); + assertEquals(bs.cardinality(), bs.stream().count()); + + int[] indexHolder = new int[] { -1 }; + bs.stream().forEach(i -> { + int ei = indexHolder[0]; + indexHolder[0] = bs.nextSetBit(ei + 1); + assertEquals(i, indexHolder[0]); + }); PrimitiveIterator.OfInt it = bs.stream().iterator(); - for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { + for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { assertTrue(it.hasNext()); assertEquals(it.nextInt(), i); if (i == Integer.MAX_VALUE) - break; // or (i+1) would overflow + break; // or (i + 1) would overflow } assertFalse(it.hasNext()); } @@ -123,16 +128,20 @@ public class BitSetStreamTest { for (int seed : seeds) { final Random random = new Random(seed); random.nextBytes(bytes); - final BitSet bitSet = BitSet.valueOf(bytes); - final int cardinality = bitSet.cardinality(); - final IntStream stream = bitSet.stream(); - final int[] array = stream.toArray(); - assertEquals(array.length, cardinality); - int nextSetBit = -1; - for (int i=0; i < cardinality; i++) { - nextSetBit = bitSet.nextSetBit(nextSetBit + 1); - assertEquals(array[i], nextSetBit); - } + + BitSet bitSet = BitSet.valueOf(bytes); + testBitSetContents(bitSet, bitSet.stream().toArray()); + testBitSetContents(bitSet, bitSet.stream().parallel().toArray()); + } + } + + void testBitSetContents(BitSet bitSet, int[] array) { + int cardinality = bitSet.cardinality(); + assertEquals(array.length, cardinality); + int nextSetBit = -1; + for (int i = 0; i < cardinality; i++) { + nextSetBit = bitSet.nextSetBit(nextSetBit + 1); + assertEquals(array[i], nextSetBit); } } } diff --git a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java index a8d6a9c6471..6d00fd6a3e3 100644 --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java @@ -37,6 +37,7 @@ import java.util.AbstractSet; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -80,7 +81,9 @@ import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; +import java.util.stream.IntStream; +import static java.util.stream.Collectors.toList; import static org.testng.Assert.*; import static org.testng.Assert.assertEquals; @@ -883,6 +886,33 @@ public class SpliteratorTraversingAndSplittingTest { cdb.add("new StringBuffer(\"%s\")", StringBuffer::new); } + + Object[][] bitStreamTestcases = new Object[][] { + { "none", IntStream.empty().toArray() }, + { "index 0", IntStream.of(0).toArray() }, + { "index 255", IntStream.of(255).toArray() }, + { "index 0 and 255", IntStream.of(0, 255).toArray() }, + { "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE).toArray() }, + { "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1).toArray() }, + { "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE).toArray() }, + { "every bit", IntStream.range(0, 255).toArray() }, + { "step 2", IntStream.range(0, 255).map(f -> f * 2).toArray() }, + { "step 3", IntStream.range(0, 255).map(f -> f * 3).toArray() }, + { "step 5", IntStream.range(0, 255).map(f -> f * 5).toArray() }, + { "step 7", IntStream.range(0, 255).map(f -> f * 7).toArray() }, + { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000).toArray() }, + }; + for (Object[] tc : bitStreamTestcases) { + String description = (String)tc[0]; + int[] exp = (int[])tc[1]; + SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder( + data, IntStream.of(exp).boxed().collect(toList())); + + db.add("BitSet.stream.spliterator() {" + description + "}", () -> + IntStream.of(exp).collect(BitSet::new, BitSet::set, BitSet::or). + stream().spliterator() + ); + } return spliteratorOfIntDataProvider = data.toArray(new Object[0][]); } From a7d4828bea82c64e295f9b62aa6afb74fa28b2df Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Wed, 16 Nov 2016 17:29:14 -0800 Subject: [PATCH 053/402] 8169764: output more information when java/nio/channels/AsynchronousSocketChannel/Basic.java fails Reviewed-by: alanb --- .../AsynchronousSocketChannel/Basic.java | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java index e12ab09c32b..f98fca05391 100644 --- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java +++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java @@ -219,7 +219,8 @@ public class Basic { throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } final AtomicReference connectException = new AtomicReference<>(); ch.connect(server.address(), (Void)null, new CompletionHandler() { @@ -233,7 +234,8 @@ public class Basic { Thread.sleep(100); } if (!(connectException.get() instanceof ClosedChannelException)) - throw new RuntimeException("ClosedChannelException expected"); + throw new RuntimeException("ClosedChannelException expected", + connectException.get()); } // test that failure to connect closes the channel @@ -353,7 +355,8 @@ public class Basic { Thread.sleep(100); } if (!(writeException.get() instanceof AsynchronousCloseException)) - throw new RuntimeException("AsynchronousCloseException expected"); + throw new RuntimeException("AsynchronousCloseException expected", + writeException.get()); } } @@ -460,7 +463,8 @@ public class Basic { throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } } } @@ -630,7 +634,8 @@ public class Basic { throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } } } @@ -738,7 +743,8 @@ public class Basic { throw new RuntimeException("ClosedChannelException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("ClosedChannelException expected"); + throw new RuntimeException("ClosedChannelException expected", + x.getCause()); } } } @@ -776,7 +782,8 @@ public class Basic { Thread.sleep(100); } if (!(readException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); + throw new RuntimeException("InterruptedByTimeoutException expected", + readException.get()); // after a timeout then further reading should throw unspecified runtime exception boolean exceptionThrown = false; @@ -813,7 +820,8 @@ public class Basic { Thread.sleep(100); } if (!(writeException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); + throw new RuntimeException("InterruptedByTimeoutException expected", + writeException.get()); // after a timeout then further writing should throw unspecified runtime exception boolean exceptionThrown = false; From 5b06ce3c07c7f26e7b47d920c6975b5dfed61243 Mon Sep 17 00:00:00 2001 From: Nancy Nigam Date: Thu, 17 Nov 2016 11:40:50 +0530 Subject: [PATCH 054/402] 8165296: update existing i18n test cases of test/java/util Reviewed-by: okutsu --- jdk/test/java/text/testlib/IntlTest.java | 14 +- jdk/test/java/util/Calendar/Bug4766302.java | 2 + jdk/test/java/util/Calendar/Bug4958050.java | 124 +- .../util/Calendar/CalendarRegression.java | 1515 +++++++++-------- jdk/test/java/util/Calendar/CalendarTest.java | 1068 ++++++------ .../java/util/Calendar/CalendarTypeTest.java | 22 +- .../java/util/Calendar/FieldStateTest.java | 25 +- .../util/Calendar/GregorianCutoverTest.java | 37 +- jdk/test/java/util/Calendar/JavatimeTest.java | 49 +- jdk/test/java/util/Calendar/Koyomi.java | 34 +- .../java/util/Calendar/NonLenientTest.java | 40 +- jdk/test/java/util/Calendar/ZoneOffsets.java | 50 +- jdk/test/java/util/Calendar/bug4372743.java | 107 +- jdk/test/java/util/Calendar/bug4401223.java | 23 +- jdk/test/java/util/Calendar/bug4514831.java | 57 +- jdk/test/java/util/Date/Bug4955000.java | 42 +- jdk/test/java/util/Locale/Bug4175998Test.java | 6 +- jdk/test/java/util/Locale/Bug4184873Test.java | 5 +- jdk/test/java/util/Locale/Bug8001562.java | 69 +- jdk/test/java/util/Locale/HashCodeTest.java | 17 +- .../java/util/Locale/LocaleEnhanceTest.java | 3 +- jdk/test/java/util/Locale/LocaleTest.java | 467 ++--- jdk/test/java/util/Locale/LocaleTestFmwk.java | 267 --- 23 files changed, 2006 insertions(+), 2037 deletions(-) delete mode 100644 jdk/test/java/util/Locale/LocaleTestFmwk.java diff --git a/jdk/test/java/text/testlib/IntlTest.java b/jdk/test/java/text/testlib/IntlTest.java index d8ae8572f30..9dfb5a45193 100644 --- a/jdk/test/java/text/testlib/IntlTest.java +++ b/jdk/test/java/text/testlib/IntlTest.java @@ -89,6 +89,9 @@ public abstract class IntlTest { case "-nothrow": nothrow = true; break; + case "-exitcode": + exitCode = true; + break; default: Method m = testMethods.get(arg); if (m == null) { @@ -138,7 +141,12 @@ public abstract class IntlTest { } } if (nothrow) { - System.exit(errorCount); + if (exitCode) { + System.exit(errorCount); + } + if (errorCount > 0) { + throw new IllegalArgumentException("encountered " + errorCount + " errors"); + } } } @@ -243,7 +251,7 @@ public abstract class IntlTest { */ void usage() { System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-prompt] [test names]"); + ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); System.out.println(" Available test names:"); for (String methodName : testMethods.keySet()) { @@ -254,7 +262,7 @@ public abstract class IntlTest { private boolean prompt; private boolean nothrow; protected boolean verbose; - + private boolean exitCode; private PrintWriter log; private int indentLevel; private boolean needLineFeed; diff --git a/jdk/test/java/util/Calendar/Bug4766302.java b/jdk/test/java/util/Calendar/Bug4766302.java index 42df92b7e16..cd27e009ea2 100644 --- a/jdk/test/java/util/Calendar/Bug4766302.java +++ b/jdk/test/java/util/Calendar/Bug4766302.java @@ -29,9 +29,11 @@ import java.util.GregorianCalendar; +@SuppressWarnings("serial") public class Bug4766302 { static class MyCalendar extends GregorianCalendar { + boolean isTimeStillSet() { return isTimeSet; } diff --git a/jdk/test/java/util/Calendar/Bug4958050.java b/jdk/test/java/util/Calendar/Bug4958050.java index dfd627cda6f..2b2e6e4ff43 100644 --- a/jdk/test/java/util/Calendar/Bug4958050.java +++ b/jdk/test/java/util/Calendar/Bug4958050.java @@ -29,9 +29,11 @@ import java.util.Locale; import java.util.TimeZone; + import static java.util.Calendar.*; public class Bug4958050 { + static int errorCount = 0; public static void main(String[] args) { @@ -41,87 +43,87 @@ public class Bug4958050 { System.out.println("Time zone = " + cal.getTimeZone().getID()); // Test the week fields - int[] weekFields = { WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH }; + int[] weekFields = {WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH}; for (int i = 0; i < weekFields.length; i++) { int field = weekFields[i]; // add() cal.clear(); - cal.set(1919, DECEMBER, 14-7, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 7, 23, 50, 00); cal.add(weekFields[i], +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/07: add("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/07: add(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-7); + cal.set(1930, JUNE, 21 - 7); cal.add(weekFields[i], +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/14: add("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/14: add(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() cal.clear(); - cal.set(1919, DECEMBER, 14-7, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 7, 23, 50, 00); cal.roll(weekFields[i], +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/07: roll("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/07: roll(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-7); + cal.set(1930, JUNE, 21 - 7); cal.roll(weekFields[i], +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/14: roll("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/14: roll(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } } // Test the day fields - int[] dayFields = { DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK }; + int[] dayFields = {DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK}; for (int i = 0; i < dayFields.length; i++) { int field = dayFields[i]; // add() cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.add(field, +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/13: add("+cal.getFieldName(field)+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/13: add(" + Koyomi.getFieldName(field) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1919, DECEMBER, 14, 00, 00, 00); cal.add(field, -1); if (!cal.checkDate(1919, DECEMBER, 13)) { - error("1919/12/14: add("+cal.getFieldName(field)+", -1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/14: add(" + Koyomi.getFieldName(field) + ", -1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1); + cal.set(1930, JUNE, 21 - 1); cal.add(field, +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/20: add("+cal.getFieldName(field)+", +1)\n" - + cal.getMessage() + cal.toDateTimeString()); + error("1930/6/20: add(" + Koyomi.getFieldName(field) + ", +1)\n" + + cal.getMessage() + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(field, -1); if (!cal.checkDateTime(1930, JUNE, 20, 01, 00, 00, 000)) { - error("1930/6/21: add("+cal.getFieldName(field)+", -1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/21: add(" + Koyomi.getFieldName(field) + ", -1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() cal.clear(); - cal.set(1930, JUNE, 21-1); + cal.set(1930, JUNE, 21 - 1); int amount = +1; if (field == DAY_OF_WEEK) { amount += 700; } cal.roll(field, amount); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/20: roll("+cal.getFieldName(field)+", +"+amount+")\n" - + cal.getMessage() + " " + cal.toDateTimeString()); + error("1930/6/20: roll(" + Koyomi.getFieldName(field) + ", +" + amount + ")\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); @@ -131,93 +133,93 @@ public class Bug4958050 { } cal.roll(field, amount); if (!cal.checkDateTime(1930, JUNE, 20, 01, 00, 00, 000)) { - error("1930/6/21: roll("+cal.getFieldName(field)+", "+amount+")\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + error("1930/6/21: roll(" + Koyomi.getFieldName(field) + ", " + amount + ")\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } } // Test the AM_PM field // add() cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.add(AM_PM, +1); if (!cal.checkDate(1919, DECEMBER, 14) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1919/12/13: add(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1, 12, 00, 00); + cal.set(1930, JUNE, 21 - 1, 12, 00, 00); cal.add(AM_PM, +1); if (!cal.checkDate(1930, JUNE, 21) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/20: add(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-2, 12, 00, 00); + cal.set(1930, JUNE, 21 - 2, 12, 00, 00); cal.add(AM_PM, +3); if (!cal.checkDate(1930, JUNE, 21) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/10: add(AM_PM, +3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1919, DECEMBER, 14, 11, 50, 00); cal.add(AM_PM, -1); - if (!cal.checkDateTime(1919, DECEMBER, 14-1, 23, 50, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1919, DECEMBER, 14 - 1, 23, 50, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1919/12/14 11:50:00: add(AM_PM, -1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(AM_PM, -1); - if (!cal.checkDateTime(1930, JUNE, 21-1, 01+12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 1, 01 + 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1930/6/20: add(AM_PM, -1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(AM_PM, -3); - if (!cal.checkDateTime(1930, JUNE, 21-2, 01+12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 2, 01 + 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1930/6/10: add(AM_PM, -3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() (should NOT change the date) cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.roll(AM_PM, +1); - if (!cal.checkDateTime(1919, DECEMBER, 14-1, 23-12, 50, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1919, DECEMBER, 14 - 1, 23 - 12, 50, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1919/12/13: roll(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1, 12, 00, 00); + cal.set(1930, JUNE, 21 - 1, 12, 00, 00); cal.roll(AM_PM, +1); - if (!cal.checkDateTime(1930, JUNE, 21-1, 12-12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 1, 12 - 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/20: roll(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-2, 12, 00, 00); + cal.set(1930, JUNE, 21 - 2, 12, 00, 00); cal.roll(AM_PM, +3); - if (!cal.checkDateTime(1930, JUNE, 21-2, 12-12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 2, 12 - 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/10: roll(AM_PM, +3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // Test the HOUR_OF_DAY field @@ -227,7 +229,7 @@ public class Bug4958050 { cal.add(HOUR_OF_DAY, +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { error("1930/6/20 23:00:00: add(HOUR_OF_DAY, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() (should NOT change the date) @@ -236,7 +238,7 @@ public class Bug4958050 { cal.roll(HOUR_OF_DAY, +1); if (!cal.checkDateTime(1930, JUNE, 20, 00, 00, 00, 000)) { error("1930/6/20 23:00:00: roll(HOUR_OF_DAY, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } checkErrors(); diff --git a/jdk/test/java/util/Calendar/CalendarRegression.java b/jdk/test/java/util/Calendar/CalendarRegression.java index 2852fae33f6..8a1ebcc4544 100644 --- a/jdk/test/java/util/Calendar/CalendarRegression.java +++ b/jdk/test/java/util/Calendar/CalendarRegression.java @@ -34,11 +34,24 @@ * @library /java/text/testlib * @run main CalendarRegression */ +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.SimpleTimeZone; +import java.util.TimeZone; -import java.lang.reflect.*; -import java.io.*; -import java.util.*; -import java.text.*; +import static java.util.Calendar.*; public class CalendarRegression extends IntlTest { @@ -47,99 +60,101 @@ public class CalendarRegression extends IntlTest { } /* - Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 + Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 - ==== Here is the test ==== - public static void main (String args[]) { - java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); - logln("expected=1901-04-05 05:08:13.1234567"); - logln(" result="+t); - } + ==== Here is the test ==== + public static void main (String args[]) { + java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); + logln("expected=1901-04-05 05:08:13.1234567"); + logln(" result="+t); + } - ==== Here is the output of the test on Solaris or NT ==== - expected=1901-04-05 05:08:13.1234567 - result=1901-04-05 05:08:13.1234567 - - ==== Here is the output of the test on Windows95 ==== - expected=1901-04-05 05:08:13.1234567 - result=1901-04-05 06:08:13.1234567 - */ + ==== Here is the output of the test on Solaris or NT ==== + expected=1901-04-05 05:08:13.1234567 + result=1901-04-05 05:08:13.1234567 + ==== Here is the output of the test on Windows95 ==== + expected=1901-04-05 05:08:13.1234567 + result=1901-04-05 06:08:13.1234567 + */ public void Test4031502() { // This bug actually occurs on Windows NT as well, and doesn't // require the host zone to be set; it can be set in Java. String[] ids = TimeZone.getAvailableIDs(); boolean bad = false; - for (int i=0; i max) + } + if (dow < min || dow > max) { errln("FAIL: Day of week " + dow + " out of range"); - if (dow != Calendar.SUNDAY) + } + if (dow != SUNDAY) { errln("FAIL: Day of week should be SUNDAY Got " + dow); + } } + @SuppressWarnings("deprecation") public void Test4071385() { Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(98, Calendar.JUNE, 24)); - cal.set(Calendar.MONTH, Calendar.NOVEMBER); // change a field + cal.setTime(new Date(98, JUNE, 24)); + cal.set(MONTH, NOVEMBER); // change a field logln(cal.getTime().toString()); - if (!cal.getTime().equals(new Date(98, Calendar.NOVEMBER, 24))) + if (!cal.getTime().equals(new Date(98, NOVEMBER, 24))) { errln("Fail"); + } } public void Test4073929() { GregorianCalendar foo1 = new GregorianCalendar(1997, 8, 27); - foo1.add(Calendar.DAY_OF_MONTH, +1); - int testyear = foo1.get(Calendar.YEAR); - int testmonth = foo1.get(Calendar.MONTH); - int testday = foo1.get(Calendar.DAY_OF_MONTH); - if (testyear != 1997 || - testmonth != 8 || - testday != 28) + foo1.add(DAY_OF_MONTH, +1); + int testyear = foo1.get(YEAR); + int testmonth = foo1.get(MONTH); + int testday = foo1.get(DAY_OF_MONTH); + if (testyear != 1997 + || testmonth != 8 + || testday != 28) { errln("Fail: Calendar not initialized"); + } } public void Test4083167() { @@ -322,27 +346,26 @@ public class CalendarRegression extends IntlTest { Date firstDate = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(firstDate); - long firstMillisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L + - cal.get(Calendar.MINUTE) * 60000L + - cal.get(Calendar.SECOND) * 1000L + - cal.get(Calendar.MILLISECOND); + long firstMillisInDay = cal.get(HOUR_OF_DAY) * 3600000L + + cal.get(MINUTE) * 60000L + + cal.get(SECOND) * 1000L + + cal.get(MILLISECOND); logln("Current time: " + firstDate.toString()); - for (int validity=0; validity<30; validity++) { - Date lastDate = new Date(firstDate.getTime() + - (long)validity*1000*24*60*60); + for (int validity = 0; validity < 30; validity++) { + Date lastDate = new Date(firstDate.getTime() + + (long) validity * 1000 * 24 * 60 * 60); cal.setTime(lastDate); - long millisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L + - cal.get(Calendar.MINUTE) * 60000L + - cal.get(Calendar.SECOND) * 1000L + - cal.get(Calendar.MILLISECOND); + long millisInDay = cal.get(HOUR_OF_DAY) * 3600000L + + cal.get(MINUTE) * 60000L + + cal.get(SECOND) * 1000L + + cal.get(MILLISECOND); if (firstMillisInDay != millisInDay) { errln("Day has shifted " + lastDate); } } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } @@ -359,61 +382,60 @@ public class CalendarRegression extends IntlTest { TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); date = new SimpleDateFormat("zzzz"); - Calendar cal=Calendar.getInstance(); - cal.set(1997,Calendar.SEPTEMBER,30); - Date now=cal.getTime(); + Calendar cal = Calendar.getInstance(); + cal.set(1997, SEPTEMBER, 30); + Date now = cal.getTime(); String formattedDate = date.format(now); if (!formattedDate.equals(summerTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + int weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 40) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1996,Calendar.DECEMBER,31); - now=cal.getTime(); + cal.set(1996, DECEMBER, 31); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1997,Calendar.JANUARY,1); - now=cal.getTime(); + cal.set(1997, JANUARY, 1); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1997,Calendar.JANUARY,8); - now=cal.getTime(); + cal.set(1997, JANUARY, 8); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 2) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - } - finally { + } finally { Locale.setDefault(saveLocale); TimeZone.setDefault(saveZone); } @@ -428,9 +450,9 @@ public class CalendarRegression extends IntlTest { cal1.set( Calendar.MINUTE, 20 ); cal1.set( Calendar.SECOND, 40 ); */ - logln( " Cal1 = " + cal1.getTime().getTime() ); - logln( " Cal1 time in ms = " + cal1.get(Calendar.MILLISECOND) ); - for( int k = 0; k < 100 ; k++ ); + logln(" Cal1 = " + cal1.getTime().getTime()); + logln(" Cal1 time in ms = " + cal1.get(MILLISECOND)); + for (int k = 0; k < 100; k++); GregorianCalendar cal2 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); /*cal2.set( Calendar.YEAR, 1997 ); @@ -440,17 +462,19 @@ public class CalendarRegression extends IntlTest { cal2.set( Calendar.MINUTE, 20 ); cal2.set( Calendar.SECOND, 40 ); */ - logln( " Cal2 = " + cal2.getTime().getTime() ); - logln( " Cal2 time in ms = " + cal2.get(Calendar.MILLISECOND) ); - if( !cal1.equals( cal2 ) ) + logln(" Cal2 = " + cal2.getTime().getTime()); + logln(" Cal2 time in ms = " + cal2.get(MILLISECOND)); + if (!cal1.equals(cal2)) { errln("Fail: Milliseconds randomized"); + } } public void Test4095407() { - GregorianCalendar a = new GregorianCalendar(1997,Calendar.NOVEMBER, 13); - int dow = a.get(Calendar.DAY_OF_WEEK); - if (dow != Calendar.THURSDAY) + GregorianCalendar a = new GregorianCalendar(1997, NOVEMBER, 13); + int dow = a.get(DAY_OF_WEEK); + if (dow != THURSDAY) { errln("Fail: Want THURSDAY Got " + dow); + } } public void Test4096231() { @@ -461,72 +485,74 @@ public class CalendarRegression extends IntlTest { Calendar cal1 = new GregorianCalendar(PST); cal1.setTime(new Date(880698639000L)); int p; - logln("PST 1 is: " + (p=cal1.get(cal1.HOUR_OF_DAY))); + logln("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); cal1.setTimeZone(GMT); // Issue 1: Changing the timezone doesn't change the // represented time. - int h1,h2; - logln("GMT 1 is: " + (h1=cal1.get(cal1.HOUR_OF_DAY))); + int h1, h2; + logln("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); cal1.setTime(new Date(880698639000L)); - logln("GMT 2 is: " + (h2=cal1.get(cal1.HOUR_OF_DAY))); + logln("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); // Note: This test had a bug in it. It wanted h1!=h2, when // what was meant was h1!=p. Fixed this concurrent with fix // to 4177484. - if (p == h1 || h1 != h2) + if (p == h1 || h1 != h2) { errln("Fail: Hour same in different zones"); + } Calendar cal2 = new GregorianCalendar(GMT); Calendar cal3 = new GregorianCalendar(PST); - cal2.set(Calendar.MILLISECOND, 0); - cal3.set(Calendar.MILLISECOND, 0); + cal2.set(MILLISECOND, 0); + cal3.set(MILLISECOND, 0); - cal2.set(cal1.get(cal1.YEAR), - cal1.get(cal1.MONTH), - cal1.get(cal1.DAY_OF_MONTH), - cal1.get(cal1.HOUR_OF_DAY), - cal1.get(cal1.MINUTE), - cal1.get(cal1.SECOND)); + cal2.set(cal1.get(YEAR), + cal1.get(MONTH), + cal1.get(DAY_OF_MONTH), + cal1.get(HOUR_OF_DAY), + cal1.get(MINUTE), + cal1.get(SECOND)); - long t1,t2,t3,t4; - logln("RGMT 1 is: " + (t1=cal2.getTime().getTime())); + long t1, t2, t3, t4; + logln("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); cal3.set(year, month, day, hr, min, sec); - logln("RPST 1 is: " + (t2=cal3.getTime().getTime())); + logln("RPST 1 is: " + (t2 = cal3.getTime().getTime())); cal3.setTimeZone(GMT); - logln("RGMT 2 is: " + (t3=cal3.getTime().getTime())); - cal3.set(cal1.get(cal1.YEAR), - cal1.get(cal1.MONTH), - cal1.get(cal1.DAY_OF_MONTH), - cal1.get(cal1.HOUR_OF_DAY), - cal1.get(cal1.MINUTE), - cal1.get(cal1.SECOND)); + logln("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); + cal3.set(cal1.get(YEAR), + cal1.get(MONTH), + cal1.get(DAY_OF_MONTH), + cal1.get(HOUR_OF_DAY), + cal1.get(MINUTE), + cal1.get(SECOND)); // Issue 2: Calendar continues to use the timezone in its // constructor for set() conversions, regardless // of calls to setTimeZone() - logln("RGMT 3 is: " + (t4=cal3.getTime().getTime())); - if (t1 == t2 || - t1 != t4 || - t2 != t3) + logln("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); + if (t1 == t2 + || t1 != t4 + || t2 != t3) { errln("Fail: Calendar zone behavior faulty"); + } } public void Test4096539() { - int[] y = {31,28,31,30,31,30,31,31,30,31,30,31}; + int[] y = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - for (int x=0;x<12;x++) { - GregorianCalendar gc = new - GregorianCalendar(1997,x,y[x]); - int m1,m2; - log((m1=gc.get(Calendar.MONTH)+1)+"/"+ - gc.get(Calendar.DATE)+"/"+gc.get(Calendar.YEAR)+ - " + 1mo = "); + for (int x = 0; x < 12; x++) { + GregorianCalendar gc = new GregorianCalendar(1997, x, y[x]); + int m1, m2; + log((m1 = gc.get(MONTH) + 1) + "/" + + gc.get(DATE) + "/" + gc.get(YEAR) + + " + 1mo = "); - gc.add(Calendar.MONTH, 1); - logln((m2=gc.get(Calendar.MONTH)+1)+"/"+ - gc.get(Calendar.DATE)+"/"+gc.get(Calendar.YEAR) - ); + gc.add(MONTH, 1); + logln((m2 = gc.get(MONTH) + 1) + "/" + + gc.get(DATE) + "/" + gc.get(YEAR) + ); int m = (m1 % 12) + 1; - if (m2 != m) + if (m2 != m) { errln("Fail: Want " + m + " Got " + m2); + } } } @@ -538,13 +564,14 @@ public class CalendarRegression extends IntlTest { return; } - GregorianCalendar cal = (GregorianCalendar)Calendar.getInstance(); - cal.set(Calendar.YEAR, 1997); - cal.set(Calendar.DAY_OF_YEAR, 1); + GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); + cal.set(YEAR, 1997); + cal.set(DAY_OF_YEAR, 1); Date d = cal.getTime(); // Should be Jan 1 logln(d.toString()); - if (cal.get(Calendar.DAY_OF_YEAR) != 1) + if (cal.get(DAY_OF_YEAR) != 1) { errln("Fail: DAY_OF_YEAR not set"); + } } public void Test4103271() { @@ -555,28 +582,28 @@ public class CalendarRegression extends IntlTest { } SimpleDateFormat sdf = new SimpleDateFormat(); - int numYears=40, startYear=1997, numDays=15; + int numYears = 40, startYear = 1997, numDays = 15; String output, testDesc; - GregorianCalendar testCal = (GregorianCalendar)Calendar.getInstance(); + GregorianCalendar testCal = (GregorianCalendar) Calendar.getInstance(); testCal.clear(); sdf.setCalendar(testCal); sdf.applyPattern("d MMM yyyy"); boolean fail = false; - for (int firstDay=1; firstDay<=2; firstDay++) { - for (int minDays=1; minDays<=7; minDays++) { + for (int firstDay = 1; firstDay <= 2; firstDay++) { + for (int minDays = 1; minDays <= 7; minDays++) { testCal.setMinimalDaysInFirstWeek(minDays); testCal.setFirstDayOfWeek(firstDay); testDesc = ("Test" + String.valueOf(firstDay) + String.valueOf(minDays)); - logln(testDesc + " => 1st day of week=" + - String.valueOf(firstDay) + - ", minimum days in first week=" + - String.valueOf(minDays)); - for (int j=startYear; j<=startYear+numYears; j++) { - testCal.set(j,11,25); - for(int i=0; i 1st day of week=" + + String.valueOf(firstDay) + + ", minimum days in first week=" + + String.valueOf(minDays)); + for (int j = startYear; j <= startYear + numYears; j++) { + testCal.set(j, 11, 25); + for (int i = 0; i < numDays; i++) { + testCal.add(DATE, 1); String calWOY; - int actWOY = testCal.get(Calendar.WEEK_OF_YEAR); + int actWOY = testCal.get(WEEK_OF_YEAR); if (actWOY < 1 || actWOY > 53) { Date d = testCal.getTime(); calWOY = String.valueOf(actWOY); @@ -592,20 +619,19 @@ public class CalendarRegression extends IntlTest { int[] DATA = { 3, 52, 52, 52, 52, 52, 52, 52, - 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 4, 52, 52, 52, 52, 52, 52, 52, - 53, 53, 53, 53, 53, 53, 53, - 1, 1, 1, 1, 1, 1, 1, - }; - testCal.setFirstDayOfWeek(Calendar.SUNDAY); - for (int j=0; j " + testCal.getTime()); + if (ADDROLL[i] == ADD) { + testCal.add(WEEK_OF_YEAR, amount); + } else { + testCal.roll(WEEK_OF_YEAR, amount); + } + log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + + amount + ")\t " + before + + "\n\t\t => " + testCal.getTime()); if (!after.equals(testCal.getTime())) { logln("\tFAIL\n\t\texp: " + after); fail = true; - } else + } else { logln(" OK"); + } testCal.setTime(after); - if (ADDROLL[i] == ADD) - testCal.add(Calendar.WEEK_OF_YEAR, -amount); - else - testCal.roll(Calendar.WEEK_OF_YEAR, -amount); - log((ADDROLL[i]==ADD ? "add(WOY," : "roll(WOY,") + - (-amount) + ") " + after + - "\n\t\t => " + testCal.getTime()); + if (ADDROLL[i] == ADD) { + testCal.add(WEEK_OF_YEAR, -amount); + } else { + testCal.roll(WEEK_OF_YEAR, -amount); + } + log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + + (-amount) + ") " + after + + "\n\t\t => " + testCal.getTime()); if (!before.equals(testCal.getTime())) { logln("\tFAIL\n\t\texp: " + before); fail = true; + } else { + logln("\tOK"); } - else logln("\tOK"); } if (fail) { @@ -719,63 +749,68 @@ public class CalendarRegression extends IntlTest { public void Test4106136() { Locale saveLocale = Locale.getDefault(); try { - Locale[] locales = { Locale.CHINESE, Locale.CHINA }; - for (int i=0; i maxYear) { - errln("Failed for "+DATES[i].getTime()+" ms: year=" + - year + ", maxYear=" + maxYear); + errln("Failed for " + DATES[i].getTime() + " ms: year=" + + year + ", maxYear=" + maxYear); } } } @@ -1068,28 +1104,29 @@ public class CalendarRegression extends IntlTest { "SECOND", "MILLISECOND", "ZONE_OFFSET", - "DST_OFFSET" - }; + "DST_OFFSET"}; GregorianCalendar calendar = new GregorianCalendar(); calendar.setLenient(false); - Date date = new Date(1996-1900, Calendar.JANUARY, 3); // Arbitrary date - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + @SuppressWarnings("deprecation") + Date date = new Date(1996 - 1900, JANUARY, 3); // Arbitrary date + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); // Note: In the bug report, getActualMaximum() was called instead // of getMaximum() -- this was an error. The validation code doesn't // use getActualMaximum(), since that's too costly. int max = calendar.getMaximum(field); - int value = max+1; + int value = max + 1; calendar.set(field, value); try { calendar.getTime(); // Force time computation // We expect an exception to be thrown. If we fall through // to the next line, then we have a bug. - errln("Test failed with field " + fieldName[field] + - ", date before: " + date + - ", date after: " + calendar.getTime() + - ", value: " + value + " (max = " + max +")"); - } catch (IllegalArgumentException e) {} + errln("Test failed with field " + fieldName[field] + + ", date before: " + date + + ", date after: " + calendar.getTime() + + ", value: " + value + " (max = " + max + ")"); + } catch (IllegalArgumentException e) { + } } } @@ -1099,19 +1136,19 @@ public class CalendarRegression extends IntlTest { * CANNOT REPRODUCE THIS BUG */ public void Test4149677() { - TimeZone[] zones = { TimeZone.getTimeZone("GMT"), - TimeZone.getTimeZone("PST"), - TimeZone.getTimeZone("EAT") }; - for (int i=0; i0) logln("---"); + for (int i = 0; i < 5; ++i) { + if (i > 0) { + logln("---"); + } cal.clear(); - cal.set(1998, Calendar.APRIL, 5, i, 0); + cal.set(1998, APRIL, 5, i, 0); d = cal.getTime(); String s0 = d.toString(); logln("0 " + i + ": " + s0); cal.clear(); - cal.set(1998, Calendar.APRIL, 4, i+24, 0); + cal.set(1998, APRIL, 4, i + 24, 0); d = cal.getTime(); String sPlus = d.toString(); logln("+ " + i + ": " + sPlus); cal.clear(); - cal.set(1998, Calendar.APRIL, 6, i-24, 0); + cal.set(1998, APRIL, 6, i - 24, 0); d = cal.getTime(); String sMinus = d.toString(); logln("- " + i + ": " + sMinus); @@ -1164,8 +1203,7 @@ public class CalendarRegression extends IntlTest { errln("Fail: All three lines must match"); } } - } - finally { + } finally { TimeZone.setDefault(savedTz); } } @@ -1174,14 +1212,14 @@ public class CalendarRegression extends IntlTest { * Adding 12 months behaves differently from adding 1 year */ public void Test4165343() { - GregorianCalendar calendar = new GregorianCalendar(1996, Calendar.FEBRUARY, 29); + GregorianCalendar calendar = new GregorianCalendar(1996, FEBRUARY, 29); Date start = calendar.getTime(); logln("init date: " + start); - calendar.add(Calendar.MONTH, 12); + calendar.add(MONTH, 12); Date date1 = calendar.getTime(); logln("after adding 12 months: " + date1); calendar.setTime(start); - calendar.add(Calendar.YEAR, 1); + calendar.add(YEAR, 1); Date date2 = calendar.getTime(); logln("after adding one year : " + date2); if (date1.equals(date2)) { @@ -1196,34 +1234,34 @@ public class CalendarRegression extends IntlTest { */ public void Test4166109() { /* Test month: - * - * March 1998 - * Su Mo Tu We Th Fr Sa - * 1 2 3 4 5 6 7 - * 8 9 10 11 12 13 14 - * 15 16 17 18 19 20 21 - * 22 23 24 25 26 27 28 - * 29 30 31 + * + * March 1998 + * Su Mo Tu We Th Fr Sa + * 1 2 3 4 5 6 7 + * 8 9 10 11 12 13 14 + * 15 16 17 18 19 20 21 + * 22 23 24 25 26 27 28 + * 29 30 31 */ boolean passed = true; - int field = Calendar.WEEK_OF_MONTH; + int field = WEEK_OF_MONTH; GregorianCalendar calendar = new GregorianCalendar(Locale.US); - calendar.set(1998, Calendar.MARCH, 1); + calendar.set(1998, MARCH, 1); calendar.setMinimalDaysInFirstWeek(1); logln("Date: " + calendar.getTime()); - int firstInMonth = calendar.get(Calendar.DAY_OF_MONTH); + int firstInMonth = calendar.get(DAY_OF_MONTH); - for (int firstInWeek = Calendar.SUNDAY; firstInWeek <= Calendar.SATURDAY; firstInWeek++) { + for (int firstInWeek = SUNDAY; firstInWeek <= SATURDAY; firstInWeek++) { calendar.setFirstDayOfWeek(firstInWeek); int returned = calendar.getActualMaximum(field); - int expected = (31 + ((firstInMonth - firstInWeek + 7)% 7) + 6) / 7; + int expected = (31 + ((firstInMonth - firstInWeek + 7) % 7) + 6) / 7; - logln("First day of week = " + firstInWeek + - " getActualMaximum(WEEK_OF_MONTH) = " + returned + - " expected = " + expected + - ((returned == expected) ? " ok" : " FAIL")); + logln("First day of week = " + firstInWeek + + " getActualMaximum(WEEK_OF_MONTH) = " + returned + + " expected = " + expected + + ((returned == expected) ? " ok" : " FAIL")); if (returned != expected) { passed = false; @@ -1242,19 +1280,19 @@ public class CalendarRegression extends IntlTest { * changed. See 4928615. */ public void Test4167060() { - int field = Calendar.YEAR; + int field = YEAR; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy G", - Locale.US); + Locale.US); int[][] dates = { // year, month, day of month - { 100, Calendar.NOVEMBER, 1 }, - { -99 /*100BC*/, Calendar.JANUARY, 1 }, - { 1996, Calendar.FEBRUARY, 29 }}; + {100, NOVEMBER, 1}, + {-99 /*100BC*/, JANUARY, 1}, + {1996, FEBRUARY, 29}}; - String[] id = { "Hybrid", "Gregorian", "Julian" }; + String[] id = {"Hybrid", "Gregorian", "Julian"}; - for (int k=0; k<3; ++k) { + for (int k = 0; k < 3; ++k) { logln("--- " + id[k] + " ---"); for (int j = 0; j < dates.length; ++j) { @@ -1265,7 +1303,7 @@ public class CalendarRegression extends IntlTest { calendar.setGregorianChange(new Date(Long.MAX_VALUE)); } calendar.set(dates[j][0], dates[j][1], dates[j][2]); - format.setCalendar((Calendar)calendar.clone()); + format.setCalendar((Calendar) calendar.clone()); Date dateBefore = calendar.getTime(); @@ -1273,7 +1311,7 @@ public class CalendarRegression extends IntlTest { logln("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); logln("date before: " + format.format(dateBefore)); - int years[] = {2000, maxYear-1, maxYear, maxYear+1}; + int[] years = {2000, maxYear - 1, maxYear, maxYear + 1}; for (int i = 0; i < years.length; i++) { boolean valid = years[i] <= maxYear; @@ -1282,8 +1320,8 @@ public class CalendarRegression extends IntlTest { int newYear = calendar.get(field); calendar.setTime(dateBefore); // restore calendar for next use - logln(" Year " + years[i] + (valid? " ok " : " bad") + - " => " + format.format(dateAfter)); + logln(" Year " + years[i] + (valid ? " ok " : " bad") + + " => " + format.format(dateAfter)); if (valid && newYear != years[i]) { errln(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); } else if (!valid && newYear == years[i]) { @@ -1305,18 +1343,16 @@ public class CalendarRegression extends IntlTest { return; } - int fieldsList[][] = { - { 1997, Calendar.FEBRUARY, 1, 10, 45, 15, 900 }, - { 1999, Calendar.DECEMBER, 22, 23, 59, 59, 999 }, + int[][] fieldsList = { + {1997, FEBRUARY, 1, 10, 45, 15, 900}, + {1999, DECEMBER, 22, 23, 59, 59, 999}, // test case for 4960642 with default cutover - { 1582, Calendar.OCTOBER, 4, 23, 59, 59, 999 }, - }; + {1582, OCTOBER, 4, 23, 59, 59, 999}}; String[] fieldNames = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", - "ZONE_OFFSET", "DST_OFFSET" - }; + "ZONE_OFFSET", "DST_OFFSET"}; Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1326,25 +1362,25 @@ public class CalendarRegression extends IntlTest { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(0)); - cal.roll(Calendar.HOUR, 0x7F000000); - cal.roll(Calendar.HOUR, -0x7F000000); + cal.roll(HOUR, 0x7F000000); + cal.roll(HOUR, -0x7F000000); if (cal.getTime().getTime() != 0) { - errln("Hour rolling broken. expected 0, got "+cal.getTime().getTime()); + errln("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); } - for (int op=0; op<2; ++op) { - logln("Testing GregorianCalendar " + (op==0 ? "add" : "roll")); + for (int op = 0; op < 2; ++op) { + logln("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); - for (int field=0; field < Calendar.FIELD_COUNT; ++field) { - if (field != Calendar.ZONE_OFFSET && - field != Calendar.DST_OFFSET) { - for (int j=0; j " + - cal.get(Calendar.YEAR) + - "/" + (cal.get(Calendar.MONTH) + 1) + - "/" + cal.get(Calendar.DATE) + - " " + cal.get(Calendar.HOUR_OF_DAY) + - ":" + cal.get(Calendar.MINUTE) + - ":" + cal.get(Calendar.SECOND) + - "." + cal.get(Calendar.MILLISECOND) + - " d=" + delta); + errln((op == 0 ? "add(" : "roll(") + + fieldNames[field] + ", " + + (i < limit ? "+" : "-") + "1) => " + + cal.get(YEAR) + + "/" + (cal.get(MONTH) + 1) + + "/" + cal.get(DATE) + + " " + cal.get(HOUR_OF_DAY) + + ":" + cal.get(MINUTE) + + ":" + cal.get(SECOND) + + "." + cal.get(MILLISECOND) + + " d=" + delta); } } } } } } - } - finally { + } finally { Locale.setDefault(savedLocale); } } @@ -1425,14 +1460,14 @@ public class CalendarRegression extends IntlTest { public void Test4174361() { GregorianCalendar calendar = new GregorianCalendar(1996, 1, 29); - calendar.add(Calendar.MONTH, 10); + calendar.add(MONTH, 10); Date date1 = calendar.getTime(); - int d1 = calendar.get(Calendar.DAY_OF_MONTH); + int d1 = calendar.get(DAY_OF_MONTH); calendar = new GregorianCalendar(1996, 1, 29); - calendar.add(Calendar.MONTH, 11); + calendar.add(MONTH, 11); Date date2 = calendar.getTime(); - int d2 = calendar.get(Calendar.DAY_OF_MONTH); + int d2 = calendar.get(DAY_OF_MONTH); if (d1 != d2) { errln("adding months to Feb 29 broken"); @@ -1449,9 +1484,9 @@ public class CalendarRegression extends IntlTest { Calendar cal = Calendar.getInstance(PST, Locale.US); cal.clear(); cal.set(1999, 3, 21, 15, 5, 0); // Arbitrary - int h1 = cal.get(Calendar.HOUR_OF_DAY); + int h1 = cal.get(HOUR_OF_DAY); cal.setTimeZone(EST); - int h2 = cal.get(Calendar.HOUR_OF_DAY); + int h2 = cal.get(HOUR_OF_DAY); if (h1 == h2) { errln("FAIL: Fields not updated after setTimeZone"); } @@ -1460,7 +1495,7 @@ public class CalendarRegression extends IntlTest { // getTime() returns zone-independent time in ms. cal.clear(); cal.setTimeZone(PST); - cal.set(Calendar.HOUR_OF_DAY, 10); + cal.set(HOUR_OF_DAY, 10); Date pst10 = cal.getTime(); cal.setTimeZone(EST); Date est10 = cal.getTime(); @@ -1474,28 +1509,27 @@ public class CalendarRegression extends IntlTest { */ public void Test4197699() { GregorianCalendar cal = new GregorianCalendar(); - cal.setFirstDayOfWeek(Calendar.MONDAY); + cal.setFirstDayOfWeek(MONDAY); cal.setMinimalDaysInFirstWeek(4); DateFormat fmt = new SimpleDateFormat("E dd MMM yyyy 'DOY='D 'WOY='w"); fmt.setCalendar(cal); int[] DATA = { - 2000, Calendar.JANUARY, 1, 52, - 2001, Calendar.DECEMBER, 31, 1, - }; + 2000, JANUARY, 1, 52, + 2001, DECEMBER, 31, 1}; - for (int i=0; i " + actual + - ", want " + DATA[i+1]); + if (!actual.equals(DATA[i + 1])) { + errln("FAIL: Sunday " + DATA[i] + + " of Jan 1997 -> " + actual + + ", want " + DATA[i + 1]); } } } - public void Test4288792() throws Exception - { + public void Test4288792() throws Exception { TimeZone savedTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); GregorianCalendar cal = new GregorianCalendar(); @@ -1631,45 +1664,44 @@ public class CalendarRegression extends IntlTest { for (int i = 1900; i < 2100; i++) { for (int j1 = 1; j1 <= 7; j1++) { // Loop for MinimalDaysInFirstWeek: 1..7 - for (int j = Calendar.SUNDAY; j <= Calendar.SATURDAY; j++) { + for (int j = SUNDAY; j <= SATURDAY; j++) { // Loop for FirstDayOfWeek: SUNDAY..SATURDAY cal.clear(); cal.setMinimalDaysInFirstWeek(j1); cal.setFirstDayOfWeek(j); - cal.set(Calendar.YEAR, i); - int maxWeek = cal.getActualMaximum(Calendar.WEEK_OF_YEAR); - cal.set(Calendar.WEEK_OF_YEAR, maxWeek); - cal.set(Calendar.DAY_OF_WEEK, j); + cal.set(YEAR, i); + int maxWeek = cal.getActualMaximum(WEEK_OF_YEAR); + cal.set(WEEK_OF_YEAR, maxWeek); + cal.set(DAY_OF_WEEK, j); for (int k = 1; k < 7; k++) { - cal.add(Calendar.DATE, 1); - int WOY = cal.get(Calendar.WEEK_OF_YEAR); + cal.add(DATE, 1); + int WOY = cal.get(WEEK_OF_YEAR); if (WOY != maxWeek) { errln(cal.getTime() + ",got=" + WOY - + ",expected=" + maxWeek - + ",min=" + j1 + ",first=" + j); + + ",expected=" + maxWeek + + ",min=" + j1 + ",first=" + j); } } - cal.add(Calendar.DATE, 1); - int WOY = cal.get(Calendar.WEEK_OF_YEAR); + cal.add(DATE, 1); + int WOY = cal.get(WEEK_OF_YEAR); if (WOY != 1) { errln(cal.getTime() + ",got=" + WOY - + ",expected=1,min=" + j1 + ",first" + j); + + ",expected=1,min=" + j1 + ",first" + j); } } } } - } - finally { + } finally { TimeZone.setDefault(savedTZ); } } public void Test4328747() throws Exception { - Calendar c = (Calendar)Calendar.getInstance(Locale.US); + Calendar c = Calendar.getInstance(Locale.US); c.clear(); - c.set(1966,0,1); // 1 jan 1966 + c.set(1966, 0, 1); // 1 jan 1966 // serialize ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1679,16 +1711,16 @@ public class CalendarRegression extends IntlTest { // deserialize ObjectInputStream t = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); - Calendar result = (Calendar)t.readObject(); + Calendar result = (Calendar) t.readObject(); // let recalculate fields with the same UTC time result.setTime(result.getTime()); // Bug gives 1965 11 19 - if ((result.get(c.YEAR) != 1966) || (result.get(c.MONTH) != 0) - || (result.get(c.DATE) != 1)) { + if ((result.get(YEAR) != 1966) || (result.get(MONTH) != 0) + || (result.get(DATE) != 1)) { errln("deserialized Calendar returned wrong date field(s): " - + result.get(c.YEAR) + "/" + result.get(c.MONTH) + "/" + result.get(c.DATE) - + ", expected 1966/0/1"); + + result.get(YEAR) + "/" + result.get(MONTH) + "/" + result.get(DATE) + + ", expected 1966/0/1"); } } @@ -1700,13 +1732,13 @@ public class CalendarRegression extends IntlTest { TimeZone savedTimeZone = TimeZone.getDefault(); try { boolean pass = true; - String[] IDs = new String[] {"Undefined", "PST", "US/Pacific", - "GMT+3:00", "GMT-01:30"}; + String[] IDs = new String[]{"Undefined", "PST", "US/Pacific", + "GMT+3:00", "GMT-01:30"}; for (int i = 0; i < IDs.length; i++) { TimeZone tz = TimeZone.getTimeZone(IDs[i]); TimeZone.setDefault(tz); - Calendar c = (Calendar)Calendar.getInstance(); + Calendar c = Calendar.getInstance(); // serialize ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1719,26 +1751,20 @@ public class CalendarRegression extends IntlTest { if (!c.equals(t.readObject())) { pass = false; - logln("Calendar instance which uses TimeZone <" + - IDs[i] + "> is incorrectly serialized/deserialized."); + logln("Calendar instance which uses TimeZone <" + + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("Calendar instance which uses TimeZone <" + - IDs[i] + "> is correctly serialized/deserialized."); + logln("Calendar instance which uses TimeZone <" + + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { errln("Fail: Calendar serialization/equality bug"); } - } - catch (IOException e) { + } catch (IOException | ClassNotFoundException e) { errln("Fail: " + e); e.printStackTrace(); - } - catch (ClassNotFoundException e) { - errln("Fail: " + e); - e.printStackTrace(); - } - finally { + } finally { TimeZone.setDefault(savedTimeZone); } } @@ -1747,12 +1773,12 @@ public class CalendarRegression extends IntlTest { * 4546637: Incorrect WEEK_OF_MONTH after changing First Day Of Week */ public void Test4546637() { - GregorianCalendar day = new GregorianCalendar (2001, Calendar.NOVEMBER, 04); + GregorianCalendar day = new GregorianCalendar(2001, NOVEMBER, 04); day.setMinimalDaysInFirstWeek(1); - int wom = day.get(Calendar.WEEK_OF_MONTH); + int wom = day.get(WEEK_OF_MONTH); - day.setFirstDayOfWeek(Calendar.MONDAY); - if (day.get(Calendar.WEEK_OF_MONTH) != 1) { + day.setFirstDayOfWeek(MONDAY); + if (day.get(WEEK_OF_MONTH) != 1) { errln("Fail: 2001/11/4 must be the first week of the month."); } } @@ -1761,14 +1787,14 @@ public class CalendarRegression extends IntlTest { * 4623997: GregorianCalendar returns bad WEEK_OF_YEAR */ public void Test4623997() { - GregorianCalendar cal = new GregorianCalendar(2000, GregorianCalendar.JANUARY, 1); + GregorianCalendar cal = new GregorianCalendar(2000, JANUARY, 1); - int dow = cal.get(GregorianCalendar.DAY_OF_WEEK); + int dow = cal.get(DAY_OF_WEEK); - cal.setFirstDayOfWeek(GregorianCalendar.MONDAY); + cal.setFirstDayOfWeek(MONDAY); cal.setMinimalDaysInFirstWeek(4); - if (cal.get(GregorianCalendar.WEEK_OF_YEAR) != 52) { + if (cal.get(WEEK_OF_YEAR) != 52) { errln("Fail: 2000/1/1 must be the 52nd week of the year."); } } @@ -1800,9 +1826,9 @@ public class CalendarRegression extends IntlTest { } t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 33); + calendar.set(DAY_OF_MONTH, 33); t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 0); + calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); @@ -1815,10 +1841,10 @@ public class CalendarRegression extends IntlTest { throw new RuntimeException("Unexpected parse exception", e); } t = calendar.getTime(); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); - calendar.set(Calendar.DAY_OF_MONTH, 33); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); + calendar.set(DAY_OF_MONTH, 33); t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 0); + calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("DAY_OF_MONTH: expected: " + expected + ", got: " + s); @@ -1834,11 +1860,11 @@ public class CalendarRegression extends IntlTest { throw new RuntimeException("Unexpected parse exception", e); } t = calendar.getTime(); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); // jump to the next year - calendar.set(Calendar.WEEK_OF_YEAR, 100); + calendar.set(WEEK_OF_YEAR, 100); t = calendar.getTime(); - calendar.set(Calendar.WEEK_OF_YEAR, 0); + calendar.set(WEEK_OF_YEAR, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); @@ -1846,11 +1872,11 @@ public class CalendarRegression extends IntlTest { // change the state back calendar.clear(); calendar.setTime(initialDate); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); // jump to next month - calendar.set(Calendar.WEEK_OF_MONTH, 7); + calendar.set(WEEK_OF_MONTH, 7); t = calendar.getTime(); - calendar.set(Calendar.WEEK_OF_MONTH, 0); + calendar.set(WEEK_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); @@ -1870,10 +1896,10 @@ public class CalendarRegression extends IntlTest { } t = calendar.getTime(); // time should be 22:59:59. - calendar.set(Calendar.MINUTE, 61); + calendar.set(MINUTE, 61); // time should be 23:01:59. t = calendar.getTime(); - calendar.set(Calendar.MINUTE, -1); + calendar.set(MINUTE, -1); // time should be back to 22:59:59. s = df.format(calendar.getTime()); if (!expected.equals(s)) { @@ -1896,15 +1922,15 @@ public class CalendarRegression extends IntlTest { Calendar cal = Calendar.getInstance(); cal.setTime(new Date(1029814211523L)); - cal.set(Calendar.YEAR, 2001); + cal.set(YEAR, 2001); Date t = cal.getTime(); - cal.set(Calendar.MONTH, Calendar.JANUARY); + cal.set(MONTH, JANUARY); t = cal.getTime(); - cal.set(Calendar.DAY_OF_MONTH, 8); + cal.set(DAY_OF_MONTH, 8); t = cal.getTime(); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + cal.set(DAY_OF_WEEK, MONDAY); DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US); String expected = "2001/01/08"; String s = df.format(cal.getTime()); @@ -1923,9 +1949,9 @@ public class CalendarRegression extends IntlTest { */ public void Test4683492() { Calendar cal = new GregorianCalendar(2002, 3, 29, 10, 0, 0); - cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1); - cal.set(Calendar.MONTH, 12); + cal.set(DAY_OF_WEEK, FRIDAY); + cal.set(DAY_OF_WEEK_IN_MONTH, -1); + cal.set(MONTH, 12); DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US); String expected = "2003/01/31"; String s = df.format(cal.getTime()); @@ -1940,31 +1966,31 @@ public class CalendarRegression extends IntlTest { public void Test4080631() { Calendar cal = Calendar.getInstance(); int h1 = cal.hashCode(); - cal.add(cal.SECOND, +1); + cal.add(SECOND, +1); int h2 = cal.hashCode(); Calendar cal2 = (Calendar) cal.clone(); - cal.add(cal.MILLISECOND, +1); + cal.add(MILLISECOND, +1); int h3 = cal.hashCode(); - logln("hash code: h1="+h1+", h2="+h2+", h3="+h3); + logln("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); if (h1 == h2 || h1 == h3 || h2 == h3) { - errln("hash code is poor: hashCode="+h1); + errln("hash code is poor: hashCode=" + h1); } h2 = cal2.hashCode(); - cal.add(cal.MILLISECOND, -1); + cal.add(MILLISECOND, -1); int h4 = cal.hashCode(); - logln("hash code: h2="+h2+", h4="+h4); + logln("hash code: h2=" + h2 + ", h4=" + h4); if (cal.equals(cal2) && h2 != h4) { - errln("broken hash code: h2="+h2+", h4="+h4); + errln("broken hash code: h2=" + h2 + ", h4=" + h4); } int x = cal.getFirstDayOfWeek() + 3; - if (x > cal.SATURDAY) { + if (x > SATURDAY) { x -= 7; } cal.setFirstDayOfWeek(x); int h5 = cal.hashCode(); - logln("hash code: h4="+h4+", h5="+h5); + logln("hash code: h4=" + h4 + ", h5=" + h5); if (h4 == h5) { - errln("has code is poor with first day of week param: hashCode="+h4); + errln("has code is poor with first day of week param: hashCode=" + h4); } } @@ -1991,8 +2017,7 @@ public class CalendarRegression extends IntlTest { errln("Wrong BCE and/or CE values"); } } - */ - + */ /** * 4167995: GregorianCalendar.setGregorianChange() not to spec */ @@ -2000,42 +2025,42 @@ public class CalendarRegression extends IntlTest { Koyomi gc = new Koyomi(TimeZone.getTimeZone("GMT")); logln("Hybrid: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292269055, gc.DECEMBER, 2, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Hybrid: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292278994, gc.AUGUST, 17, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MIN_VALUE)); logln("Gregorian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292275056, gc.MAY, 16, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292275056, MAY, 16, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Gregorian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292278994, gc.AUGUST, 17, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MAX_VALUE)); logln("Julian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292269055, gc.DECEMBER, 2, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Julian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292272993, gc.JANUARY, 4, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292272993, JANUARY, 4, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } } @@ -2046,13 +2071,13 @@ public class CalendarRegression extends IntlTest { public void Test4340146() { Koyomi cal = new Koyomi(); cal.clear(); - cal.set(2003, cal.OCTOBER, 32); + cal.set(2003, OCTOBER, 32); cal.equals(new Koyomi()); - if (!cal.checkInternalDate(2003, cal.OCTOBER, 32)) { + if (!cal.checkInternalDate(2003, OCTOBER, 32)) { errln(cal.getMessage()); } new Koyomi().equals(cal); - if (!cal.checkInternalDate(2003, cal.OCTOBER, 32)) { + if (!cal.checkInternalDate(2003, OCTOBER, 32)) { errln(cal.getMessage()); } } @@ -2065,10 +2090,10 @@ public class CalendarRegression extends IntlTest { // throw IllegalArgumentException. Koyomi cal = new Koyomi(TimeZone.getTimeZone("Pacific/Kiritimati")); cal.setLenient(false); - cal.set(2003, cal.OCTOBER, 10); + cal.set(2003, OCTOBER, 10); cal.getTime(); cal.setTimeZone(TimeZone.getTimeZone("Pacific/Tongatapu")); - cal.set(2003, cal.OCTOBER, 10); + cal.set(2003, OCTOBER, 10); cal.getTime(); } @@ -2077,10 +2102,10 @@ public class CalendarRegression extends IntlTest { */ public void Test4652815() { Koyomi cal = new Koyomi(Locale.US); - testRoll(cal, 2003, cal.SEPTEMBER, 29); - testRoll(cal, 2003, cal.DECEMBER, 24); - testRoll(cal, 1582, cal.DECEMBER, 19); - testRoll(cal, 1582, cal.DECEMBER, 20); + testRoll(cal, 2003, SEPTEMBER, 29); + testRoll(cal, 2003, DECEMBER, 24); + testRoll(cal, 1582, DECEMBER, 19); + testRoll(cal, 1582, DECEMBER, 20); } private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { @@ -2089,15 +2114,15 @@ public class CalendarRegression extends IntlTest { cal.getTime(); // normalize fields logln("Roll backwards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { - cal.roll(cal.WEEK_OF_YEAR, -i); - if (!cal.checkFieldValue(cal.YEAR, year)) { + cal.roll(WEEK_OF_YEAR, -i); + if (!cal.checkFieldValue(YEAR, year)) { errln(cal.getMessage()); } } logln("Roll forewards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { - cal.roll(cal.WEEK_OF_YEAR, +i); - if (!cal.checkFieldValue(cal.YEAR, year)) { + cal.roll(WEEK_OF_YEAR, +i); + if (!cal.checkFieldValue(YEAR, year)) { errln(cal.getMessage()); } } @@ -2110,20 +2135,20 @@ public class CalendarRegression extends IntlTest { Koyomi cal = new Koyomi(Locale.US); cal.clear(); logln("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); - cal.set(cal.ERA, cal.BC); - cal.set(9, cal.FEBRUARY, 28); - if (cal.getActualMaximum(cal.DAY_OF_YEAR) != 366) { + cal.set(ERA, GregorianCalendar.BC); + cal.set(9, FEBRUARY, 28); + if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { errln(" wrong actual max of DAY_OF_YEAR: got " - + cal.getActualMaximum(cal.DAY_OF_YEAR) + " expected " + 366); + + cal.getActualMaximum(DAY_OF_YEAR) + " expected " + 366); } - cal.roll(cal.DAY_OF_MONTH, +1); - if (!cal.checkFieldValue(cal.ERA, cal.BC) - || !cal.checkDate(9, cal.FEBRUARY, 29)) { + cal.roll(DAY_OF_MONTH, +1); + if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) + || !cal.checkDate(9, FEBRUARY, 29)) { errln(cal.getMessage()); } - cal.roll(cal.DAY_OF_MONTH, +1); - if (!cal.checkFieldValue(cal.ERA, cal.BC) - || !cal.checkDate(9, cal.FEBRUARY, 1)) { + cal.roll(DAY_OF_MONTH, +1); + if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) + || !cal.checkDate(9, FEBRUARY, 1)) { errln(cal.getMessage()); } } @@ -2135,11 +2160,11 @@ public class CalendarRegression extends IntlTest { logln("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); Koyomi cal = new Koyomi(Locale.US); cal.clear(); - cal.set(1999, cal.FEBRUARY + 12, 1); - if (!cal.checkActualMaximum(cal.DAY_OF_YEAR, 366)) { + cal.set(1999, FEBRUARY + 12, 1); + if (!cal.checkActualMaximum(DAY_OF_YEAR, 366)) { errln(cal.getMessage()); } - if (!cal.checkActualMaximum(cal.DAY_OF_MONTH, 29)) { + if (!cal.checkActualMaximum(DAY_OF_MONTH, 29)) { errln(cal.getMessage()); } } @@ -2150,36 +2175,36 @@ public class CalendarRegression extends IntlTest { public void Test4936355() { Koyomi cal = new Koyomi(TimeZone.getTimeZone("GMT")); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR_OF_DAY, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, HOUR_OF_DAY, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, HOUR, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.MINUTE, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, MINUTE, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 1000); cal.clear(); // Make sure to use Gregorian dates (before and after the // set() call) for testing - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR_OF_DAY, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, HOUR_OF_DAY, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, HOUR, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.MINUTE, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, MINUTE, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 1000); } private void checkTimeCalculation(Koyomi cal, int field, int value, long expectedDelta) { @@ -2189,7 +2214,7 @@ public class CalendarRegression extends IntlTest { if ((time + expectedDelta) != time2) { String s = value == Integer.MAX_VALUE ? "Integer.MAX_VALUE" : "Integer.MIN_VALUE"; errln("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 - + ", expected " + (time+expectedDelta)); + + ", expected " + (time + expectedDelta)); } } @@ -2204,8 +2229,8 @@ public class CalendarRegression extends IntlTest { cal2.clear(); cal2.setLenient(false); - cal1.set(2003, Calendar.OCTOBER, 31); - cal2.set(2003, Calendar.OCTOBER, 31); + cal1.set(2003, OCTOBER, 31); + cal2.set(2003, OCTOBER, 31); try { if (cal1.equals(cal2)) { errln("lenient and non-lenient shouldn't be equal. (2003/10/31)"); @@ -2217,8 +2242,8 @@ public class CalendarRegression extends IntlTest { errln("equals threw IllegalArugumentException with non-lenient"); } - cal1.set(2003, Calendar.OCTOBER, 32); - cal2.set(2003, Calendar.OCTOBER, 32); + cal1.set(2003, OCTOBER, 32); + cal2.set(2003, OCTOBER, 32); try { if (cal1.equals(cal2)) { errln("lenient and non-lenient shouldn't be equal. (2003/10/32)"); @@ -2246,17 +2271,17 @@ public class CalendarRegression extends IntlTest { * 4738710: API: Calendar comparison methods should be improved */ public void Test4738710() { - Calendar cal0 = new GregorianCalendar(2003, Calendar.SEPTEMBER, 30); - Comparable cal1 = new GregorianCalendar(2003, Calendar.OCTOBER, 1); - Calendar cal2 = new GregorianCalendar(2003, Calendar.OCTOBER, 2); + Calendar cal0 = new GregorianCalendar(2003, SEPTEMBER, 30); + Comparable cal1 = new GregorianCalendar(2003, OCTOBER, 1); + Calendar cal2 = new GregorianCalendar(2003, OCTOBER, 2); if (!(cal1.compareTo(cal0) > 0)) { errln("!(cal1 > cal0)"); } if (!(cal1.compareTo(cal2) < 0)) { errln("!(cal1 < cal2)"); } - if (cal1.compareTo(new GregorianCalendar(2003, Calendar.OCTOBER, 1)) != 0) { - errln("cal1 != new GregorianCalendar(2003, Calendar.OCTOBER, 1)"); + if (cal1.compareTo(new GregorianCalendar(2003, OCTOBER, 1)) != 0) { + errln("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); } if (cal0.after(cal2)) { @@ -2266,10 +2291,10 @@ public class CalendarRegression extends IntlTest { errln("cal2 shouldn't be before cal0"); } - if (cal0.after(new Integer(0))) { + if (cal0.after(0)) { errln("cal0.after() returned true with an Integer."); } - if (cal0.before(new Integer(0))) { + if (cal0.before(0)) { errln("cal0.before() returned true with an Integer."); } if (cal0.after(null)) { @@ -2283,34 +2308,35 @@ public class CalendarRegression extends IntlTest { /** * 4633646: Setting WEEK_OF_MONTH to 1 results in incorrect date */ + @SuppressWarnings("deprecation") public void Test4633646() { Koyomi cal = new Koyomi(Locale.US); - cal.setTime(new Date(2002-1900, 1-1, 28)); + cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); sub4633646(cal); cal.setLenient(false); - cal.setTime(new Date(2002-1900, 1-1, 28)); + cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); sub4633646(cal); cal = new Koyomi(Locale.US); cal.clear(); - cal.set(2002, cal.JANUARY, 28); + cal.set(2002, JANUARY, 28); sub4633646(cal); cal.clear(); cal.setLenient(false); - cal.set(2002, cal.JANUARY, 28); + cal.set(2002, JANUARY, 28); sub4633646(cal); } void sub4633646(Koyomi cal) { cal.getTime(); - cal.set(cal.WEEK_OF_MONTH, 1); + cal.set(WEEK_OF_MONTH, 1); if (cal.isLenient()) { - if (!cal.checkDate(2001, cal.DECEMBER, 31)) { + if (!cal.checkDate(2001, DECEMBER, 31)) { errln(cal.getMessage()); } - if (!cal.checkFieldValue(cal.WEEK_OF_MONTH, 6)) { + if (!cal.checkFieldValue(WEEK_OF_MONTH, 6)) { errln(cal.getMessage()); } } else { @@ -2329,29 +2355,29 @@ public class CalendarRegression extends IntlTest { public void Test4846659() { Koyomi cal = new Koyomi(); cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); // Test roll() - cal.roll(cal.AM_PM, +1); // should turn to PM - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 10+12)) { + cal.roll(AM_PM, +1); // should turn to PM + if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { errln("roll: AM_PM didn't change to PM"); } cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); // Test set() - cal.set(cal.AM_PM, cal.PM); // should turn to PM - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 10+12)) { + cal.set(AM_PM, PM); // should turn to PM + if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { errln("set: AM_PM didn't change to PM"); } cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); - cal.set(cal.AM_PM, cal.PM); - cal.set(cal.HOUR, 9); - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 9+12)) { + cal.set(AM_PM, PM); + cal.set(HOUR, 9); + if (!cal.checkFieldValue(HOUR_OF_DAY, 9 + 12)) { errln("set: both AM_PM and HOUT didn't change to PM"); } } @@ -2370,15 +2396,15 @@ public class CalendarRegression extends IntlTest { // 29 30 cal.clear(); // 6/1 to 6/7 should be the 1st week of June. - cal.set(2003, cal.JUNE, 2); + cal.set(2003, JUNE, 2); cal.getTime(); // Let cal calculate time. - cal.setFirstDayOfWeek(cal.MONDAY); + cal.setFirstDayOfWeek(MONDAY); // Now 6/2 to 6/8 should be the 2nd week of June. Sunday of // that week is 6/8. - logln("1: " +cal.get(cal.WEEK_OF_MONTH)+", "+cal.get(cal.DAY_OF_MONTH)); - cal.set(cal.DAY_OF_WEEK, cal.SUNDAY); + logln("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); + cal.set(DAY_OF_WEEK, SUNDAY); logln("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); - if (!cal.checkDate(2003, cal.JUNE, 8)) { + if (!cal.checkDate(2003, JUNE, 8)) { errln(cal.getMessage()); } } @@ -2387,7 +2413,7 @@ public class CalendarRegression extends IntlTest { * 4973919: Inconsistent GregorianCalendar hashCode before and after serialization */ public void Test4966499() throws Exception { - GregorianCalendar date1 = new GregorianCalendar(2004, Calendar.JANUARY, 7); + GregorianCalendar date1 = new GregorianCalendar(2004, JANUARY, 7); // Serialize date1 ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -2399,15 +2425,15 @@ public class CalendarRegression extends IntlTest { // Deserialize it ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); - GregorianCalendar date2 = (GregorianCalendar)ois.readObject(); + GregorianCalendar date2 = (GregorianCalendar) ois.readObject(); if (!date1.equals(date2)) { errln("date1.equals(date2) != true"); } if (date1.hashCode() != date2.hashCode()) { errln("inconsistent hashCode() value (before=0x" - +Integer.toHexString(date1.hashCode())+ - ", after=0x"+Integer.toHexString(date2.hashCode())+")"); + + Integer.toHexString(date1.hashCode()) + + ", after=0x" + Integer.toHexString(date2.hashCode()) + ")"); } } @@ -2468,29 +2494,26 @@ public class CalendarRegression extends IntlTest { TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); try { - Map data = new HashMap(); - data.put(getGregorianDate(999, Calendar.OCTOBER, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.JANUARY, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.FEBRUARY, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.FEBRUARY, 28), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.MARCH, 1), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.JANUARY, 1), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.JANUARY, 6), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.MARCH, 1), Boolean.TRUE); + Map data = new HashMap<>(); + data.put(getGregorianDate(999, OCTOBER, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, JANUARY, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, FEBRUARY, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, FEBRUARY, 28), Boolean.FALSE); + data.put(getGregorianDate(1000, MARCH, 1), Boolean.TRUE); + data.put(getGregorianDate(1001, JANUARY, 1), Boolean.TRUE); + data.put(getGregorianDate(1001, JANUARY, 6), Boolean.TRUE); + data.put(getGregorianDate(1001, MARCH, 1), Boolean.TRUE); - Iterator itr = data.keySet().iterator(); - while (itr.hasNext()) { - Date d = itr.next(); - boolean expected = data.get(d).booleanValue(); + data.keySet().forEach(d -> { + boolean expected = data.get(d); GregorianCalendar cal = new GregorianCalendar(); cal.setGregorianChange(d); if (cal.isLeapYear(1000) != expected) { - errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + - " with cutover date (Julian) " + d); + errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + + " with cutover date (Julian) " + d); } - } - } - finally { + }); + } finally { TimeZone.setDefault(savedZone); } } @@ -2511,15 +2534,15 @@ public class CalendarRegression extends IntlTest { */ public void Test5006864() { GregorianCalendar cal = new GregorianCalendar(); - int min = cal.getMinimum(cal.DAY_OF_WEEK_IN_MONTH); + int min = cal.getMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { errln("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " - + min + ", expected 1."); + + min + ", expected 1."); } - min = cal.getGreatestMinimum(cal.DAY_OF_WEEK_IN_MONTH); + min = cal.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { errln("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " - + min + ", expected 1."); + + min + ", expected 1."); } } } diff --git a/jdk/test/java/util/Calendar/CalendarTest.java b/jdk/test/java/util/Calendar/CalendarTest.java index b04bb03a1fc..d9ce67196af 100644 --- a/jdk/test/java/util/Calendar/CalendarTest.java +++ b/jdk/test/java/util/Calendar/CalendarTest.java @@ -30,12 +30,25 @@ * @key randomness */ -import java.util.*; -import java.text.*; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import static java.util.Calendar.*; public class CalendarTest extends IntlTest { - static final int ONE_DAY = 24*60*60*1000; + + static final int ONE_DAY = 24 * 60 * 60 * 1000; static final int EPOCH_JULIAN = 2440588; public static void main(String argv[]) throws Exception { @@ -64,32 +77,31 @@ public class CalendarTest extends IntlTest { Changeover +6 days: 1582/10/21 dow=5 Changeover +7 days: 1582/10/22 dow=6 */ - int MON[] = { 9, 9, 9,10,10,10,10, 10, 10, 10, 10, 10, 10, 10, 10 }; - int DOM[] = { 28, 29, 30, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20, 21, 22 }; - int DOW[] = { 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6 }; + int[] MON = { 9, 9, 9,10,10,10,10, 10, 10, 10, 10, 10, 10, 10, 10 }; + int[] DOM = { 28, 29, 30, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20, 21, 22 }; + int[] DOW = { 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6 }; // ^ <-Changeover Fri Oct 15 1582 - try { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Date co = new Date(1582-1900, Calendar.OCTOBER, 15); + @SuppressWarnings("deprecation") + Date co = new Date(1582 - 1900, OCTOBER, 15); GregorianCalendar cal = new GregorianCalendar(); int j = 0; for (int i = -7; i <= 7; ++i, ++j) { - Date d = new Date(co.getTime() + i*ONE_DAY); + Date d = new Date(co.getTime() + i * ONE_DAY); cal.setTime(d); - int y = cal.get(Calendar.YEAR); - int mon = cal.get(Calendar.MONTH)+1-Calendar.JANUARY; - int dom = cal.get(Calendar.DATE); - int dow = cal.get(Calendar.DAY_OF_WEEK); + int y = cal.get(YEAR); + int mon = cal.get(MONTH) + 1 - JANUARY; + int dom = cal.get(DATE); + int dow = cal.get(DAY_OF_WEEK); - logln("Changeover " + (i>=0?"+":"") + i + - " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); + logln("Changeover " + (i >= 0 ? "+" : "") + i + + " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); if (y != 1582 || mon != MON[j] || dom != DOM[j] || dow != DOW[j]) { errln(" Fail: Above line is wrong"); } } - } - finally { + } finally { TimeZone.setDefault(savedZone); } } @@ -99,22 +111,22 @@ public class CalendarTest extends IntlTest { * of this test, we don't care about timezones and week data * (first day of week, minimal days in first week). */ + @SuppressWarnings("deprecation") public void TestMapping() { TimeZone saveZone = TimeZone.getDefault(); int[] DATA = { - // Julian# Year Month DOM JULIAN:Year, Month, DOM - 2440588, 1970, Calendar.JANUARY, 1, 1969, Calendar.DECEMBER, 19, - 2415080, 1900, Calendar.MARCH, 1, 1900, Calendar.FEBRUARY, 17, - 2451604, 2000, Calendar.FEBRUARY, 29, 2000, Calendar.FEBRUARY, 16, - 2452269, 2001, Calendar.DECEMBER, 25, 2001, Calendar.DECEMBER, 12, - 2416526, 1904, Calendar.FEBRUARY, 15, 1904, Calendar.FEBRUARY, 2, - 2416656, 1904, Calendar.JUNE, 24, 1904, Calendar.JUNE, 11, - 1721426, 1, Calendar.JANUARY, 1, 1, Calendar.JANUARY, 3, - 2000000, 763, Calendar.SEPTEMBER, 18, 763, Calendar.SEPTEMBER, 14, - 4000000, 6239, Calendar.JULY, 12, 6239, Calendar.MAY, 28, - 8000000, 17191, Calendar.FEBRUARY, 26, 17190, Calendar.OCTOBER, 22, - 10000000, 22666, Calendar.DECEMBER, 20, 22666, Calendar.JULY, 5, - }; + // Julian# Year Month DOM JULIAN:Year Month, DOM + 2440588, 1970, JANUARY, 1, 1969, DECEMBER, 19, + 2415080, 1900, MARCH, 1, 1900, FEBRUARY, 17, + 2451604, 2000, FEBRUARY, 29, 2000, FEBRUARY, 16, + 2452269, 2001, DECEMBER, 25, 2001, DECEMBER, 12, + 2416526, 1904, FEBRUARY, 15, 1904, FEBRUARY, 2, + 2416656, 1904, JUNE, 24, 1904, JUNE, 11, + 1721426, 1, JANUARY, 1, 1, JANUARY, 3, + 2000000, 763, SEPTEMBER, 18, 763, SEPTEMBER, 14, + 4000000, 6239, JULY, 12, 6239, MAY, 28, + 8000000, 17191, FEBRUARY, 26, 17190, OCTOBER, 22, + 10000000, 22666, DECEMBER, 20, 22666, JULY, 5}; try { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); @@ -123,11 +135,11 @@ public class CalendarTest extends IntlTest { GregorianCalendar cal = new GregorianCalendar(); for (int i = 0; i < DATA.length; i += 7) { int julian = DATA[i]; - int year = DATA[i+1]; - int month = DATA[i+2]; - int dom = DATA[i+3]; + int year = DATA[i + 1]; + int month = DATA[i + 2]; + int dom = DATA[i + 3]; int year2, month2, dom2; - long millis = ((long)julian - EPOCH_JULIAN) * ONE_DAY; + long millis = ((long) julian - EPOCH_JULIAN) * ONE_DAY; String s; // Test Gregorian computation @@ -137,56 +149,55 @@ public class CalendarTest extends IntlTest { long calMillis = cal.getTime().getTime(); long delta = calMillis - millis; cal.setTime(new Date(millis)); - year2 = cal.get(Calendar.YEAR); - month2 = cal.get(Calendar.MONTH); - dom2 = cal.get(Calendar.DAY_OF_MONTH); - s = "G " + year + "-" + (month+1-Calendar.JANUARY) + "-" + dom + - " => " + calMillis + - " (" + ((float)delta/ONE_DAY) + " day delta) => " + - year2 + "-" + (month2+1-Calendar.JANUARY) + "-" + dom2; - if (delta != 0 || year != year2 || month != month2 || - dom != dom2) { + year2 = cal.get(YEAR); + month2 = cal.get(MONTH); + dom2 = cal.get(DAY_OF_MONTH); + s = "G " + year + "-" + (month + 1 - JANUARY) + "-" + dom + + " => " + calMillis + + " (" + ((float) delta / ONE_DAY) + " day delta) => " + + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; + if (delta != 0 || year != year2 || month != month2 + || dom != dom2) { errln(s + " FAIL"); } else { logln(s); } // Test Julian computation - year = DATA[i+4]; - month = DATA[i+5]; - dom = DATA[i+6]; + year = DATA[i + 4]; + month = DATA[i + 5]; + dom = DATA[i + 6]; cal.setGregorianChange(PURE_JULIAN); cal.clear(); cal.set(year, month, dom); calMillis = cal.getTime().getTime(); delta = calMillis - millis; cal.setTime(new Date(millis)); - year2 = cal.get(Calendar.YEAR); - month2 = cal.get(Calendar.MONTH); - dom2 = cal.get(Calendar.DAY_OF_MONTH); - s = "J " + year + "-" + (month+1-Calendar.JANUARY) + "-" + dom + - " => " + calMillis + - " (" + ((float)delta/ONE_DAY) + " day delta) => " + - year2 + "-" + (month2+1-Calendar.JANUARY) + "-" + dom2; - if (delta != 0 || year != year2 || month != month2 || - dom != dom2) { + year2 = cal.get(YEAR); + month2 = cal.get(MONTH); + dom2 = cal.get(DAY_OF_MONTH); + s = "J " + year + "-" + (month + 1 - JANUARY) + "-" + dom + + " => " + calMillis + + " (" + ((float) delta / ONE_DAY) + " day delta) => " + + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; + if (delta != 0 || year != year2 || month != month2 + || dom != dom2) { errln(s + " FAIL"); } else { logln(s); } } - cal.setGregorianChange(new Date(1582-1900, Calendar.OCTOBER, 15)); - auxMapping(cal, 1582, Calendar.OCTOBER, 4); - auxMapping(cal, 1582, Calendar.OCTOBER, 15); - auxMapping(cal, 1582, Calendar.OCTOBER, 16); - for (int y = 800; y < 3000; y += 1+(int)100*Math.random()) { - for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; ++m) { + cal.setGregorianChange(new Date(1582 - 1900, OCTOBER, 15)); + auxMapping(cal, 1582, OCTOBER, 4); + auxMapping(cal, 1582, OCTOBER, 15); + auxMapping(cal, 1582, OCTOBER, 16); + for (int y = 800; y < 3000; y += 1 + 100 * Math.random()) { + for (int m = JANUARY; m <= DECEMBER; ++m) { auxMapping(cal, y, m, 15); } } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } @@ -195,14 +206,16 @@ public class CalendarTest extends IntlTest { cal.set(y, m, d); long millis = cal.getTime().getTime(); cal.setTime(new Date(millis)); - int year2 = cal.get(Calendar.YEAR); - int month2 = cal.get(Calendar.MONTH); - int dom2 = cal.get(Calendar.DAY_OF_MONTH); - if (y != year2 || m != month2 || dom2 != d) - errln("Round-trip failure: " + y + "-" + (m+1) + "-"+d+" =>ms=> " + - year2 + "-" + (month2+1) + "-" + dom2); + int year2 = cal.get(YEAR); + int month2 = cal.get(MONTH); + int dom2 = cal.get(DAY_OF_MONTH); + if (y != year2 || m != month2 || dom2 != d) { + errln("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + + year2 + "-" + (month2 + 1) + "-" + dom2); + } } + @SuppressWarnings("deprecation") public void TestGenericAPI() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { @@ -211,76 +224,95 @@ public class CalendarTest extends IntlTest { } String str; - - Date when = new Date(90, Calendar.APRIL, 15); + Date when = new Date(90, APRIL, 15); String tzid = "TestZone"; int tzoffset = 123400; SimpleTimeZone zone = new SimpleTimeZone(tzoffset, tzid); - Calendar cal = (Calendar)Calendar.getInstance((SimpleTimeZone)zone.clone()); + Calendar cal = Calendar.getInstance((SimpleTimeZone) zone.clone()); - if (!zone.equals(cal.getTimeZone())) errln("FAIL: Calendar.getTimeZone failed"); + if (!zone.equals(cal.getTimeZone())) { + errln("FAIL: Calendar.getTimeZone failed"); + } Calendar cal2 = Calendar.getInstance(cal.getTimeZone()); cal.setTime(when); cal2.setTime(when); - if (!(cal.equals(cal2))) errln("FAIL: Calendar.operator== failed"); + if (!(cal.equals(cal2))) { + errln("FAIL: Calendar.operator== failed"); + } // if ((*cal != *cal2)) errln("FAIL: Calendar.operator!= failed"); - if (!cal.equals(cal2) || - cal.before(cal2) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + if (!cal.equals(cal2) + || cal.before(cal2) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } cal2.setTime(new Date(when.getTime() + 1000)); - if (cal.equals(cal2) || - cal2.before(cal) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + if (cal.equals(cal2) + || cal2.before(cal) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } - cal.roll(Calendar.SECOND, true); - if (!cal.equals(cal2) || - cal.before(cal2) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + cal.roll(SECOND, true); + if (!cal.equals(cal2) + || cal.before(cal2) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } // Roll back to January - cal.roll(Calendar.MONTH, (int)(1 + Calendar.DECEMBER - cal.get(Calendar.MONTH))); - if (cal.equals(cal2) || - cal2.before(cal) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + cal.roll(MONTH, 1 + DECEMBER - cal.get(MONTH)); + if (cal.equals(cal2) + || cal2.before(cal) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } // C++ only /* TimeZone z = cal.orphanTimeZone(); - if (z.getID(str) != tzid || - z.getRawOffset() != tzoffset) - errln("FAIL: orphanTimeZone failed"); - */ - + if (z.getID(str) != tzid || + z.getRawOffset() != tzoffset) + errln("FAIL: orphanTimeZone failed"); + */ for (int i = 0; i < 2; ++i) { - boolean lenient = ( i > 0 ); + boolean lenient = (i > 0); cal.setLenient(lenient); - if (lenient != cal.isLenient()) errln("FAIL: setLenient/isLenient failed"); + if (lenient != cal.isLenient()) { + errln("FAIL: setLenient/isLenient failed"); + } // Later: Check for lenient behavior } int i; - for (i = Calendar.SUNDAY; i <= Calendar.SATURDAY; ++i) { + for (i = SUNDAY; i <= SATURDAY; ++i) { cal.setFirstDayOfWeek(i); - if (cal.getFirstDayOfWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); + if (cal.getFirstDayOfWeek() != i) { + errln("FAIL: set/getFirstDayOfWeek failed"); + } } for (i = 0; i <= 7; ++i) { cal.setMinimalDaysInFirstWeek(i); - if (cal.getMinimalDaysInFirstWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); + if (cal.getMinimalDaysInFirstWeek() != i) { + errln("FAIL: set/getFirstDayOfWeek failed"); + } } - for (i = 0; i < Calendar.FIELD_COUNT; ++i) { - if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) + for (i = 0; i < FIELD_COUNT; ++i) { + if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) { errln("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); - if (cal.getLeastMaximum(i) > cal.getMaximum(i)) + } + if (cal.getLeastMaximum(i) > cal.getMaximum(i)) { errln("FAIL: getLeastMaximum larger than getMaximum for field " + i); - if (cal.getMinimum(i) >= cal.getMaximum(i)) + } + if (cal.getMinimum(i) >= cal.getMaximum(i)) { errln("FAIL: getMinimum not less than getMaximum for field " + i); + } } cal.setTimeZone(TimeZone.getDefault()); @@ -306,30 +338,36 @@ public class CalendarTest extends IntlTest { } cal.getTime(); - for (i = 0; i < Calendar.FIELD_COUNT; ++i) { - switch(i) { - case Calendar.YEAR: case Calendar.MONTH: case Calendar.DATE: - case Calendar.HOUR_OF_DAY: case Calendar.MINUTE: case Calendar.SECOND: - if (!cal.isSet(i)) - errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); - break; - default: - if (cal.isSet(i)) - errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + for (i = 0; i < FIELD_COUNT; ++i) { + switch (i) { + case YEAR: + case MONTH: + case DATE: + case HOUR_OF_DAY: + case MINUTE: + case SECOND: + if (!cal.isSet(i)) { + errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); + } + break; + default: + if (cal.isSet(i)) { + errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + } } cal.clear(i); - if (cal.isSet(i)) errln("FAIL: Calendar.clear/isSet failed"); + if (cal.isSet(i)) { + errln("FAIL: Calendar.clear/isSet failed"); + } } // delete cal; // delete cal2; - Locale[] loc = Calendar.getAvailableLocales(); long count = loc.length; if (count < 1 || loc == null) { errln("FAIL: getAvailableLocales failed"); - } - else { + } else { for (i = 0; i < count; ++i) { cal = Calendar.getInstance(loc[i]); // delete cal; @@ -358,13 +396,15 @@ public class CalendarTest extends IntlTest { // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43); - if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) + if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) { errln("FAIL: new GregorianCalendar(ymdhm) failed"); + } // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55); - if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) + if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) { errln("FAIL: new GregorianCalendar(ymdhms) failed"); + } // C++ only: // GregorianCalendar gc2 = new GregorianCalendar(Locale.ENGLISH); @@ -378,19 +418,20 @@ public class CalendarTest extends IntlTest { public void TestRog() { GregorianCalendar gc = new GregorianCalendar(); - int year = 1997, month = Calendar.APRIL, date = 1; + int year = 1997, month = APRIL, date = 1; gc.set(year, month, date); // April 1, 1997 - gc.set(Calendar.HOUR_OF_DAY, 23); - gc.set(Calendar.MINUTE, 0); - gc.set(Calendar.SECOND, 0); - gc.set(Calendar.MILLISECOND, 0); + gc.set(HOUR_OF_DAY, 23); + gc.set(MINUTE, 0); + gc.set(SECOND, 0); + gc.set(MILLISECOND, 0); - for (int i = 0; i < 9; i++, gc.add(Calendar.DATE, 1)) { - if (gc.get(Calendar.YEAR) != year || - gc.get(Calendar.MONTH) != month || - gc.get(Calendar.DATE) != (date + i)) + for (int i = 0; i < 9; i++, gc.add(DATE, 1)) { + if (gc.get(YEAR) != year + || gc.get(MONTH) != month + || gc.get(DATE) != (date + i)) { errln("FAIL: Date " + gc.getTime() + " wrong"); + } } } @@ -402,162 +443,172 @@ public class CalendarTest extends IntlTest { void dowTest(boolean lenient) { GregorianCalendar cal = new GregorianCalendar(); - cal.set(1997, Calendar.AUGUST, 12); // Wednesday + cal.set(1997, AUGUST, 12); // Wednesday cal.getTime(); // Force update cal.setLenient(lenient); - cal.set(1996, Calendar.DECEMBER, 1); // Set the date to be December 1, 1996 - int dow = cal.get(Calendar.DAY_OF_WEEK); - int min = cal.getMinimum(Calendar.DAY_OF_WEEK); - int max = cal.getMaximum(Calendar.DAY_OF_WEEK); - if (dow < min || dow > max) errln("FAIL: Day of week " + dow + " out of range"); - if (dow != Calendar.SUNDAY) { + cal.set(1996, DECEMBER, 1); // Set the date to be December 1, 1996 + int dow = cal.get(DAY_OF_WEEK); + int min = cal.getMinimum(DAY_OF_WEEK); + int max = cal.getMaximum(DAY_OF_WEEK); + if (dow < min || dow > max) { + errln("FAIL: Day of week " + dow + " out of range"); + } + if (dow != SUNDAY) { errln("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); } - if (min != Calendar.SUNDAY || max != Calendar.SATURDAY) errln("FAIL: Min/max bad"); + if (min != SUNDAY || max != SATURDAY) { + errln("FAIL: Min/max bad"); + } } // Verify that the clone method produces distinct objects with no // unintentionally shared fields. public void TestClonesUnique908() { Calendar c = Calendar.getInstance(); - Calendar d = (Calendar)c.clone(); - c.set(Calendar.MILLISECOND, 123); - d.set(Calendar.MILLISECOND, 456); - if (c.get(Calendar.MILLISECOND) != 123 || - d.get(Calendar.MILLISECOND) != 456) { + Calendar d = (Calendar) c.clone(); + c.set(MILLISECOND, 123); + d.set(MILLISECOND, 456); + if (c.get(MILLISECOND) != 123 + || d.get(MILLISECOND) != 456) { errln("FAIL: Clones share fields"); } } // Verify effect of Gregorian cutoff value + @SuppressWarnings("deprecation") public void TestGregorianChange768() { boolean b; GregorianCalendar c = new GregorianCalendar(); logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b=c.isLeapYear(1800))); + logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); logln(" (should be FALSE)"); - if (b != false) errln("FAIL"); + if (b != false) { + errln("FAIL"); + } c.setGregorianChange(new Date(0, 0, 1)); // Jan 1 1900 logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b=c.isLeapYear(1800))); + logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); logln(" (should be TRUE)"); - if (b != true) errln("FAIL"); + if (b != true) { + errln("FAIL"); + } } // Test the correct behavior of the disambiguation algorithm. public void TestDisambiguation765() throws Exception { - Locale savedLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - Calendar c = Calendar.getInstance(); - c.setLenient(false); - - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DATE, 3); - - verify765("1997 third day of June = ", c, 1997, Calendar.JUNE, 3); - - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); - verify765("1997 first Tuesday in June = ", c, 1997, Calendar.JUNE, 3); - - c.setLenient(true); // for 4944795 - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1); - verify765("1997 last Tuesday in June = ", c, 1997, Calendar.JUNE, 24); - - c.setLenient(false); - IllegalArgumentException e = null; + Locale savedLocale = Locale.getDefault(); try { + Locale.setDefault(Locale.US); + Calendar c = Calendar.getInstance(); + c.setLenient(false); + c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 0); - c.getTime(); - } - catch (IllegalArgumentException ex) { - e = ex; - } - verify765("1997 zero-th Tuesday in June = ", e); + c.set(YEAR, 1997); + c.set(MONTH, JUNE); + c.set(DATE, 3); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 1); - verify765("1997 Tuesday in week 1 of June = ", c, 1997, Calendar.JUNE, 3); + verify765("1997 third day of June = ", c, 1997, JUNE, 3); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 4); - verify765("1997 Tuesday in week 4 of June = ", c, 1997, Calendar.JUNE, 24); - - try { c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 1); - verify765("1997 Tuesday in week 0 of June = ", c, 1997, Calendar.JUNE, 3); - } - catch (IllegalArgumentException ex) { - errln("FAIL: Exception seen: " + ex.getMessage()); - // ex.printStackTrace(log); - } + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, 1); + verify765("1997 first Tuesday in June = ", c, 1997, JUNE, 3); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 2); - verify765("1997 Tuesday in week 2 of year = ", c, 1997, Calendar.JANUARY, 7); - - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 10); - verify765("1997 Tuesday in week 10 of year = ", c, 1997, Calendar.MARCH, 4); - - try { + c.setLenient(true); // for 4944795 c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 0); - verify765("1997 Tuesday in week 0 of year = ", c, 1996, Calendar.DECEMBER, 24); - throw new Exception("Fail: WEEK_OF_YEAR 0 should be illegal"); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, -1); + verify765("1997 last Tuesday in June = ", c, 1997, JUNE, 24); + + c.setLenient(false); + IllegalArgumentException e = null; + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, 0); + c.getTime(); + } catch (IllegalArgumentException ex) { + e = ex; + } + verify765("1997 zero-th Tuesday in June = ", e); + + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 1); + verify765("1997 Tuesday in week 1 of June = ", c, 1997, JUNE, 3); + + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 4); + verify765("1997 Tuesday in week 4 of June = ", c, 1997, JUNE, 24); + + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 1); + verify765("1997 Tuesday in week 0 of June = ", c, 1997, JUNE, 3); + } catch (IllegalArgumentException ex) { + errln("FAIL: Exception seen: " + ex.getMessage()); + // ex.printStackTrace(log); + } + + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 2); + verify765("1997 Tuesday in week 2 of year = ", c, 1997, JANUARY, 7); + + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 10); + verify765("1997 Tuesday in week 10 of year = ", c, 1997, MARCH, 4); + + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 0); + verify765("1997 Tuesday in week 0 of year = ", c, 1996, DECEMBER, 24); + throw new Exception("Fail: WEEK_OF_YEAR 0 should be illegal"); + } catch (IllegalArgumentException ex) { + } + } finally { + Locale.setDefault(savedLocale); } - catch (IllegalArgumentException ex) {} - } - finally { - Locale.setDefault(savedLocale); - } } + void verify765(String msg, Calendar c, int year, int month, int day) { - if (c.get(Calendar.YEAR) == year && - c.get(Calendar.MONTH) == month && - c.get(Calendar.DATE) == day) { + if (c.get(YEAR) == year + && c.get(MONTH) == month + && c.get(DATE) == day) { logln("PASS: " + msg + c.getTime()); - } - else { - errln("FAIL: " + msg + c.getTime() + - "; expected " + - year + "/" + (month+1) + "/" + day); + } else { + errln("FAIL: " + msg + c.getTime() + + "; expected " + + year + "/" + (month + 1) + "/" + day); } } + // Called when e expected to be non-null void verify765(String msg, IllegalArgumentException e) { - if (e == null) errln("FAIL: No IllegalArgumentException for " + msg); - else logln("PASS: " + msg + "IllegalArgument as expected"); + if (e == null) { + errln("FAIL: No IllegalArgumentException for " + msg); + } else { + logln("PASS: " + msg + "IllegalArgument as expected"); + } } // Test the behavior of GMT vs. local time @@ -588,106 +639,112 @@ public class CalendarTest extends IntlTest { Date date; Calendar gmtcal = Calendar.getInstance(); gmtcal.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca")); - gmtcal.set(yr, mo-1, dt, hr, mn, sc); - gmtcal.set(Calendar.MILLISECOND, 0); + gmtcal.set(yr, mo - 1, dt, hr, mn, sc); + gmtcal.set(MILLISECOND, 0); date = gmtcal.getTime(); - logln("date = "+date); + logln("date = " + date); Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); cal.setTime(date); - int offset = cal.getTimeZone().getOffset(cal.get(Calendar.ERA), - cal.get(Calendar.YEAR), - cal.get(Calendar.MONTH), - cal.get(Calendar.DATE), - cal.get(Calendar.DAY_OF_WEEK), - cal.get(Calendar.MILLISECOND)); + int offset = cal.getTimeZone().getOffset(cal.get(ERA), + cal.get(YEAR), + cal.get(MONTH), + cal.get(DATE), + cal.get(DAY_OF_WEEK), + cal.get(MILLISECOND)); - logln("offset for "+date+"= "+(offset/1000/60/60.0) + "hr"); + logln("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); - int utc = ((cal.get(Calendar.HOUR_OF_DAY) * 60 + - cal.get(Calendar.MINUTE)) * 60 + - cal.get(Calendar.SECOND)) * 1000 + - cal.get(Calendar.MILLISECOND) - offset; + int utc = ((cal.get(HOUR_OF_DAY) * 60 + + cal.get(MINUTE)) * 60 + + cal.get(SECOND)) * 1000 + + cal.get(MILLISECOND) - offset; int expected = ((hr * 60 + mn) * 60 + sc) * 1000; - if (utc != expected) - errln("FAIL: Discrepancy of " + - (utc - expected) + " millis = " + - ((utc-expected)/1000/60/60.0) + " hr"); + if (utc != expected) { + errln("FAIL: Discrepancy of " + + (utc - expected) + " millis = " + + ((utc - expected) / 1000 / 60 / 60.0) + " hr"); + } } // Verify that add and set work regardless of the order in which // they are called. public void TestAddSetOrder621() { + @SuppressWarnings("deprecation") Date d = new Date(97, 4, 14, 13, 23, 45); - Calendar cal = Calendar.getInstance (); - cal.setTime (d); - cal.add (Calendar.DATE, -5); - cal.set (Calendar.HOUR_OF_DAY, 0); - cal.set (Calendar.MINUTE, 0); - cal.set (Calendar.SECOND, 0); + Calendar cal = Calendar.getInstance(); + cal.setTime(d); + cal.add(DATE, -5); + cal.set(HOUR_OF_DAY, 0); + cal.set(MINUTE, 0); + cal.set(SECOND, 0); // ma feb 03 00:00:00 GMT+00:00 1997 - String s = cal.getTime ().toString (); + String s = cal.getTime().toString(); - cal = Calendar.getInstance (); - cal.setTime (d); - cal.set (Calendar.HOUR_OF_DAY, 0); - cal.set (Calendar.MINUTE, 0); - cal.set (Calendar.SECOND, 0); - cal.add (Calendar.DATE, -5); + cal = Calendar.getInstance(); + cal.setTime(d); + cal.set(HOUR_OF_DAY, 0); + cal.set(MINUTE, 0); + cal.set(SECOND, 0); + cal.add(DATE, -5); // ma feb 03 13:11:06 GMT+00:00 1997 - String s2 = cal.getTime ().toString (); + String s2 = cal.getTime().toString(); - if (s.equals(s2)) + if (s.equals(s2)) { logln("Pass: " + s + " == " + s2); - else + } else { errln("FAIL: " + s + " != " + s2); + } } // Verify that add works. public void TestAdd520() { - int y = 1997, m = Calendar.FEBRUARY, d = 1; - GregorianCalendar temp = new GregorianCalendar( y, m, d ); + int y = 1997, m = FEBRUARY, d = 1; + GregorianCalendar temp = new GregorianCalendar(y, m, d); check520(temp, y, m, d); - temp.add( temp.YEAR, 1 ); + temp.add(YEAR, 1); y++; check520(temp, y, m, d); - temp.add( temp.MONTH, 1 ); + temp.add(MONTH, 1); m++; check520(temp, y, m, d); - temp.add( temp.DATE, 1 ); + temp.add(DATE, 1); d++; check520(temp, y, m, d); - temp.add( temp.DATE, 2 ); + temp.add(DATE, 2); d += 2; check520(temp, y, m, d); - temp.add( temp.DATE, 28 ); - d = 1; ++m; + temp.add(DATE, 28); + d = 1; + ++m; check520(temp, y, m, d); } + void check520(Calendar c, int y, int m, int d) { - if (c.get(Calendar.YEAR) != y || - c.get(Calendar.MONTH) != m || - c.get(Calendar.DATE) != d) { - errln("FAILURE: Expected YEAR/MONTH/DATE of " + - y + "/" + (m+1) + "/" + d + - "; got " + - c.get(Calendar.YEAR) + "/" + - (c.get(Calendar.MONTH)+1) + "/" + - c.get(Calendar.DATE)); + if (c.get(YEAR) != y + || c.get(MONTH) != m + || c.get(DATE) != d) { + errln("FAILURE: Expected YEAR/MONTH/DATE of " + + y + "/" + (m + 1) + "/" + d + + "; got " + + c.get(YEAR) + "/" + + (c.get(MONTH) + 1) + "/" + + c.get(DATE)); + } else { + logln("Confirmed: " + + y + "/" + (m + 1) + "/" + d); } - else logln("Confirmed: " + - y + "/" + (m+1) + "/" + d); } // Verify that setting fields works. This test fails when an exception is thrown. @@ -697,18 +754,18 @@ public class CalendarTest extends IntlTest { GregorianCalendar g2 = new GregorianCalendar(); // At this point UTC value is set, various fields are not. // Now set to noon. - g2.set(Calendar.HOUR, 12); - g2.set(Calendar.MINUTE, 0); - g2.set(Calendar.SECOND, 0); + g2.set(HOUR, 12); + g2.set(MINUTE, 0); + g2.set(SECOND, 0); // At this point the object thinks UTC is NOT set, but fields are set. // The following line will result in IllegalArgumentException because // it thinks the YEAR is set and it is NOT. - if (g2.equals(g)) + if (g2.equals(g)) { logln("Same"); - else + } else { logln("Different"); - } - catch (IllegalArgumentException e) { + } + } catch (IllegalArgumentException e) { errln("Unexpected exception seen: " + e); } } @@ -729,28 +786,28 @@ public class CalendarTest extends IntlTest { FileInputStream in = new FileInputStream(FILENAME); ObjectInputStream t = new ObjectInputStream(in); - String pre = (String)t.readObject(); - Calendar c = (Calendar)t.readObject(); - String post = (String)t.readObject(); + String pre = (String) t.readObject(); + Calendar c = (Calendar) t.readObject(); + String post = (String) t.readObject(); in.close(); - ok = pre.equals(PREFIX) && - post.equals(POSTFIX) && - cal.equals(c); + ok = pre.equals(PREFIX) + && post.equals(POSTFIX) + && cal.equals(c); File fl = new File(FILENAME); fl.delete(); - } - catch (IOException e) { + } catch (IOException e) { errln("FAIL: Exception received:"); // e.printStackTrace(log); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { errln("FAIL: Exception received:"); // e.printStackTrace(log); } - if (!ok) errln("Serialization of Calendar object failed."); + if (!ok) { + errln("Serialization of Calendar object failed."); + } } static final String PREFIX = "abc"; static final String POSTFIX = "def"; @@ -758,14 +815,16 @@ public class CalendarTest extends IntlTest { // Try to zero out the seconds field public void TestSecondsZero121() { - Calendar cal = new GregorianCalendar(); + Calendar cal = new GregorianCalendar(); // Initialize with current date/time cal.setTime(new Date()); // Round down to minute - cal.set(Calendar.SECOND, 0); - Date d = cal.getTime(); + cal.set(SECOND, 0); + Date d = cal.getTime(); String s = d.toString(); - if (s.indexOf(":00 ") < 0) errln("Expected to see :00 in " + s); + if (s.indexOf(":00 ") < 0) { + errln("Expected to see :00 in " + s); + } } // Try various sequences of add, set, and get method calls. @@ -777,15 +836,17 @@ public class CalendarTest extends IntlTest { // - Addition uses millis which are still *now* // { - Calendar calendar = new GregorianCalendar( ) ; - calendar.set( 1993, Calendar.JANUARY, 4 ) ; - logln( "1A) " + value( calendar ) ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(); + calendar.set(1993, JANUARY, 4); + logln("1A) " + value(calendar)); + calendar.add(DATE, 1); String v = value(calendar); - logln( "1B) " + v ); - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("1B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } // @@ -793,16 +854,17 @@ public class CalendarTest extends IntlTest { // - Upon initialization calendar fields set, millis = 0 // - Addition uses millis which are still 1970, 0, 1 // - { - Calendar calendar = new GregorianCalendar( 1993, Calendar.JANUARY, 4 ) ; - logln( "2A) " + value( calendar ) ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); + logln("2A) " + value(calendar)); + calendar.add(DATE, 1); String v = value(calendar); - logln( "2B) " + v ); - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("2B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } // @@ -811,102 +873,99 @@ public class CalendarTest extends IntlTest { // - getTime( ) is called which forces the millis to be set // - Addition uses millis which are correct // - { - Calendar calendar = new GregorianCalendar( 1993, Calendar.JANUARY, 4 ) ; - logln( "3A) " + value( calendar ) ) ; - calendar.getTime( ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); + logln("3A) " + value(calendar)); + calendar.getTime(); + calendar.add(DATE, 1); String v = value(calendar); - logln( "3B) " + v ) ; - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("3B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } } - static String value( Calendar calendar ) { - return( calendar.get( Calendar.YEAR ) + "/" + - calendar.get( Calendar.MONTH ) + "/" + - calendar.get( Calendar.DATE ) ) ; + static String value(Calendar calendar) { + return (calendar.get(YEAR) + "/" + + calendar.get(MONTH) + "/" + + calendar.get(DATE)); } static String EXPECTED_0610 = "1993/0/5"; // Test that certain fields on a certain date are as expected. public void TestFields060() { int year = 1997; - int month = java.util.Calendar.OCTOBER; //october + int month = OCTOBER; //october int dDate = 22; //DAYOFWEEK should return 3 for Wednesday GregorianCalendar calendar = null; - calendar = new GregorianCalendar( year, month, dDate); - for (int i = 0; i < EXPECTED_FIELDS.length; ) { + calendar = new GregorianCalendar(year, month, dDate); + for (int i = 0; i < EXPECTED_FIELDS.length;) { int field = EXPECTED_FIELDS[i++]; int expected = EXPECTED_FIELDS[i++]; if (calendar.get(field) != expected) { - errln("Expected field " + field + " to have value " + expected + - "; received " + calendar.get(field) + " instead"); + errln("Expected field " + field + " to have value " + expected + + "; received " + calendar.get(field) + " instead"); } } } - static int EXPECTED_FIELDS[] = { - Calendar.YEAR, 1997, - Calendar.MONTH, Calendar.OCTOBER, - Calendar.DAY_OF_MONTH, 22, - Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY, - Calendar.DAY_OF_WEEK_IN_MONTH, 4, - Calendar.DAY_OF_YEAR, 295 - }; + static int[] EXPECTED_FIELDS = { + YEAR, 1997, + MONTH, OCTOBER, + DAY_OF_MONTH, 22, + DAY_OF_WEEK, WEDNESDAY, + DAY_OF_WEEK_IN_MONTH, 4, + DAY_OF_YEAR, 295}; static final String[] calendarFieldNames = { - /* 0 */ "ERA", - /* 1 */ "YEAR", - /* 2 */ "MONTH", - /* 3 */ "WEEK_OF_YEAR", - /* 4 */ "WEEK_OF_MONTH", - /* 5 */ "DAY_OF_MONTH", - /* 6 */ "DAY_OF_YEAR", - /* 7 */ "DAY_OF_WEEK", - /* 8 */ "DAY_OF_WEEK_IN_MONTH", - /* 9 */ "AM_PM", - /* 10 */ "HOUR", - /* 11 */ "HOUR_OF_DAY", - /* 12 */ "MINUTE", - /* 13 */ "SECOND", - /* 14 */ "MILLISECOND", - /* 15 */ "ZONE_OFFSET", - /* 16 */ "DST_OFFSET" - }; + /* 0 */ "ERA", + /* 1 */ "YEAR", + /* 2 */ "MONTH", + /* 3 */ "WEEK_OF_YEAR", + /* 4 */ "WEEK_OF_MONTH", + /* 5 */ "DAY_OF_MONTH", + /* 6 */ "DAY_OF_YEAR", + /* 7 */ "DAY_OF_WEEK", + /* 8 */ "DAY_OF_WEEK_IN_MONTH", + /* 9 */ "AM_PM", + /* 10 */ "HOUR", + /* 11 */ "HOUR_OF_DAY", + /* 12 */ "MINUTE", + /* 13 */ "SECOND", + /* 14 */ "MILLISECOND", + /* 15 */ "ZONE_OFFSET", + /* 16 */ "DST_OFFSET"}; // Verify that the fields are as expected (mostly zero) at the epoch start. // Note that we adjust for the default timezone to get most things to zero. public void TestEpochStartFields() { String[][] lt = { - {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ - {"en", "US", "America/Anchorage"}, /* First day = 1, Minimum day = 1 */ - {"en", "TO", "Pacific/Tongatapu"}, /* First day = 1, Minimum day = 1 */ - {"en", "MH", "Pacific/Majuro"}, /* First day = 1, Minimum day = 1 */ - {"ja", "JP", "Asia/Tokyo"}, /* First day = 1, Minimum day = 1 */ - {"iw", "IL", "Asia/Jerusalem"}, /* First day = 1, Minimum day = 1 */ - {"hi", "IN", "Asia/Jakarta"}, /* First day = 1, Minimum day = 1 */ - {"en", "GB", "Europe/London"}, /* First day = 2, Minimum day = 1 */ - {"en", "GB", "GMT"}, /* First day = 2, Minimum day = 1 */ - {"de", "DE", "Europe/Berlin"}, /* First day = 2, Minimum day = 4 */ - {"ar", "EG", "Africa/Cairo"}, /* First day = 7, Minimum day = 1 */ - }; + {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ + {"en", "US", "America/Anchorage"}, /* First day = 1, Minimum day = 1 */ + {"en", "TO", "Pacific/Tongatapu"}, /* First day = 1, Minimum day = 1 */ + {"en", "MH", "Pacific/Majuro"}, /* First day = 1, Minimum day = 1 */ + {"ja", "JP", "Asia/Tokyo"}, /* First day = 1, Minimum day = 1 */ + {"iw", "IL", "Asia/Jerusalem"}, /* First day = 1, Minimum day = 1 */ + {"hi", "IN", "Asia/Jakarta"}, /* First day = 1, Minimum day = 1 */ + {"en", "GB", "Europe/London"}, /* First day = 2, Minimum day = 1 */ + {"en", "GB", "GMT"}, /* First day = 2, Minimum day = 1 */ + {"de", "DE", "Europe/Berlin"}, /* First day = 2, Minimum day = 4 */ + {"ar", "EG", "Africa/Cairo"}}; /* First day = 7, Minimum day = 1 */ int[][] goldenData = { - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, -28800000, 0}, - {1, 1969, 11, 1, 5, 31, 365, 4, 5, 1, 11, 23, 0, 0, 0, -36000000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 46800000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 43200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 32400000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 25200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 1, 1, 0, 0, 0, 3600000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 3600000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, - }; + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, -28800000, 0}, + {1, 1969, 11, 1, 5, 31, 365, 4, 5, 1, 11, 23, 0, 0, 0, -36000000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 46800000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 43200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 32400000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 25200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 1, 1, 0, 0, 0, 3600000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 3600000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}}; Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -927,19 +986,18 @@ public class CalendarTest extends IntlTest { boolean err = false; for (int i = 0; i < calendarFieldNames.length; ++i) { if ((val = c.get(i)) != EPOCH_FIELDS[i]) { - errln("Wrong value: " + val + - " for field(" + calendarFieldNames[i] + - "), expected: " + EPOCH_FIELDS[i]); + errln("Wrong value: " + val + + " for field(" + calendarFieldNames[i] + + "), expected: " + EPOCH_FIELDS[i]); err = true; } } if (err) { - errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + - "\n\tLocale=" + l + "\n\tCalendar=" + c); + errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + + "\n\tLocale=" + l + "\n\tCalendar=" + c); } } - } - finally { + } finally { Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); } @@ -948,125 +1006,146 @@ public class CalendarTest extends IntlTest { // Verify that as you add days to the calendar (e.g., 24 day periods), // the day of the week shifts in the expected pattern. public void TestDOWProgression() { - Calendar cal = - new GregorianCalendar(1972, Calendar.OCTOBER, 26); + Calendar cal + = new GregorianCalendar(1972, OCTOBER, 26); marchByDelta(cal, 24); // Last parameter must be != 0 modulo 7 } // Supply a delta which is not a multiple of 7. void marchByDelta(Calendar cal, int delta) { - Calendar cur = (Calendar)cal.clone(); - int initialDOW = cur.get(Calendar.DAY_OF_WEEK); + Calendar cur = (Calendar) cal.clone(); + int initialDOW = cur.get(DAY_OF_WEEK); int DOW, newDOW = initialDOW; do { DOW = newDOW; logln("DOW = " + DOW + " " + cur.getTime()); - cur.add(Calendar.DAY_OF_WEEK, delta); - newDOW = cur.get(Calendar.DAY_OF_WEEK); + cur.add(DAY_OF_WEEK, delta); + newDOW = cur.get(DAY_OF_WEEK); int expectedDOW = 1 + (DOW + delta - 1) % 7; if (newDOW != expectedDOW) { - errln("Day of week should be " + expectedDOW + - " instead of " + newDOW + " on " + cur.getTime()); + errln("Day of week should be " + expectedDOW + + " instead of " + newDOW + " on " + cur.getTime()); return; } - } - while (newDOW != initialDOW); + } while (newDOW != initialDOW); } public void TestActualMinMax() { - Calendar cal = new GregorianCalendar(1967, Calendar.MARCH, 10); - cal.setFirstDayOfWeek(Calendar.SUNDAY); + Calendar cal = new GregorianCalendar(1967, MARCH, 10); + cal.setFirstDayOfWeek(SUNDAY); cal.setMinimalDaysInFirstWeek(3); - if (cal.getActualMinimum(Calendar.DAY_OF_MONTH) != 1) - errln("Actual minimum date for 3/10/1967 should have been 1; got " + - cal.getActualMinimum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 31) - errln("Actual maximum date for 3/10/1967 should have been 31; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); + if (cal.getActualMinimum(DAY_OF_MONTH) != 1) { + errln("Actual minimum date for 3/10/1967 should have been 1; got " + + cal.getActualMinimum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_MONTH) != 31) { + errln("Actual maximum date for 3/10/1967 should have been 31; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } - cal.set(Calendar.MONTH, Calendar.FEBRUARY); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 28) - errln("Actual maximum date for 2/10/1967 should have been 28; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_YEAR) != 365) - errln("Number of days in 1967 should have been 365; got " + - cal.getActualMaximum(Calendar.DAY_OF_YEAR)); + cal.set(MONTH, FEBRUARY); + if (cal.getActualMaximum(DAY_OF_MONTH) != 28) { + errln("Actual maximum date for 2/10/1967 should have been 28; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_YEAR) != 365) { + errln("Number of days in 1967 should have been 365; got " + + cal.getActualMaximum(DAY_OF_YEAR)); + } - cal.set(Calendar.YEAR, 1968); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 29) - errln("Actual maximum date for 2/10/1968 should have been 29; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_YEAR) != 366) - errln("Number of days in 1968 should have been 366; got " + - cal.getActualMaximum(Calendar.DAY_OF_YEAR)); + cal.set(YEAR, 1968); + if (cal.getActualMaximum(DAY_OF_MONTH) != 29) { + errln("Actual maximum date for 2/10/1968 should have been 29; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { + errln("Number of days in 1968 should have been 366; got " + + cal.getActualMaximum(DAY_OF_YEAR)); + } // Using week settings of SUNDAY/3 (see above) - if (cal.getActualMaximum(Calendar.WEEK_OF_YEAR) != 52) - errln("Number of weeks in 1968 should have been 52; got " + - cal.getActualMaximum(Calendar.WEEK_OF_YEAR)); + if (cal.getActualMaximum(WEEK_OF_YEAR) != 52) { + errln("Number of weeks in 1968 should have been 52; got " + + cal.getActualMaximum(WEEK_OF_YEAR)); + } - cal.set(Calendar.YEAR, 1976); + cal.set(YEAR, 1976); // Using week settings of SUNDAY/3 (see above) - if (cal.getActualMaximum(Calendar.WEEK_OF_YEAR) != 53) - errln("Number of weeks in 1976 should have been 53; got " + - cal.getActualMaximum(Calendar.WEEK_OF_YEAR)); + if (cal.getActualMaximum(WEEK_OF_YEAR) != 53) { + errln("Number of weeks in 1976 should have been 53; got " + + cal.getActualMaximum(WEEK_OF_YEAR)); + } } public void TestRoll() { - Calendar cal = new GregorianCalendar(1997, Calendar.JANUARY, 31); + Calendar cal = new GregorianCalendar(1997, JANUARY, 31); - int[] dayValues = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31 }; + int[] dayValues = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31}; for (int i = 0; i < dayValues.length; i++) { - Calendar cal2 = (Calendar)cal.clone(); - cal2.roll(Calendar.MONTH, i); - if (cal2.get(Calendar.DAY_OF_MONTH) != dayValues[i]) + Calendar cal2 = (Calendar) cal.clone(); + cal2.roll(MONTH, i); + if (cal2.get(DAY_OF_MONTH) != dayValues[i]) { errln("Rolling the month in 1/31/1997 up by " + i + " should have yielded " - + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " - + ((i + 1) % 12) + "/" + cal2.get(Calendar.DAY_OF_MONTH) + "/1997."); + + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " + + ((i + 1) % 12) + "/" + cal2.get(DAY_OF_MONTH) + "/1997."); + } } - cal.set(1996, Calendar.FEBRUARY, 29); + cal.set(1996, FEBRUARY, 29); - int[] monthValues = { 1, 2, 2, 2, 1, 2, 2, 2, 1, 2 }; - int[] dayValues2 = { 29, 1, 1, 1, 29, 1, 1, 1, 29, 1 }; + int[] monthValues = {1, 2, 2, 2, 1, 2, 2, 2, 1, 2}; + int[] dayValues2 = {29, 1, 1, 1, 29, 1, 1, 1, 29, 1}; for (int i = 0; i < dayValues2.length; i++) { - Calendar cal2 = (Calendar)cal.clone(); - cal2.roll(Calendar.YEAR, i); - if (cal2.get(Calendar.DAY_OF_MONTH) != dayValues2[i] || cal2.get(Calendar.MONTH) - != monthValues[i]) + Calendar cal2 = (Calendar) cal.clone(); + cal2.roll(YEAR, i); + if (cal2.get(DAY_OF_MONTH) != dayValues2[i] || cal2.get(MONTH) + != monthValues[i]) { errln("Rolling the year in 2/29/1996 up by " + i + " should have yielded " - + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" - + (1996 + i) + ", but actually yielded " - + (cal2.get(Calendar.MONTH) + 1) + "/" + - cal2.get(Calendar.DAY_OF_MONTH) + "/" + (1996 + i) + "."); + + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" + + (1996 + i) + ", but actually yielded " + + (cal2.get(MONTH) + 1) + "/" + + cal2.get(DAY_OF_MONTH) + "/" + (1996 + i) + "."); + } } // Test rolling hour of day - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.roll(Calendar.HOUR_OF_DAY, -2); - int f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 22) errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); - cal.roll(Calendar.HOUR_OF_DAY, 5); - f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 3) errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); - cal.roll(Calendar.HOUR_OF_DAY, 21); - f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 0) errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + cal.set(HOUR_OF_DAY, 0); + cal.roll(HOUR_OF_DAY, -2); + int f = cal.get(HOUR_OF_DAY); + if (f != 22) { + errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); + } + cal.roll(HOUR_OF_DAY, 5); + f = cal.get(HOUR_OF_DAY); + if (f != 3) { + errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); + } + cal.roll(HOUR_OF_DAY, 21); + f = cal.get(HOUR_OF_DAY); + if (f != 0) { + errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + } // Test rolling hour - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.roll(Calendar.HOUR, -2); - f = cal.get(Calendar.HOUR); - if (f != 10) errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); - cal.roll(Calendar.HOUR, 5); - f = cal.get(Calendar.HOUR); - if (f != 3) errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); - cal.roll(Calendar.HOUR, 9); - f = cal.get(Calendar.HOUR); - if (f != 0) errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + cal.set(HOUR_OF_DAY, 0); + cal.roll(HOUR, -2); + f = cal.get(HOUR); + if (f != 10) { + errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); + } + cal.roll(HOUR, 5); + f = cal.get(HOUR); + if (f != 3) { + errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); + } + cal.roll(HOUR, 9); + f = cal.get(HOUR); + if (f != 0) { + errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + } } /* @@ -1081,19 +1160,18 @@ public class CalendarTest extends IntlTest { TimeZone.setDefault(TimeZone.getTimeZone("PST")); Calendar cal = Calendar.getInstance(); - cal.set(Calendar.YEAR, 2001); - cal.set(Calendar.MONTH, Calendar.OCTOBER); - cal.set(Calendar.WEEK_OF_YEAR, 4); - cal.set(Calendar.DAY_OF_WEEK, 2); + cal.set(YEAR, 2001); + cal.set(MONTH, OCTOBER); + cal.set(WEEK_OF_YEAR, 4); + cal.set(DAY_OF_WEEK, 2); - if (cal.get(Calendar.YEAR) != 2001 || - cal.get(Calendar.MONTH) != Calendar.JANUARY || - cal.get(Calendar.DATE) != 22 || - cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { + if (cal.get(YEAR) != 2001 + || cal.get(MONTH) != JANUARY + || cal.get(DATE) != 22 + || cal.get(DAY_OF_WEEK) != MONDAY) { errln("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); } - } - finally { + } finally { Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); } diff --git a/jdk/test/java/util/Calendar/CalendarTypeTest.java b/jdk/test/java/util/Calendar/CalendarTypeTest.java index ce36cd656b3..41bb87e7421 100644 --- a/jdk/test/java/util/Calendar/CalendarTypeTest.java +++ b/jdk/test/java/util/Calendar/CalendarTypeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,13 @@ * @summary Unit test for calendar types */ -import java.util.*; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.Set; public class CalendarTypeTest { + // Calendar types supported in JRE static Locale[] locales = new Locale[] { Locale.US, @@ -37,23 +41,20 @@ public class CalendarTypeTest { new Locale("th", "TH"), Locale.forLanguageTag("en-US-u-ca-buddhist"), new Locale("ja", "JP", "JP"), - Locale.forLanguageTag("en-US-u-ca-japanese"), - }; + Locale.forLanguageTag("en-US-u-ca-japanese")}; static final String[] TYPES = new String[] { "gregory", "buddhist", - "japanese", - }; + "japanese"}; static final String[] ALIASES = new String[] { "gregorian", - "iso8601", - }; + "iso8601"}; public static void main(String[] args) { for (int i = 0; i < locales.length; i++) { Calendar cal = Calendar.getInstance(locales[i]); String type = cal.getCalendarType(); - checkValue("bad calendar type", type, TYPES[i/2]); + checkValue("bad calendar type", type, TYPES[i / 2]); } GregorianCalendar gcal = new GregorianCalendar(); @@ -88,10 +89,13 @@ public class CalendarTypeTest { } } + @SuppressWarnings("serial") private static class Gregorian extends GregorianCalendar { } + @SuppressWarnings("serial") private static class Koyomi extends Calendar { + @Override protected void computeTime() { throw new UnsupportedOperationException("Not supported yet."); diff --git a/jdk/test/java/util/Calendar/FieldStateTest.java b/jdk/test/java/util/Calendar/FieldStateTest.java index caa6f219a24..34ab9e8076d 100644 --- a/jdk/test/java/util/Calendar/FieldStateTest.java +++ b/jdk/test/java/util/Calendar/FieldStateTest.java @@ -144,8 +144,11 @@ public class FieldStateTest extends IntlTest { } logln("Set day of week to SUNDAY and date to 2003/10/31. " - + "Then, getTime and set week of year to 43."); - cal.setTime(new Date(2003-1990, OCTOBER, 31)); + + "Then, getTime and set week of year to 43."); + + @SuppressWarnings("deprecation") + Date d = new Date(2003 - 1990, OCTOBER, 31); + cal.setTime(d); cal.set(DAY_OF_WEEK, SUNDAY); cal.set(2003, OCTOBER, 31); // 2003/10/31 is Friday. cal.set(ZONE_OFFSET, 0); @@ -166,8 +169,8 @@ public class FieldStateTest extends IntlTest { * 4916815: REGRESSION: Problem with java.util.Calendar VM 1.4.2-b28 */ public void Test4916815() { - logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. "+ - "Set dayofweek to Sunday which should be 2003/9/21."); + logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + + "Set dayofweek to Sunday which should be 2003/9/21."); Koyomi cal = new Koyomi(); cal.clear(); // 2003/9/26 (Fri) @@ -192,17 +195,17 @@ public class FieldStateTest extends IntlTest { cal.clear(); cal.set(YEAR, 2004); cal.set(WEEK_OF_YEAR, 1); - checkDate(cal, SUNDAY, 2003, DECEMBER, 28); - checkDate(cal, MONDAY, 2003, DECEMBER, 29); - checkDate(cal, TUESDAY, 2003, DECEMBER, 30); + checkDate(cal, SUNDAY, 2003, DECEMBER, 28); + checkDate(cal, MONDAY, 2003, DECEMBER, 29); + checkDate(cal, TUESDAY, 2003, DECEMBER, 30); checkDate(cal, WEDNESDAY, 2003, DECEMBER, 31); - checkDate(cal, THURSDAY, 2004, JANUARY, 1); - checkDate(cal, FRIDAY, 2004, JANUARY, 2); - checkDate(cal, SATURDAY, 2004, JANUARY, 3); + checkDate(cal, THURSDAY, 2004, JANUARY, 1); + checkDate(cal, FRIDAY, 2004, JANUARY, 2); + checkDate(cal, SATURDAY, 2004, JANUARY, 3); } private void checkDate(Koyomi cal, int dayOfWeek, - int expectedYear, int expectedMonth, int expectedDayOfMonth) { + int expectedYear, int expectedMonth, int expectedDayOfMonth) { cal.set(DAY_OF_WEEK, dayOfWeek); cal.getTime(); if (!cal.checkInternalDate(expectedYear, expectedMonth, expectedDayOfMonth, dayOfWeek)) { diff --git a/jdk/test/java/util/Calendar/GregorianCutoverTest.java b/jdk/test/java/util/Calendar/GregorianCutoverTest.java index bd743ae19f6..a9b840a95b1 100644 --- a/jdk/test/java/util/Calendar/GregorianCutoverTest.java +++ b/jdk/test/java/util/Calendar/GregorianCutoverTest.java @@ -76,7 +76,9 @@ public class GregorianCutoverTest extends IntlTest { checkContinuity(cal, WEEK_OF_YEAR); // Use large date (year >= 50000) - cal.setGregorianChange(new Date(50000-1900, JANUARY, 20)); + @SuppressWarnings("deprecation") + Date d = new Date(50000 - 1900, JANUARY, 20); + cal.setGregorianChange(d); cal.set(49998, JANUARY, 1); checkContinuity(cal, DAY_OF_YEAR); checkContinuity(cal, WEEK_OF_YEAR); @@ -124,7 +126,9 @@ public class GregorianCutoverTest extends IntlTest { // should handle the gap between 1969/12/22 (Julian) to 1970/1/5 (Gregorian) logln("Cutover date is 1970/1/5"); - cal.setGregorianChange(new Date(1970-1900, JANUARY, 5)); + @SuppressWarnings("deprecation") + Date d1 = new Date(1970 - 1900, JANUARY, 5); + cal.setGregorianChange(d1); cal.set(ERA, AD); cal.set(YEAR, 1970); logln(" Set DAY_OF_YEAR to the 28th day of 1970"); @@ -203,16 +207,17 @@ public class GregorianCutoverTest extends IntlTest { public void Test4928615() { Koyomi cal = new Koyomi(); logln("Today is 2003/10/1 Gregorian."); - Date x = new Date(2003-1900, 10-1, 1); + @SuppressWarnings("deprecation") + Date x = new Date(2003 - 1900, 10 - 1, 1); cal.setTime(x); logln(" Changing the cutover date to yesterday..."); - cal.setGregorianChange(new Date(x.getTime() - (24*3600*1000))); + cal.setGregorianChange(new Date(x.getTime() - (24 * 3600 * 1000))); if (!cal.checkDate(2003, OCTOBER, 1)) { errln(" " + cal.getMessage()); } logln(" Changing the cutover date to tomorrow..."); - cal.setGregorianChange(new Date(x.getTime() + (24*3600*1000))); + cal.setGregorianChange(new Date(x.getTime() + (24 * 3600 * 1000))); if (!cal.checkDate(2003, SEPTEMBER, 18)) { errln(" " + cal.getMessage()); } @@ -225,11 +230,11 @@ public class GregorianCutoverTest extends IntlTest { Koyomi cal = new Koyomi(); Koyomi cal2 = (Koyomi) cal.clone(); logln("getLeastMaximum should handle cutover year.\n" - +" default cutover date"); - if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365-10)) { + + " default cutover date"); + if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365 - 10)) { errln(" " + cal.getMessage()); } - if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52-((10+6)/7))) { + if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52 - ((10 + 6) / 7))) { errln(" " + cal.getMessage()); } // Corrected for 4956232 @@ -261,7 +266,9 @@ public class GregorianCutoverTest extends IntlTest { cal = new Koyomi(); logln("Change the cutover date to 1970/1/5."); - cal.setGregorianChange(new Date(1970-1900, 0, 5)); + @SuppressWarnings("deprecation") + Date d = new Date(1970 - 1900, 0, 5); + cal.setGregorianChange(d); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 356)) { errln(" " + cal.getMessage()); } @@ -287,15 +294,15 @@ public class GregorianCutoverTest extends IntlTest { int hour = 13865672; Koyomi gc1 = new Koyomi(); gc1.clear(); - gc1.set(1, gc1.JANUARY, 1, 0, 0, 0); - gc1.set(gc1.HOUR_OF_DAY, hour); - if (!gc1.checkDate(1582, gc1.OCTOBER, 4)) { + gc1.set(1, JANUARY, 1, 0, 0, 0); + gc1.set(HOUR_OF_DAY, hour); + if (!gc1.checkDate(1582, OCTOBER, 4)) { errln("test case 1: " + gc1.getMessage()); } gc1.clear(); - gc1.set(1, gc1.JANUARY, 1, 0, 0, 0); - gc1.set(gc1.HOUR_OF_DAY, hour + 24); - if (!gc1.checkDate(1582, gc1.OCTOBER, 15)) { + gc1.set(1, JANUARY, 1, 0, 0, 0); + gc1.set(HOUR_OF_DAY, hour + 24); + if (!gc1.checkDate(1582, OCTOBER, 15)) { errln("test case 2: " + gc1.getMessage()); } } diff --git a/jdk/test/java/util/Calendar/JavatimeTest.java b/jdk/test/java/util/Calendar/JavatimeTest.java index 7af6e9d4c03..8f32801a307 100644 --- a/jdk/test/java/util/Calendar/JavatimeTest.java +++ b/jdk/test/java/util/Calendar/JavatimeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,16 +28,16 @@ * @key randomness */ -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Random; -import java.util.TimeZone; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.ZoneId; import java.time.ZoneOffset; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Random; +import java.util.TimeZone; public class JavatimeTest { @@ -46,10 +46,11 @@ public class JavatimeTest { public static void main(String[] args) throws Throwable { int N = 10000; + @SuppressWarnings("deprecation") long t1970 = new java.util.Date(70, 0, 01).getTime(); Random r = new Random(); for (int i = 0; i < N; i++) { - int days = r.nextInt(50) * 365 + r.nextInt(365); + int days = r.nextInt(50) * 365 + r.nextInt(365); long secs = t1970 + days * 86400 + r.nextInt(86400); int nanos = r.nextInt(NANOS_PER_SECOND); int nanos_ms = nanos / 1000000 * 1000000; // millis precision @@ -61,15 +62,15 @@ public class JavatimeTest { ///////////// java.util.Date ///////////////////////// Date jud = new java.util.Date(millis); Instant inst0 = jud.toInstant(); - if (jud.getTime() != inst0.toEpochMilli() || - !jud.equals(Date.from(inst0))) { + if (jud.getTime() != inst0.toEpochMilli() + || !jud.equals(Date.from(inst0))) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d"); } // roundtrip only with millis precision Date jud0 = Date.from(inst_ms); - if (jud0.getTime() != inst_ms.toEpochMilli() || - !inst_ms.equals(jud0.toInstant())) { + if (jud0.getTime() != inst_ms.toEpochMilli() + || !inst_ms.equals(jud0.toInstant())) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: instant -> j.u.d -> instant"); } @@ -82,8 +83,8 @@ public class JavatimeTest { cal.setMinimalDaysInFirstWeek(4); cal.setTimeInMillis(millis); ZonedDateTime zdt0 = cal.toZonedDateTime(); - if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() || - !cal.equals(GregorianCalendar.from(zdt0))) { + if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() + || !cal.equals(GregorianCalendar.from(zdt0))) { System.out.println("cal:" + cal); System.out.println("zdt:" + zdt0); System.out.println("calNew:" + GregorianCalendar.from(zdt0)); @@ -97,8 +98,8 @@ public class JavatimeTest { } ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault()); GregorianCalendar cal0 = GregorianCalendar.from(zdt); - if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() || - !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) { + if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() + || !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: zdt -> gcal -> zdt"); } @@ -107,12 +108,12 @@ public class JavatimeTest { ///////////// java.util.TimeZone ///////////////////////// for (String zidStr : TimeZone.getAvailableIDs()) { // TBD: tzdt intergration - if (zidStr.startsWith("SystemV") || - zidStr.contains("Riyadh8") || - zidStr.equals("US/Pacific-New") || - zidStr.equals("EST") || - zidStr.equals("HST") || - zidStr.equals("MST")) { + if (zidStr.startsWith("SystemV") + || zidStr.contains("Riyadh8") + || zidStr.equals("US/Pacific-New") + || zidStr.equals("EST") + || zidStr.equals("HST") + || zidStr.equals("MST")) { continue; } ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS); @@ -121,9 +122,9 @@ public class JavatimeTest { } TimeZone tz = TimeZone.getTimeZone(zidStr); // no round-trip for alias and "GMT" - if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) && - !ZoneId.SHORT_IDS.containsKey(zidStr) && - !zidStr.startsWith("GMT")) { + if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) + && !ZoneId.SHORT_IDS.containsKey(zidStr) + && !zidStr.startsWith("GMT")) { throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr); } } diff --git a/jdk/test/java/util/Calendar/Koyomi.java b/jdk/test/java/util/Calendar/Koyomi.java index 8eec03b5de4..90f2eda0867 100644 --- a/jdk/test/java/util/Calendar/Koyomi.java +++ b/jdk/test/java/util/Calendar/Koyomi.java @@ -21,8 +21,6 @@ * questions. */ -import static java.util.Calendar.*; - import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; @@ -30,7 +28,9 @@ import java.util.TimeZone; /** * GregorianCalendar subclass for testing. */ +@SuppressWarnings("serial") public class Koyomi extends GregorianCalendar { + static final String[] FIELD_NAMES = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", @@ -78,7 +78,7 @@ public class Koyomi extends GregorianCalendar { StringBuilder sb = new StringBuilder(); sb.append(internalGet(ERA) == 0 ? "BCE " : ""); sb.append(internalGet(YEAR)).append('-'); - sb.append(internalGet(MONTH)+1).append('-'); + sb.append(internalGet(MONTH) + 1).append('-'); sb.append(internalGet(DAY_OF_MONTH)); return sb.toString(); } @@ -98,7 +98,7 @@ public class Koyomi extends GregorianCalendar { sb.append(ms); int offset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); offset /= 60000; - offset = (offset/60) * 100 + (offset%60); + offset = (offset / 60) * 100 + (offset % 60); if (offset >= 0) { sb.append('+'); } else { @@ -187,8 +187,8 @@ public class Koyomi extends GregorianCalendar { boolean checkActualMaximum(int field, int expectedValue) { int val; if ((val = getActualMaximum(field)) != expectedValue) { - appendMessage("getActualMaximum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getActualMaximum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -196,8 +196,8 @@ public class Koyomi extends GregorianCalendar { boolean checkLeastMaximum(int field, int expectedValue) { int val; if ((val = getLeastMaximum(field)) != expectedValue) { - appendMessage("getLeastMaximum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getLeastMaximum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -205,8 +205,8 @@ public class Koyomi extends GregorianCalendar { boolean checkActualMinimum(int field, int expectedValue) { int val; if ((val = getActualMinimum(field)) != expectedValue) { - appendMessage("getActualMinimum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getActualMinimum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -214,8 +214,8 @@ public class Koyomi extends GregorianCalendar { boolean checkGreatestMinimum(int field, int expectedValue) { int val; if ((val = getGreatestMinimum(field)) != expectedValue) { - appendMessage("getGreatestMinimum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getGreatestMinimum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -238,7 +238,7 @@ public class Koyomi extends GregorianCalendar { } boolean checkDateTime(int year, int month, int dayOfMonth, - int hourOfDay, int minute, int second, int ms) { + int hourOfDay, int minute, int second, int ms) { initTest(); checkFieldValue(YEAR, year); checkFieldValue(MONTH, month); @@ -270,8 +270,8 @@ public class Koyomi extends GregorianCalendar { boolean checkFieldValue(int field, int expectedValue) { int val; if ((val = get(field)) != expectedValue) { - appendMessage("get(" + FIELD_NAMES[field] + "): got " + val + - ", expected " + expectedValue + "; "); + appendMessage("get(" + FIELD_NAMES[field] + "): got " + val + + ", expected " + expectedValue + "; "); return false; } return true; @@ -280,8 +280,8 @@ public class Koyomi extends GregorianCalendar { boolean checkInternalFieldValue(int field, int expectedValue) { int val; if ((val = internalGet(field)) != expectedValue) { - appendMessage("internalGet(" + FIELD_NAMES[field] + "): got " + val + - ", expected " + expectedValue + "; "); + appendMessage("internalGet(" + FIELD_NAMES[field] + "): got " + val + + ", expected " + expectedValue + "; "); return false; } return true; diff --git a/jdk/test/java/util/Calendar/NonLenientTest.java b/jdk/test/java/util/Calendar/NonLenientTest.java index 6c42c594932..357cf0e95c0 100644 --- a/jdk/test/java/util/Calendar/NonLenientTest.java +++ b/jdk/test/java/util/Calendar/NonLenientTest.java @@ -28,7 +28,10 @@ * @library /java/text/testlib */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; import static java.util.Calendar.*; @@ -129,7 +132,6 @@ public class NonLenientTest extends IntlTest { validate(cal, "6th Sunday in Jan 2003"); } - /** * 4726030: GregorianCalendar doesn't check invalid dates in non-lenient */ @@ -146,34 +148,34 @@ public class NonLenientTest extends IntlTest { */ public void Test4147269() { Koyomi calendar = getNonLenient(); - Date date = (new GregorianCalendar(1996,0,3)).getTime(); + Date date = (new GregorianCalendar(1996, 0, 3)).getTime(); - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); int max = calendar.getActualMaximum(field); - int value = max+1; + int value = max + 1; calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + calendar.getFieldName(field) - + "\n\tdate before: " + date - + "\n\tdate after: " + calendar.getTime() - + "\n\tvalue: " + value + " (max = " + max +")"); + errln("Test failed with field " + Koyomi.getFieldName(field) + + "\n\tdate before: " + date + + "\n\tdate after: " + calendar.getTime() + + "\n\tvalue: " + value + " (max = " + max + ")"); } catch (IllegalArgumentException e) { } } - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); int min = calendar.getActualMinimum(field); - int value = min-1; + int value = min - 1; calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + calendar.getFieldName(field) - + "\n\tdate before: " + date - + "\n\tdate after: " + calendar.getTime() - + "\n\tvalue: " + value + " (min = " + min +")"); + errln("Test failed with field " + Koyomi.getFieldName(field) + + "\n\tdate before: " + date + + "\n\tdate after: " + calendar.getTime() + + "\n\tvalue: " + value + " (min = " + min + ")"); } catch (IllegalArgumentException e) { } } @@ -194,17 +196,17 @@ public class NonLenientTest extends IntlTest { // In non-lenient, calendar field values that have beeb set by // user shouldn't be modified. int[] afterFields = cal.getFields(); - for (int i = 0; i < Calendar.FIELD_COUNT; i++) { + for (int i = 0; i < FIELD_COUNT; i++) { if (cal.isSet(i) && originalFields[i] != afterFields[i]) { - errln(" complete() modified fields[" + cal.getFieldName(i) + "] got " - + afterFields[i] + ", expected " + originalFields[i]); + errln(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + + afterFields[i] + ", expected " + originalFields[i]); } } // In non-lenient, set state of fields shouldn't be modified. int afterSetFields = cal.getSetStateFields(); if (setFields != afterSetFields) { errln(" complate() modified set states: before 0x" + toHex(setFields) - + ", after 0x"+ toHex(afterSetFields)); + + ", after 0x" + toHex(afterSetFields)); } } diff --git a/jdk/test/java/util/Calendar/ZoneOffsets.java b/jdk/test/java/util/Calendar/ZoneOffsets.java index 147df337497..a0ddfde625c 100644 --- a/jdk/test/java/util/Calendar/ZoneOffsets.java +++ b/jdk/test/java/util/Calendar/ZoneOffsets.java @@ -28,12 +28,20 @@ * taken into account for time calculations. */ -import java.util.*; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + import static java.util.GregorianCalendar.*; public class ZoneOffsets { + // This TimeZone always returns the dstOffset value. + @SuppressWarnings("serial") private static class TestTimeZone extends TimeZone { + private int gmtOffset; private int dstOffset; @@ -44,7 +52,7 @@ public class ZoneOffsets { } public int getOffset(int era, int year, int month, int day, - int dayOfWeek, int milliseconds) { + int dayOfWeek, int milliseconds) { return gmtOffset + dstOffset; } @@ -80,22 +88,20 @@ public class ZoneOffsets { private static Locale[] locales = { Locale.getDefault(), new Locale("th", "TH"), - new Locale("ja", "JP", "JP"), - }; + new Locale("ja", "JP", "JP")}; private static final int HOUR = 60 * 60 * 1000; private static int[][] offsets = { - { 0, 0 }, - { 0, HOUR }, - { 0, 2 * HOUR }, - { -8 * HOUR, 0 }, - { -8 * HOUR, HOUR }, - { -8 * HOUR, 2 * HOUR }, - { 9 * HOUR, 0 }, - { 9 * HOUR, HOUR }, - { 9 * HOUR, 2 * HOUR }, - }; + {0, 0}, + {0, HOUR}, + {0, 2 * HOUR}, + {-8 * HOUR, 0}, + {-8 * HOUR, HOUR}, + {-8 * HOUR, 2 * HOUR}, + {9 * HOUR, 0}, + {9 * HOUR, HOUR}, + {9 * HOUR, 2 * HOUR}}; public static void main(String[] args) { for (int l = 0; l < locales.length; l++) { @@ -121,17 +127,17 @@ public class ZoneOffsets { private static void test(Locale loc, int gmtOffset, int dstOffset) { TimeZone tz1 = new TestTimeZone(gmtOffset, - "GMT" + (gmtOffset/HOUR) + "." + (dstOffset/HOUR), - dstOffset); + "GMT" + (gmtOffset / HOUR) + "." + (dstOffset / HOUR), + dstOffset); int someDifferentOffset = gmtOffset + 2 * HOUR; TimeZone tz2 = new TestTimeZone(someDifferentOffset, - "GMT"+ (someDifferentOffset/HOUR) + "." + (dstOffset/HOUR), - dstOffset); + "GMT" + (someDifferentOffset / HOUR) + "." + (dstOffset / HOUR), + dstOffset); int someDifferentDSTOffset = dstOffset == 2 * HOUR ? HOUR : dstOffset + HOUR; TimeZone tz3 = new TestTimeZone(gmtOffset, - "GMT"+ (gmtOffset/HOUR) + "." + (someDifferentDSTOffset/HOUR), - someDifferentDSTOffset); + "GMT" + (gmtOffset / HOUR) + "." + (someDifferentDSTOffset / HOUR), + someDifferentDSTOffset); // cal1 is the base line. Calendar cal1 = Calendar.getInstance(tz1, loc); @@ -225,7 +231,7 @@ public class ZoneOffsets { private static void error(String msg, Locale loc, Calendar cal2, int gmtOffset, int dstOffset, long t1) { System.err.println(cal2); throw new RuntimeException(msg + ": Locale=" + loc - + ", gmtOffset=" + gmtOffset + ", dstOffset=" + dstOffset - + ", cal1 time=" + t1 + ", cal2 time=" + cal2.getTime().getTime()); + + ", gmtOffset=" + gmtOffset + ", dstOffset=" + dstOffset + + ", cal1 time=" + t1 + ", cal2 time=" + cal2.getTime().getTime()); } } diff --git a/jdk/test/java/util/Calendar/bug4372743.java b/jdk/test/java/util/Calendar/bug4372743.java index 1800ebc002a..6d380e523e2 100644 --- a/jdk/test/java/util/Calendar/bug4372743.java +++ b/jdk/test/java/util/Calendar/bug4372743.java @@ -28,9 +28,8 @@ * @library /java/text/testlib */ -import java.io.*; -import java.util.*; -import java.text.*; +import java.util.GregorianCalendar; +import java.util.TimeZone; import static java.util.GregorianCalendar.*; @@ -41,51 +40,50 @@ public class bug4372743 extends IntlTest { } private int[][] data = { - {AD, 2, MARCH}, - {AD, 2, FEBRUARY}, - {AD, 2, JANUARY}, - {AD, 1, DECEMBER}, - {AD, 1, NOVEMBER}, - {AD, 1, OCTOBER}, - {AD, 1, SEPTEMBER}, - {AD, 1, AUGUST}, - {AD, 1, JULY}, - {AD, 1, JUNE}, - {AD, 1, MAY}, - {AD, 1, APRIL}, - {AD, 1, MARCH}, - {AD, 1, FEBRUARY}, - {AD, 1, JANUARY}, - {BC, 1, DECEMBER}, - {BC, 1, NOVEMBER}, - {BC, 1, OCTOBER}, - {BC, 1, SEPTEMBER}, - {BC, 1, AUGUST}, - {BC, 1, JULY}, - {BC, 1, JUNE}, - {BC, 1, MAY}, - {BC, 1, APRIL}, - {BC, 1, MARCH}, - {BC, 1, FEBRUARY}, - {BC, 1, JANUARY}, - {BC, 2, DECEMBER}, - {BC, 2, NOVEMBER}, - {BC, 2, OCTOBER}, - }; + {AD, 2, MARCH}, + {AD, 2, FEBRUARY}, + {AD, 2, JANUARY}, + {AD, 1, DECEMBER}, + {AD, 1, NOVEMBER}, + {AD, 1, OCTOBER}, + {AD, 1, SEPTEMBER}, + {AD, 1, AUGUST}, + {AD, 1, JULY}, + {AD, 1, JUNE}, + {AD, 1, MAY}, + {AD, 1, APRIL}, + {AD, 1, MARCH}, + {AD, 1, FEBRUARY}, + {AD, 1, JANUARY}, + {BC, 1, DECEMBER}, + {BC, 1, NOVEMBER}, + {BC, 1, OCTOBER}, + {BC, 1, SEPTEMBER}, + {BC, 1, AUGUST}, + {BC, 1, JULY}, + {BC, 1, JUNE}, + {BC, 1, MAY}, + {BC, 1, APRIL}, + {BC, 1, MARCH}, + {BC, 1, FEBRUARY}, + {BC, 1, JANUARY}, + {BC, 2, DECEMBER}, + {BC, 2, NOVEMBER}, + {BC, 2, OCTOBER}}; private int tablesize = data.length; private void check(GregorianCalendar gc, int index) { if (gc.get(ERA) != data[index][ERA]) { - errln("Invalid era :" + gc.get(ERA) + - ", expected :" + data[index][ERA]); + errln("Invalid era :" + gc.get(ERA) + + ", expected :" + data[index][ERA]); } if (gc.get(YEAR) != data[index][YEAR]) { - errln("Invalid year :" + gc.get(YEAR) + - ", expected :" + data[index][YEAR]); + errln("Invalid year :" + gc.get(YEAR) + + ", expected :" + data[index][YEAR]); } if (gc.get(MONTH) != data[index][MONTH]) { - errln("Invalid month :" + gc.get(MONTH) + - ", expected :" + data[index][MONTH]); + errln("Invalid month :" + gc.get(MONTH) + + ", expected :" + data[index][MONTH]); } } @@ -97,36 +95,35 @@ public class bug4372743 extends IntlTest { TimeZone.setDefault(TimeZone.getTimeZone("PST")); /* Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); + gc = new GregorianCalendar(2, MARCH, 3); for (int i = 0; i < tablesize; i++) { check(gc, i); - gc.add(gc.MONTH, -1); + gc.add(MONTH, -1); } /* Again, Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i+=7) { + gc = new GregorianCalendar(2, MARCH, 3); + for (int i = 0; i < tablesize; i += 7) { check(gc, i); - gc.add(gc.MONTH, -7); + gc.add(MONTH, -7); } /* Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(gc.YEAR, -3); - for (int i = tablesize -1; i >= 0; i--) { + gc = new GregorianCalendar(2, OCTOBER, 10); + gc.add(YEAR, -3); + for (int i = tablesize - 1; i >= 0; i--) { check(gc, i); - gc.add(gc.MONTH, 1); + gc.add(MONTH, 1); } /* Again, Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(gc.YEAR, -3); - for (int i = tablesize -1; i >= 0; i-=8) { + gc = new GregorianCalendar(2, OCTOBER, 10); + gc.add(YEAR, -3); + for (int i = tablesize - 1; i >= 0; i -= 8) { check(gc, i); - gc.add(gc.MONTH, 8); + gc.add(MONTH, 8); } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } diff --git a/jdk/test/java/util/Calendar/bug4401223.java b/jdk/test/java/util/Calendar/bug4401223.java index fbd9e29a8f6..3123181e1a1 100644 --- a/jdk/test/java/util/Calendar/bug4401223.java +++ b/jdk/test/java/util/Calendar/bug4401223.java @@ -28,7 +28,10 @@ * @library /java/text/testlib */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; + +import static java.util.GregorianCalendar.*; public class bug4401223 extends IntlTest { @@ -37,11 +40,12 @@ public class bug4401223 extends IntlTest { String s = null; try { - Date date = new Date(2000-1900, Calendar.FEBRUARY, 29); + @SuppressWarnings("deprecation") + Date date = new Date(2000 - 1900, FEBRUARY, 29); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.setLenient(false); - gc.set(Calendar.YEAR, 2001); + gc.set(YEAR, 2001); s = "02/29/00 & set(YEAR,2001) = " + gc.getTime().toString(); } catch (Exception ex) { status++; @@ -59,16 +63,17 @@ public class bug4401223 extends IntlTest { String s = null; try { - Date date = new Date(2000-1900, Calendar.DECEMBER, 31); + @SuppressWarnings("deprecation") + Date date = new Date(2000 - 1900, DECEMBER, 31); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.setLenient(false); - gc.set(Calendar.YEAR, 2001); + gc.set(YEAR, 2001); - if (gc.get(Calendar.YEAR) != 2001 || - gc.get(Calendar.MONTH) != Calendar.DECEMBER || - gc.get(Calendar.DATE) != 31 || - gc.get(Calendar.DAY_OF_YEAR) != 365) { + if (gc.get(YEAR) != 2001 + || gc.get(MONTH) != DECEMBER + || gc.get(DATE) != 31 + || gc.get(DAY_OF_YEAR) != 365) { status++; s = "Wrong Date : 12/31/00 & set(YEAR,2001) ---> " + gc.getTime().toString(); } else { diff --git a/jdk/test/java/util/Calendar/bug4514831.java b/jdk/test/java/util/Calendar/bug4514831.java index 9d635e26167..f0c34a8aa2a 100644 --- a/jdk/test/java/util/Calendar/bug4514831.java +++ b/jdk/test/java/util/Calendar/bug4514831.java @@ -27,7 +27,12 @@ * @summary Confirm that GregorianCalendar.roll() works properly during transition from Daylight Saving Time to Standard Time. */ -import java.util.*; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import static java.util.GregorianCalendar.*; + public class bug4514831 { @@ -36,52 +41,52 @@ public class bug4514831 { TimeZone savedTimeZone = TimeZone.getDefault(); boolean err = false; - String golden_data1 ="27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; - String golden_data2 ="27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; - String golden_data3 ="1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; + String golden_data1 = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; + String golden_data2 = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; + String golden_data3 = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); String test_roll = ""; - GregorianCalendar c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 27); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_YEAR, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + GregorianCalendar c_roll = new GregorianCalendar(2001, OCTOBER, 27); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_YEAR, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data1)) { err = true; - System.err.println("Wrong roll(DAY_OF_YEAR) transition: got "+ - test_roll + "expected " + golden_data1); + System.err.println("Wrong roll(DAY_OF_YEAR) transition: got " + + test_roll + "expected " + golden_data1); } test_roll = ""; - c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 27); - c_roll.setFirstDayOfWeek(Calendar.THURSDAY); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_WEEK, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + c_roll = new GregorianCalendar(2001, OCTOBER, 27); + c_roll.setFirstDayOfWeek(THURSDAY); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_WEEK, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data2)) { err = true; - System.err.println("Wrong roll(DAY_OF_WEEK) transition: got "+ - test_roll + "expected " + golden_data2); + System.err.println("Wrong roll(DAY_OF_WEEK) transition: got " + + test_roll + "expected " + golden_data2); } test_roll = ""; - c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 1); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_WEEK_IN_MONTH, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + c_roll = new GregorianCalendar(2001, OCTOBER, 1); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_WEEK_IN_MONTH, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data3)) { err = true; - System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got "+ - test_roll + "expected " + golden_data3); + System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got " + + test_roll + "expected " + golden_data3); } } finally { Locale.setDefault(savedLocale); diff --git a/jdk/test/java/util/Date/Bug4955000.java b/jdk/test/java/util/Date/Bug4955000.java index c94b23868ca..4339f848f58 100644 --- a/jdk/test/java/util/Date/Bug4955000.java +++ b/jdk/test/java/util/Date/Bug4955000.java @@ -28,11 +28,15 @@ * same date/time. Both are new implementations in 1.5. */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + import static java.util.GregorianCalendar.*; @SuppressWarnings("deprecation") public class Bug4955000 { + // Tests for Date.UTC(), derived from JCK // Date.miscTests.Date1025 and Date2015 public static void main(String[] args) { @@ -51,17 +55,17 @@ public class Bug4955000 { }; for (int i = 0; i < years1.length; i++) { gc.clear(); - gc.set(years1[i], gc.JANUARY, 1); + gc.set(years1[i], JANUARY, 1); long t = gc.getTimeInMillis(); - long utc = Date.UTC(years1[i] - 1900, 1-1, 1, - 0, 0, 0); // Jan 1 00:00:00 + long utc = Date.UTC(years1[i] - 1900, 1 - 1, 1, + 0, 0, 0); // Jan 1 00:00:00 if (t != utc) { - throw new RuntimeException("t (" + t + ") != utc (" + utc +")"); + throw new RuntimeException("t (" + t + ") != utc (" + utc + ")"); } } // Date2015 - int years[] = { + int[] years = { gc.getGreatestMinimum(YEAR), gc.getGreatestMinimum(YEAR) + 1, -1, @@ -71,47 +75,47 @@ public class Bug4955000 { gc.getLeastMaximum(YEAR) }; - int months[] = { + int[] months = { gc.getMinimum(MONTH), gc.getMinimum(MONTH) + 1, gc.getMaximum(MONTH) - 1, gc.getMaximum(MONTH) }; - int dates[] = { + int[] dates = { gc.getMinimum(DAY_OF_MONTH), gc.getMinimum(DAY_OF_MONTH) + 1, gc.getMaximum(DAY_OF_MONTH) - 1, gc.getMaximum(DAY_OF_MONTH) }; - int hs[] = { + int[] hs = { gc.getMinimum(HOUR), gc.getMinimum(HOUR) + 1, gc.getMaximum(HOUR) - 1, gc.getMaximum(HOUR) }; - int ms[] = { + int[] ms = { gc.getMinimum(MINUTE), gc.getMinimum(MINUTE) + 1, gc.getMaximum(MINUTE) - 1, gc.getMaximum(MINUTE) }; - int ss[] = { + int[] ss = { gc.getMinimum(SECOND), gc.getMinimum(SECOND) + 1, gc.getMaximum(SECOND) - 1, gc.getMaximum(SECOND) }; - for(int i = 0; i < years.length; i++) { - for(int j = 0; j < months.length; j++) { - for(int k = 0; k < dates.length; k++) { - for(int m = 0; m < hs.length; m++) { - for(int n = 0; n < ms.length; n++) { - for(int p = 0; p < ss.length; p++) { + for (int i = 0; i < years.length; i++) { + for (int j = 0; j < months.length; j++) { + for (int k = 0; k < dates.length; k++) { + for (int m = 0; m < hs.length; m++) { + for (int n = 0; n < ms.length; n++) { + for (int p = 0; p < ss.length; p++) { int year = years[i] - 1900; int month = months[j]; int date = dates[k]; @@ -120,7 +124,7 @@ public class Bug4955000 { int seconds = ss[p]; long result = Date.UTC(year, month, date, - hours, minutes, seconds); + hours, minutes, seconds); gc.clear(); gc.set(year + 1900, month, date, hours, minutes, seconds); @@ -129,7 +133,7 @@ public class Bug4955000 { if (expected != result) { throw new RuntimeException("expected (" + expected - + ") != result (" + result +")"); + + ") != result (" + result + ")"); } } } diff --git a/jdk/test/java/util/Locale/Bug4175998Test.java b/jdk/test/java/util/Locale/Bug4175998Test.java index e890ae9e667..a5ad1dd3abd 100644 --- a/jdk/test/java/util/Locale/Bug4175998Test.java +++ b/jdk/test/java/util/Locale/Bug4175998Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary test ISO639-2 language codes + * @library /java/text/testlib * @compile -encoding ascii Bug4175998Test.java * @run main Bug4175998Test * @bug 4175998 @@ -43,14 +44,13 @@ */ import java.util.*; -import java.io.*; /** * Bug4175998Test verifies that the following bug has been fixed: * Bug 4175998 - The java.util.Locale.getISO3Language() returns wrong result for a locale with * language code 'ta'(Tamil). */ -public class Bug4175998Test extends LocaleTestFmwk { +public class Bug4175998Test extends IntlTest { public static void main(String[] args) throws Exception { new Bug4175998Test().run(args); //generateTables(); //uncomment this to regenerate data tables diff --git a/jdk/test/java/util/Locale/Bug4184873Test.java b/jdk/test/java/util/Locale/Bug4184873Test.java index 478a67fbf8b..3dadf1fe3a9 100644 --- a/jdk/test/java/util/Locale/Bug4184873Test.java +++ b/jdk/test/java/util/Locale/Bug4184873Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ /* @test @summary test that locale invariants are preserved across serialization + @library /java/text/testlib @run main Bug4184873Test @bug 4184873 */ @@ -63,7 +64,7 @@ import java.io.*; /** * A Locale can never contain the following language codes: he, yi or id. */ -public class Bug4184873Test extends LocaleTestFmwk { +public class Bug4184873Test extends IntlTest { public static void main(String[] args) throws Exception { if (args.length == 1 && args[0].equals("prepTest")) { prepTest(); diff --git a/jdk/test/java/util/Locale/Bug8001562.java b/jdk/test/java/util/Locale/Bug8001562.java index 1a18ac58a97..be53600a84d 100644 --- a/jdk/test/java/util/Locale/Bug8001562.java +++ b/jdk/test/java/util/Locale/Bug8001562.java @@ -30,37 +30,46 @@ * @run main Bug8001562 */ -import java.text.*; -import java.util.*; +import java.text.BreakIterator; +import java.text.Collator; +import java.text.DateFormat; +import java.text.DateFormatSymbols; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; public class Bug8001562 { - static final String[] jdk7availTags = { - "ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", - "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SD", "ar-SY", - "ar-TN", "ar-YE", "be", "be-BY", "bg", "bg-BG", "ca", "ca-ES", "cs", - "cs-CZ", "da", "da-DK", "de", "de-AT", "de-CH", "de-DE", "de-LU", "el", - "el-CY", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", - "en-MT", "en-NZ", "en-PH", "en-SG", "en-US", "en-ZA", "es", "es-AR", - "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", - "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", - "es-US", "es-UY", "es-VE", "et", "et-EE", "fi", "fi-FI", "fr", "fr-BE", - "fr-CA", "fr-CH", "fr-FR", "fr-LU", "ga", "ga-IE", "he", "he-IL", - "hi-IN", "hr", "hr-HR", "hu", "hu-HU", "id", "id-ID", "is", "is-IS", - "it", "it-CH", "it-IT", "ja", "ja-JP", - "ja-JP-u-ca-japanese-x-lvariant-JP", "ko", "ko-KR", "lt", "lt-LT", "lv", - "lv-LV", "mk", "mk-MK", "ms", "ms-MY", "mt", "mt-MT", "nl", "nl-BE", - "nl-NL", "no", "no-NO", "no-NO-x-lvariant-NY", "pl", "pl-PL", "pt", - "pt-BR", "pt-PT", "ro", "ro-RO", "ru", "ru-RU", "sk", "sk-SK", "sl", - "sl-SI", "sq", "sq-AL", "sr", "sr-BA", "sr-CS", "sr-Latn", "sr-Latn-BA", - "sr-Latn-ME", "sr-Latn-RS", "sr-ME", "sr-RS", "sv", "sv-SE", "th", - "th-TH", "th-TH-u-nu-thai-x-lvariant-TH", "tr", "tr-TR", "uk", "uk-UA", - "vi", "vi-VN", "zh", "zh-CN", "zh-HK", "zh-SG", "zh-TW", }; - static List jdk7availLocs = new ArrayList<>(); + static final List jdk7availTags = List.of( + "ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", + "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SD", "ar-SY", + "ar-TN", "ar-YE", "be", "be-BY", "bg", "bg-BG", "ca", "ca-ES", "cs", + "cs-CZ", "da", "da-DK", "de", "de-AT", "de-CH", "de-DE", "de-LU", "el", + "el-CY", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", + "en-MT", "en-NZ", "en-PH", "en-SG", "en-US", "en-ZA", "es", "es-AR", + "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", + "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", + "es-US", "es-UY", "es-VE", "et", "et-EE", "fi", "fi-FI", "fr", "fr-BE", + "fr-CA", "fr-CH", "fr-FR", "fr-LU", "ga", "ga-IE", "he", "he-IL", + "hi-IN", "hr", "hr-HR", "hu", "hu-HU", "id", "id-ID", "is", "is-IS", + "it", "it-CH", "it-IT", "ja", "ja-JP", + "ja-JP-u-ca-japanese-x-lvariant-JP", "ko", "ko-KR", "lt", "lt-LT", "lv", + "lv-LV", "mk", "mk-MK", "ms", "ms-MY", "mt", "mt-MT", "nl", "nl-BE", + "nl-NL", "no", "no-NO", "no-NO-x-lvariant-NY", "pl", "pl-PL", "pt", + "pt-BR", "pt-PT", "ro", "ro-RO", "ru", "ru-RU", "sk", "sk-SK", "sl", + "sl-SI", "sq", "sq-AL", "sr", "sr-BA", "sr-CS", "sr-Latn", "sr-Latn-BA", + "sr-Latn-ME", "sr-Latn-RS", "sr-ME", "sr-RS", "sv", "sv-SE", "th", + "th-TH", "th-TH-u-nu-thai-x-lvariant-TH", "tr", "tr-TR", "uk", "uk-UA", + "vi", "vi-VN", "zh", "zh-CN", "zh-HK", "zh-SG", "zh-TW"); + static List jdk7availLocs; + static { - for (String locStr : jdk7availTags) { - jdk7availLocs.add(Locale.forLanguageTag(locStr)); - } + jdk7availLocs = jdk7availTags.stream() + .map(Locale::forLanguageTag) + .collect(Collectors.toList()); } public static void main(String[] args) { @@ -86,13 +95,13 @@ public class Bug8001562 { diffLocale(Locale.class, avail); } - static void diffLocale(Class c, List locs) { + static void diffLocale(Class c, List locs) { String diff = ""; System.out.printf("Only in target locales (%s.getAvailableLocales()): ", c.getSimpleName()); for (Locale l : locs) { if (!jdk7availLocs.contains(l)) { - diff += "\""+l.toLanguageTag()+"\", "; + diff += "\"" + l.toLanguageTag() + "\", "; } } System.out.println(diff); @@ -101,7 +110,7 @@ public class Bug8001562 { System.out.printf("Only in JDK7 (%s.getAvailableLocales()): ", c.getSimpleName()); for (Locale l : jdk7availLocs) { if (!locs.contains(l)) { - diff += "\""+l.toLanguageTag()+"\", "; + diff += "\"" + l.toLanguageTag() + "\", "; } } System.out.println(diff); diff --git a/jdk/test/java/util/Locale/HashCodeTest.java b/jdk/test/java/util/Locale/HashCodeTest.java index 8163ca03dc3..a911515274f 100644 --- a/jdk/test/java/util/Locale/HashCodeTest.java +++ b/jdk/test/java/util/Locale/HashCodeTest.java @@ -27,14 +27,17 @@ * @modules jdk.localedata */ -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; public class HashCodeTest { + public static void main(String[] args) { Locale[] locales = Locale.getAvailableLocales(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; - Map map = new HashMap(locales.length); + Map map = new HashMap<>(locales.length); int conflicts = 0; for (int i = 0; i < locales.length; i++) { @@ -42,19 +45,19 @@ public class HashCodeTest { int hc = loc.hashCode(); min = Math.min(hc, min); max = Math.max(hc, max); - Integer key = new Integer(hc); + Integer key = hc; if (map.containsKey(key)) { conflicts++; - System.out.println("conflict: " + (Locale) map.get(key) + ", " + loc); + System.out.println("conflict: " + map.get(key) + ", " + loc); } else { map.put(key, loc); } } - System.out.println(locales.length+" locales: conflicts="+conflicts - +", min="+min+", max="+max +", diff="+(max-min)); + System.out.println(locales.length + " locales: conflicts=" + conflicts + + ", min=" + min + ", max=" + max + ", diff=" + (max - min)); if (conflicts >= (locales.length / 10)) { throw new RuntimeException("too many conflicts: " + conflicts - + " per " + locales.length + " locales"); + + " per " + locales.length + " locales"); } } } diff --git a/jdk/test/java/util/Locale/LocaleEnhanceTest.java b/jdk/test/java/util/Locale/LocaleEnhanceTest.java index a4a2f1106fc..c30804d3a15 100644 --- a/jdk/test/java/util/Locale/LocaleEnhanceTest.java +++ b/jdk/test/java/util/Locale/LocaleEnhanceTest.java @@ -46,11 +46,12 @@ import java.util.Set; * @bug 6875847 6992272 7002320 7015500 7023613 7032820 7033504 7004603 * 7044019 8008577 * @summary test API changes to Locale + * @library /java/text/testlib * @modules jdk.localedata * @compile LocaleEnhanceTest.java * @run main/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest */ -public class LocaleEnhanceTest extends LocaleTestFmwk { +public class LocaleEnhanceTest extends IntlTest { public static void main(String[] args) throws Exception { List argList = new ArrayList(); diff --git a/jdk/test/java/util/Locale/LocaleTest.java b/jdk/test/java/util/Locale/LocaleTest.java index 90510ce2fda..33fd411863a 100644 --- a/jdk/test/java/util/Locale/LocaleTest.java +++ b/jdk/test/java/util/Locale/LocaleTest.java @@ -27,6 +27,7 @@ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 * @summary test Locales + * @library /java/text/testlib * @modules jdk.localedata * @run main/othervm -Djava.locale.providers=JRE,SPI LocaleTest */ @@ -63,16 +64,25 @@ * */ -import java.text.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OptionalDataException; +import java.io.StreamCorruptedException; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; -import java.util.Date; -import java.util.Calendar; -import java.io.*; -public class LocaleTest extends LocaleTestFmwk { +public class LocaleTest extends IntlTest { public LocaleTest() { } @@ -186,18 +196,22 @@ public class LocaleTest extends LocaleTestFmwk { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getLanguage().equals(dataTable[LANG][i])) + if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " - + dataTable[LANG][i]); - if (!testLocale.getCountry().equals(dataTable[CTRY][i])) + + dataTable[LANG][i]); + } + if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { errln(" Country code mismatch: " + testLocale.getCountry() + " versus " - + dataTable[CTRY][i]); - if (!testLocale.getVariant().equals(dataTable[VAR][i])) + + dataTable[CTRY][i]); + } + if (!testLocale.getVariant().equals(dataTable[VAR][i])) { errln(" Variant code mismatch: " + testLocale.getVariant() + " versus " - + dataTable[VAR][i]); - if (!testLocale.toString().equals(dataTable[NAME][i])) + + dataTable[VAR][i]); + } + if (!testLocale.toString().equals(dataTable[NAME][i])) { errln(" Locale name mismatch: " + testLocale.toString() + " versus " - + dataTable[NAME][i]); + + dataTable[NAME][i]); + } } logln("Same thing without variant codes..."); @@ -205,31 +219,37 @@ public class LocaleTest extends LocaleTestFmwk { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getLanguage().equals(dataTable[LANG][i])) + if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " - + dataTable[LANG][i]); - if (!testLocale.getCountry().equals(dataTable[CTRY][i])) + + dataTable[LANG][i]); + } + if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { errln(" Country code mismatch: " + testLocale.getCountry() + " versus " - + dataTable[CTRY][i]); - if (!testLocale.getVariant().equals("")) + + dataTable[CTRY][i]); + } + if (!testLocale.getVariant().equals("")) { errln(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); + } } } public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { - if (dataTable[LANG][i].equals("xx")) + if (dataTable[LANG][i].equals("xx")) { continue; + } Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) + if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) { errln(" ISO-3 language code mismatch: " + testLocale.getISO3Language() - + " versus " + dataTable[LANG3][i]); - if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) + + " versus " + dataTable[LANG3][i]); + } + if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) { errln(" ISO-3 country code mismatch: " + testLocale.getISO3Country() - + " versus " + dataTable[CTRY3][i]); + + " versus " + dataTable[CTRY3][i]); + } /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) @@ -246,11 +266,11 @@ public class LocaleTest extends LocaleTestFmwk { * @bug 4052440 Stop falling back to the default locale. */ public void TestDisplayNames() { - Locale saveDefault = Locale.getDefault(); - Locale english = new Locale("en", "US"); - Locale french = new Locale("fr", "FR"); - Locale croatian = new Locale("hr", "HR"); - Locale greek = new Locale("el", "GR"); + Locale saveDefault = Locale.getDefault(); + Locale english = new Locale("en", "US"); + Locale french = new Locale("fr", "FR"); + Locale croatian = new Locale("hr", "HR"); + Locale greek = new Locale("el", "GR"); Locale.setDefault(english); logln("With default = en_US..."); @@ -282,97 +302,116 @@ public class LocaleTest extends LocaleTestFmwk { } private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defaultIsFrench) { - if (defaultIsFrench && !Locale.getDefault().getLanguage().equals("fr")) - errln("Default locale should be French, but it's really " + Locale.getDefault().getLanguage()); - else if (!defaultIsFrench && !Locale.getDefault().getLanguage().equals("en")) - errln("Default locale should be English, but it's really " + Locale.getDefault().getLanguage()); + String language = Locale.getDefault().getLanguage(); + + if (defaultIsFrench && !language.equals("fr")) { + errln("Default locale should be French, but it's really " + language); + } else if (!defaultIsFrench && !language.equals("en")) { + errln("Default locale should be English, but it's really " + language); + } for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln(" Testing " + testLocale + "..."); - String testLang; - String testCtry; - String testVar; - String testName; + String testLang; + String testCtry; + String testVar; + String testName; if (inLocale == null) { testLang = testLocale.getDisplayLanguage(); testCtry = testLocale.getDisplayCountry(); testVar = testLocale.getDisplayVariant(); testName = testLocale.getDisplayName(); - } - else { + } else { testLang = testLocale.getDisplayLanguage(inLocale); testCtry = testLocale.getDisplayCountry(inLocale); testVar = testLocale.getDisplayVariant(inLocale); testName = testLocale.getDisplayName(inLocale); } - String expectedLang; - String expectedCtry; - String expectedVar; - String expectedName; + String expectedLang; + String expectedCtry; + String expectedVar; + String expectedName; expectedLang = dataTable[compareIndex][i]; - if (expectedLang.equals("") && defaultIsFrench) + if (expectedLang.equals("") && defaultIsFrench) { expectedLang = dataTable[DLANG_EN][i]; - if (expectedLang.equals("")) + } + if (expectedLang.equals("")) { expectedLang = dataTable[DLANG_ROOT][i]; + } expectedCtry = dataTable[compareIndex + 1][i]; - if (expectedCtry.equals("") && defaultIsFrench) + if (expectedCtry.equals("") && defaultIsFrench) { expectedCtry = dataTable[DCTRY_EN][i]; - if (expectedCtry.equals("")) + } + if (expectedCtry.equals("")) { expectedCtry = dataTable[DCTRY_ROOT][i]; + } expectedVar = dataTable[compareIndex + 2][i]; - if (expectedVar.equals("") && defaultIsFrench) + if (expectedVar.equals("") && defaultIsFrench) { expectedVar = dataTable[DVAR_EN][i]; - if (expectedVar.equals("")) + } + if (expectedVar.equals("")) { expectedVar = dataTable[DVAR_ROOT][i]; + } expectedName = dataTable[compareIndex + 3][i]; - if (expectedName.equals("") && defaultIsFrench) + if (expectedName.equals("") && defaultIsFrench) { expectedName = dataTable[DNAME_EN][i]; - if (expectedName.equals("")) + } + if (expectedName.equals("")) { expectedName = dataTable[DNAME_ROOT][i]; + } - if (!testLang.equals(expectedLang)) + if (!testLang.equals(expectedLang)) { errln("Display language mismatch: " + testLang + " versus " + expectedLang); - if (!testCtry.equals(expectedCtry)) + } + if (!testCtry.equals(expectedCtry)) { errln("Display country mismatch: " + testCtry + " versus " + expectedCtry); - if (!testVar.equals(expectedVar)) + } + if (!testVar.equals(expectedVar)) { errln("Display variant mismatch: " + testVar + " versus " + expectedVar); - if (!testName.equals(expectedName)) + } + if (!testName.equals(expectedName)) { errln("Display name mismatch: " + testName + " versus " + expectedName); + } } } public void TestSimpleObjectStuff() { - Locale test1 = new Locale("aa", "AA"); - Locale test2 = new Locale("aa", "AA"); - Locale test3 = (Locale)test1.clone(); - Locale test4 = new Locale("zz", "ZZ"); + Locale test1 = new Locale("aa", "AA"); + Locale test2 = new Locale("aa", "AA"); + Locale test3 = (Locale) test1.clone(); + Locale test4 = new Locale("zz", "ZZ"); - if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) + if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) { errln("Some of the test variables point to the same locale!"); + } - if (test3 == null) + if (test3 == null) { errln("clone() failed to produce a valid object!"); + } - if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) + if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) { errln("clone() or equals() failed: objects that should compare equal don't"); + } - if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) + if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) { errln("equals() failed: objects that shouldn't compare equal do"); + } int hash1 = test1.hashCode(); int hash2 = test2.hashCode(); int hash3 = test3.hashCode(); - if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) + if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) { errln("hashCode() failed: objects that should have the same hash code don't"); + } } /** @@ -385,22 +424,22 @@ public class LocaleTest extends LocaleTestFmwk { try { result = test.getISO3Language(); - } - catch (MissingResourceException e) { + } catch (MissingResourceException e) { gotException = true; } - if (!gotException) + if (!gotException) { errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); + } gotException = false; try { result = test.getISO3Country(); - } - catch (MissingResourceException e) { + } catch (MissingResourceException e) { gotException = true; } - if (!gotException) + if (!gotException) { errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); + } } /** @@ -416,53 +455,65 @@ public class LocaleTest extends LocaleTestFmwk { // all lower case for the language codes, all upper case for the country codes) // 4) Is each list in sorted order? String[] test = Locale.getISOLanguages(); - String[] spotCheck1 = { "en", "es", "fr", "de", "it", "ja", "ko", "zh", "th", - "he", "id", "iu", "ug", "yi", "za" }; + String[] spotCheck1 = {"en", "es", "fr", "de", "it", "ja", "ko", "zh", "th", + "he", "id", "iu", "ug", "yi", "za"}; - if (test.length != 188) + if (test.length != 188) { errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length); - else { + } else { for (int i = 0; i < spotCheck1.length; i++) { int j; - for (j = 0; j < test.length; j++) - if (test[j].equals(spotCheck1[i])) + for (j = 0; j < test.length; j++) { + if (test[j].equals(spotCheck1[i])) { break; - if (j == test.length || !test[j].equals(spotCheck1[i])) + } + } + if (j == test.length || !test[j].equals(spotCheck1[i])) { errln("Couldn't find " + spotCheck1[i] + " in language list."); + } } } for (int i = 0; i < test.length; i++) { - if (!test[i].equals(test[i].toLowerCase())) + if (!test[i].equals(test[i].toLowerCase())) { errln(test[i] + " is not all lower case."); - if (test[i].length() != 2) + } + if (test[i].length() != 2) { errln(test[i] + " is not two characters long."); - if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) + } + if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { errln(test[i] + " appears in an out-of-order position in the list."); + } } test = Locale.getISOCountries(); - String[] spotCheck2 = { "US", "CA", "GB", "FR", "DE", "IT", "JP", "KR", "CN", "TW", "TH" }; + String[] spotCheck2 = {"US", "CA", "GB", "FR", "DE", "IT", "JP", "KR", "CN", "TW", "TH"}; - if (test.length != 250) + if (test.length != 250) { errln("Expected getISOCountries to return 250 countries; it returned " + test.length); - else { + } else { for (int i = 0; i < spotCheck2.length; i++) { int j; - for (j = 0; j < test.length; j++) - if (test[j].equals(spotCheck2[i])) + for (j = 0; j < test.length; j++) { + if (test[j].equals(spotCheck2[i])) { break; - if (j == test.length || !test[j].equals(spotCheck2[i])) + } + } + if (j == test.length || !test[j].equals(spotCheck2[i])) { errln("Couldn't find " + spotCheck2[i] + " in country list."); + } } } for (int i = 0; i < test.length; i++) { - if (!test[i].equals(test[i].toUpperCase())) + if (!test[i].equals(test[i].toUpperCase())) { errln(test[i] + " is not all upper case."); - if (test[i].length() != 2) + } + if (test[i].length() != 2) { errln(test[i] + " is not two characters long."); - if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) + } + if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { errln(test[i] + " appears in an out-of-order position in the list."); + } } } @@ -475,14 +526,16 @@ public class LocaleTest extends LocaleTestFmwk { test = Locale.getISOCountries(); test[0] = "SUCKER!!!"; test = Locale.getISOCountries(); - if (test[0].equals("SUCKER!!!")) + if (test[0].equals("SUCKER!!!")) { errln("Changed internal country code list!"); + } test = Locale.getISOLanguages(); test[0] = "HAHAHAHA!!!"; test = Locale.getISOLanguages(); - if (test[0].equals("HAHAHAHA!!!")) // Fixed typo + if (test[0].equals("HAHAHAHA!!!")) { // Fixed typo errln("Changes internal language code list!"); + } } /** @@ -490,12 +543,13 @@ public class LocaleTest extends LocaleTestFmwk { */ public void TestGetAvailableLocales() { Locale[] locales = Locale.getAvailableLocales(); - if (locales == null || locales.length == 0) + if (locales == null || locales.length == 0) { errln("Locale.getAvailableLocales() returned no installed locales!"); - else { + } else { logln("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); - for (int i = 0; i < locales.length; i++) + for (int i = 0; i < locales.length; i++) { logln(locales[i].toString()); + } } } @@ -505,8 +559,9 @@ public class LocaleTest extends LocaleTestFmwk { public void TestBug4135316() { Locale[] locales1 = Locale.getAvailableLocales(); Locale[] locales2 = Locale.getAvailableLocales(); - if (locales1 == locales2) + if (locales1 == locales2) { errln("Locale.getAvailableLocales() doesn't clone its internal storage!"); + } } /** @@ -548,8 +603,7 @@ test commented out pending API-change approval * @bug 4110613 */ public void TestSerialization() throws ClassNotFoundException, OptionalDataException, - IOException, StreamCorruptedException - { + IOException, StreamCorruptedException { ObjectOutputStream ostream; ByteArrayOutputStream obstream; byte[] bytes = null; @@ -565,10 +619,11 @@ test commented out pending API-change approval ObjectInputStream istream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - Locale test2 = (Locale)(istream.readObject()); + Locale test2 = (Locale) (istream.readObject()); - if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) + if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) { errln("Locale failed to deserialize correctly."); + } } /** @@ -579,15 +634,16 @@ test commented out pending API-change approval // fallback behavior, combination of language and country names to form locale // names, and other stuff like that. This test just checks specific language // and country codes to make sure we have the correct names for them. - String[] languageCodes = { "he", "id", "iu", "ug", "yi", "za" }; - String[] languageNames = { "Hebrew", "Indonesian", "Inuktitut", "Uighur", "Yiddish", - "Zhuang" }; + String[] languageCodes = {"he", "id", "iu", "ug", "yi", "za"}; + String[] languageNames = {"Hebrew", "Indonesian", "Inuktitut", "Uighur", "Yiddish", + "Zhuang"}; for (int i = 0; i < languageCodes.length; i++) { String test = (new Locale(languageCodes[i], "", "")).getDisplayLanguage(Locale.US); - if (!test.equals(languageNames[i])) - errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + - languageNames[i] + "\", got \"" + test + "\"."); + if (!test.equals(languageNames[i])) { + errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + + languageNames[i] + "\", got \"" + test + "\"."); + } } } @@ -597,24 +653,26 @@ test commented out pending API-change approval public void TestUninstalledISO3Names() { // This test checks to make sure getISO3Language and getISO3Country work right // even for locales that are not installed. - String[] iso2Languages = { "am", "ba", "fy", "mr", "rn", "ss", "tw", "zu" }; - String[] iso3Languages = { "amh", "bak", "fry", "mar", "run", "ssw", "twi", "zul" }; + String[] iso2Languages = {"am", "ba", "fy", "mr", "rn", "ss", "tw", "zu"}; + String[] iso3Languages = {"amh", "bak", "fry", "mar", "run", "ssw", "twi", "zul"}; for (int i = 0; i < iso2Languages.length; i++) { String test = (new Locale(iso2Languages[i], "", "")).getISO3Language(); - if (!test.equals(iso3Languages[i])) - errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + - iso3Languages[i] + "\", got \"" + test + "\"."); + if (!test.equals(iso3Languages[i])) { + errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + + iso3Languages[i] + "\", got \"" + test + "\"."); + } } - String[] iso2Countries = { "AF", "BW", "KZ", "MO", "MN", "SB", "TC", "ZW" }; - String[] iso3Countries = { "AFG", "BWA", "KAZ", "MAC", "MNG", "SLB", "TCA", "ZWE" }; + String[] iso2Countries = {"AF", "BW", "KZ", "MO", "MN", "SB", "TC", "ZW"}; + String[] iso3Countries = {"AFG", "BWA", "KAZ", "MAC", "MNG", "SLB", "TCA", "ZWE"}; for (int i = 0; i < iso2Countries.length; i++) { String test = (new Locale("", iso2Countries[i], "")).getISO3Country(); - if (!test.equals(iso3Countries[i])) - errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + - iso3Countries[i] + "\", got \"" + test + "\"."); + if (!test.equals(iso3Countries[i])) { + errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + + iso3Countries[i] + "\", got \"" + test + "\"."); + } } } @@ -629,15 +687,18 @@ test commented out pending API-change approval Locale indonesianOld = new Locale("in", "", ""); Locale indonesianNew = new Locale("id", "", ""); - if (!hebrewNew.getLanguage().equals("iw")) - errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + - hebrewNew.getLanguage() + "\""); - if (!yiddishNew.getLanguage().equals("ji")) - errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + - yiddishNew.getLanguage() + "\""); - if (!indonesianNew.getLanguage().equals("in")) - errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + - indonesianNew.getLanguage() + "\""); + if (!hebrewNew.getLanguage().equals("iw")) { + errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + + hebrewNew.getLanguage() + "\""); + } + if (!yiddishNew.getLanguage().equals("ji")) { + errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + + yiddishNew.getLanguage() + "\""); + } + if (!indonesianNew.getLanguage().equals("in")) { + errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + + indonesianNew.getLanguage() + "\""); + } } /** @@ -703,25 +764,28 @@ test commented out pending API-change approval for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.US); logln(name); - if (!name.equals(englishDisplayNames[i])) + if (!name.equals(englishDisplayNames[i])) { errln("Lookup in English failed: expected \"" + englishDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(new Locale("es", "ES")); logln(name); - if (!name.equals(spanishDisplayNames[i])) + if (!name.equals(spanishDisplayNames[i])) { errln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.FRANCE); logln(name); - if (!name.equals(frenchDisplayNames[i])) + if (!name.equals(frenchDisplayNames[i])) { errln("Lookup in French failed: expected \"" + frenchDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } // restore the default locale for other tests @@ -737,15 +801,16 @@ test commented out pending API-change approval boolean gotException = false; try { Locale.setDefault(null); - } - catch (NullPointerException e) { + } catch (NullPointerException e) { // all other exception types propagate through here back to the test harness gotException = true; } - if (Locale.getDefault() == null) + if (Locale.getDefault() == null) { errln("Locale.getDefault() allowed us to set default to NULL!"); - if (!gotException) + } + if (!gotException) { errln("Trying to set default locale to NULL didn't throw exception!"); + } } /** @@ -754,14 +819,16 @@ test commented out pending API-change approval * get the LocaleDataTest working again. */ public void TestThaiCurrencyFormat() { - DecimalFormat thaiCurrency = (DecimalFormat)NumberFormat.getCurrencyInstance( - new Locale("th", "TH")); - if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) - errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + - thaiCurrency.getPositivePrefix() + "\""); - if (!thaiCurrency.getPositiveSuffix().equals("")) - errln("Thai currency suffix wrong: expected \"\", got \"" + - thaiCurrency.getPositiveSuffix() + "\""); + DecimalFormat thaiCurrency = (DecimalFormat) NumberFormat.getCurrencyInstance( + new Locale("th", "TH")); + if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) { + errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + + thaiCurrency.getPositivePrefix() + "\""); + } + if (!thaiCurrency.getPositiveSuffix().equals("")) { + errln("Thai currency suffix wrong: expected \"\", got \"" + + thaiCurrency.getPositiveSuffix() + "\""); + } } /** @@ -778,26 +845,25 @@ test commented out pending API-change approval * iterate through all locales. */ public void TestEuroSupport() { - final String EURO_VARIANT = "EURO"; + final String EURO_VARIANT = "EURO"; final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency Locale[] locales = NumberFormat.getAvailableLocales(); - for (int i=0; i= 0) { NumberFormat nf = NumberFormat.getCurrencyInstance(loc); String pos = nf.format(271828.182845); String neg = nf.format(-271828.182845); - if (pos.indexOf(EURO_CURRENCY) >= 0 && - neg.indexOf(EURO_CURRENCY) >= 0) { - logln("Ok: " + loc.toString() + - ": " + pos + " / " + neg); - } - else { - errln("Fail: " + loc.toString() + - " formats without " + EURO_CURRENCY + - ": " + pos + " / " + neg + - "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); + if (pos.indexOf(EURO_CURRENCY) >= 0 + && neg.indexOf(EURO_CURRENCY) >= 0) { + logln("Ok: " + loc.toString() + + ": " + pos + " / " + neg); + } else { + errln("Fail: " + loc.toString() + + " formats without " + EURO_CURRENCY + + ": " + pos + " / " + neg + + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); } } } @@ -811,15 +877,15 @@ test commented out pending API-change approval Object[] DATA = { new Locale("xx", "", ""), "xx", new Locale("", "YY", ""), "_YY", - new Locale("", "", "ZZ"), "", + new Locale("", "", "ZZ"), "", new Locale("xx", "YY", ""), "xx_YY", new Locale("xx", "", "ZZ"), "xx__ZZ", new Locale("", "YY", "ZZ"), "_YY_ZZ", new Locale("xx", "YY", "ZZ"), "xx_YY_ZZ", }; - for (int i=0; i" + loc); } @@ -832,9 +898,9 @@ test commented out pending API-change approval * end to test the whole pipe. */ public void Test4105828() { - Locale[] LOC = { Locale.CHINESE, new Locale("zh", "CN", ""), - new Locale("zh", "TW", ""), new Locale("zh", "HK", "") }; - for (int i=0; i= 0) + if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0) { errln("Fail: Monday in Hungarian is wrong"); + } } /** @@ -894,9 +962,10 @@ test commented out pending API-change approval try { String result = locale.getISO3Country(); - errln("ERROR: getISO3Country() returns: " + result + - " for locale '" + locale + "' rather than exception" ); - } catch(MissingResourceException e) { } + errln("ERROR: getISO3Country() returns: " + result + + " for locale '" + locale + "' rather than exception"); + } catch (MissingResourceException e) { + } } /** @@ -912,8 +981,8 @@ test commented out pending API-change approval String result = locale.getISO3Language(); if (!result.equals("aaa")) { - errln("ERROR: getISO3Language() returns: " + result + - " for locale '" + locale + "' rather than returning it as is" ); + errln("ERROR: getISO3Language() returns: " + result + + " for locale '" + locale + "' rather than returning it as is"); } // Try an invalid two letter language code, and check whether it @@ -923,36 +992,39 @@ test commented out pending API-change approval try { result = locale.getISO3Language(); - errln("ERROR: getISO3Language() returns: " + result + - " for locale '" + locale + "' rather than exception" ); - } catch(MissingResourceException e) { } + errln("ERROR: getISO3Language() returns: " + result + + " for locale '" + locale + "' rather than exception"); + } catch (MissingResourceException e) { + } } /* * @bug 4147552 4778440 8030696 */ public void Test4147552() { - Locale[] locales = { new Locale("no", "NO"), new Locale("no", "NO", "B"), - new Locale("no", "NO", "NY"), new Locale("nb", "NO"), - new Locale("nn", "NO") }; - String[] englishDisplayNames = { "Norwegian (Norway)", - "Norwegian (Norway,Bokm\u00e5l)", - "Norwegian (Norway,Nynorsk)", - "Norwegian Bokm\u00e5l (Norway)", - "Norwegian Nynorsk (Norway)" }; - String[] norwegianDisplayNames = { "norsk (Norge)", - "norsk (Norge,bokm\u00e5l)", "norsk (Noreg,nynorsk)", - "bokm\u00e5l (Norge)", "nynorsk (Noreg)" }; + Locale[] locales = {new Locale("no", "NO"), new Locale("no", "NO", "B"), + new Locale("no", "NO", "NY"), new Locale("nb", "NO"), + new Locale("nn", "NO")}; + String[] englishDisplayNames = {"Norwegian (Norway)", + "Norwegian (Norway,Bokm\u00e5l)", + "Norwegian (Norway,Nynorsk)", + "Norwegian Bokm\u00e5l (Norway)", + "Norwegian Nynorsk (Norway)"}; + String[] norwegianDisplayNames = {"norsk (Norge)", + "norsk (Norge,bokm\u00e5l)", "norsk (Noreg,nynorsk)", + "bokm\u00e5l (Norge)", "nynorsk (Noreg)"}; for (int i = 0; i < locales.length; i++) { Locale loc = locales[i]; - if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) - errln("English display-name mismatch: expected " + - englishDisplayNames[i] + ", got " + loc.getDisplayName()); - if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) - errln("Norwegian display-name mismatch: expected " + - norwegianDisplayNames[i] + ", got " + - loc.getDisplayName(loc)); + if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) { + errln("English display-name mismatch: expected " + + englishDisplayNames[i] + ", got " + loc.getDisplayName()); + } + if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) { + errln("Norwegian display-name mismatch: expected " + + norwegianDisplayNames[i] + ", got " + + loc.getDisplayName(loc)); + } } } @@ -961,21 +1033,24 @@ test commented out pending API-change approval */ public void Test8030696() { List av = Arrays.asList(Locale.getAvailableLocales()); - if (!av.contains(new Locale("nb", "NO")) || - !av.contains(new Locale("nn", "NO"))) { - errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); + if (!av.contains(new Locale("nb", "NO")) + || !av.contains(new Locale("nn", "NO"))) { + errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); } } static String escapeUnicode(String s) { StringBuffer buf = new StringBuffer(); - for (int i=0; i= 0x20 && c <= 0x7F) buf.append(c); - else { + if (c >= 0x20 && c <= 0x7F) { + buf.append(c); + } else { buf.append("\\u"); String h = "000" + Integer.toHexString(c); - if (h.length() > 4) h = h.substring(h.length() - 4); + if (h.length() > 4) { + h = h.substring(h.length() - 4); + } buf.append(h); } } diff --git a/jdk/test/java/util/Locale/LocaleTestFmwk.java b/jdk/test/java/util/Locale/LocaleTestFmwk.java deleted file mode 100644 index 68532d4d31d..00000000000 --- a/jdk/test/java/util/Locale/LocaleTestFmwk.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * - * - * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved - * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved - * - * Portions copyright (c) 2007 Sun Microsystems, Inc. - * All Rights Reserved. - * - * The original version of this source code and documentation - * is copyrighted and owned by Taligent, Inc., a wholly-owned - * subsidiary of IBM. These materials are provided under terms - * of a License Agreement between Taligent and Sun. This technology - * is protected by multiple US and International patents. - * - * This notice and attribution to Taligent may not be removed. - * Taligent is a registered trademark of Taligent, Inc. - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for NON-COMMERCIAL purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. Please refer to the file "copyright.html" - * for further important copyright and licensing information. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF - * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED - * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * LocaleTestFmwk is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public class LocaleTestFmwk { - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected LocaleTestFmwk() { - // Create a hashtable containing all the test methods. - testMethods = new Hashtable(); - Method[] methods = getClass().getDeclaredMethods(); - for( int i=0; i 0) { - throw new IllegalArgumentException("encountered " + errorCount + " errors"); - } - } - } - - /** - * Adds given string to the log if we are in verbose mode. - */ - protected void log( String message ) { - if( verbose ) { - indent(indentLevel + 1); - log.print( message ); - } - } - - protected void logln( String message ) { - log(message + System.getProperty("line.separator")); - } - - /** - * Report an error - */ - protected void err( String message ) { - errorCount++; - indent(indentLevel + 1); - log.print( message ); - log.flush(); - - if (!nothrow) { - throw new RuntimeException(message); - } - } - - protected void errln( String message ) { - err(message + System.getProperty("line.separator")); - } - - - protected void writeTestName(String testName) { - indent(indentLevel); - log.print(testName); - log.flush(); - needLineFeed = true; - } - - protected void writeTestResult(int count) { - if (!needLineFeed) { - indent(indentLevel); - log.print("}"); - } - needLineFeed = false; - - if (count != 0) - log.println(" FAILED"); - else - log.println(" Passed"); - } - - private final void indent(int distance) { - if (needLineFeed) { - log.println(" {"); - needLineFeed = false; - } - log.print(spaces.substring(0, distance * 2)); - } - - /** - * Print a usage message for this test class. - */ - void usage() { - System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); - - System.out.println("test names:"); - Enumeration methodNames = testMethods.keys(); - while( methodNames.hasMoreElements() ) { - System.out.println("\t" + methodNames.nextElement() ); - } - } - - private boolean prompt = false; - private boolean nothrow = false; - private boolean exitcode = false; - protected boolean verbose = false; - - private PrintWriter log; - private int indentLevel = 0; - private boolean needLineFeed = false; - private int errorCount = 0; - - private Hashtable testMethods; - private final String spaces = " "; -} From 3f35be72427da1482feba9dcbcfed3a973d258db Mon Sep 17 00:00:00 2001 From: Anubhav Meena Date: Thu, 17 Nov 2016 11:55:59 +0000 Subject: [PATCH 055/402] 8167618: DateTimeFormatter.format() uses exceptions for flow control Removed flow control in exception catch Reviewed-by: rriggs, scolebourne --- .../java/time/format/DateTimePrintContext.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java b/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java index 811bd5b2ee1..0faec561724 100644 --- a/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java +++ b/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -302,14 +302,10 @@ final class DateTimePrintContext { * @throws DateTimeException if the field is not available and the section is not optional */ Long getValue(TemporalField field) { - try { - return temporal.getLong(field); - } catch (DateTimeException ex) { - if (optional > 0) { - return null; - } - throw ex; + if (optional > 0 && !temporal.isSupported(field)) { + return null; } + return temporal.getLong(field); } //----------------------------------------------------------------------- From 9a7622561ae9528d90c1abfa76f7649ae5f67428 Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Thu, 17 Nov 2016 21:02:39 +0800 Subject: [PATCH 056/402] 7004967: SecureRandom should be more explicit about threading 8169312: SecureRandom::getSeed(num) not specified if num is negative Reviewed-by: mullan, xuelei --- .../classes/java/security/SecureRandom.java | 100 ++++++++++++++--- .../java/security/SecureRandomSpi.java | 20 ++++ .../sun/security/provider/SunEntries.java | 8 ++ .../sun/security/mscapi/SunMSCAPI.java | 7 +- .../sun/security/pkcs11/SunPKCS11.java | 3 +- .../java/security/SecureRandom/NoSync.java | 101 +++++++++++++++++ .../security/SecureRandom/ThreadSafe.java | 102 ++++++++++++++++++ 7 files changed, 327 insertions(+), 14 deletions(-) create mode 100644 jdk/test/java/security/SecureRandom/NoSync.java create mode 100644 jdk/test/java/security/SecureRandom/ThreadSafe.java diff --git a/jdk/src/java.base/share/classes/java/security/SecureRandom.java b/jdk/src/java.base/share/classes/java/security/SecureRandom.java index 8449613ba66..12b60f688e0 100644 --- a/jdk/src/java.base/share/classes/java/security/SecureRandom.java +++ b/jdk/src/java.base/share/classes/java/security/SecureRandom.java @@ -120,6 +120,24 @@ import sun.security.util.Debug; * gathered, for example, if the entropy source is /dev/random on various * Unix-like operating systems. * + *

    Thread safety

    + * {@code SecureRandom} objects are safe for use by multiple concurrent threads. + * + * @implSpec + * A {@code SecureRandom} service provider can advertise that it is thread-safe + * by setting the service + * provider attribute "ThreadSafe" to "true" when registering the provider. + * Otherwise, this class will instead synchronize access to the following + * methods of the {@code SecureRandomSpi} implementation: + *
      + *
    • {@link SecureRandomSpi#engineSetSeed(byte[])} + *
    • {@link SecureRandomSpi#engineNextBytes(byte[])} + *
    • {@link SecureRandomSpi#engineNextBytes(byte[], SecureRandomParameters)} + *
    • {@link SecureRandomSpi#engineGenerateSeed(int)} + *
    • {@link SecureRandomSpi#engineReseed(SecureRandomParameters)} + *
    + * * @see java.security.SecureRandomSpi * @see java.util.Random * @@ -150,6 +168,14 @@ public class SecureRandom extends java.util.Random { */ private SecureRandomSpi secureRandomSpi = null; + /** + * Thread safety. + * + * @serial + * @since 9 + */ + private final boolean threadSafe; + /* * The algorithm name of null if unknown. * @@ -189,6 +215,16 @@ public class SecureRandom extends java.util.Random { */ super(0); getDefaultPRNG(false, null); + this.threadSafe = getThreadSafe(); + } + + private boolean getThreadSafe() { + if (provider == null || algorithm == null) { + return false; + } else { + return Boolean.parseBoolean(provider.getProperty( + "SecureRandom." + algorithm + " ThreadSafe", "false")); + } } /** @@ -217,6 +253,7 @@ public class SecureRandom extends java.util.Random { public SecureRandom(byte[] seed) { super(0); getDefaultPRNG(true, seed); + this.threadSafe = getThreadSafe(); } private void getDefaultPRNG(boolean setSeed, byte[] seed) { @@ -269,6 +306,7 @@ public class SecureRandom extends java.util.Random { this.secureRandomSpi = secureRandomSpi; this.provider = provider; this.algorithm = algorithm; + this.threadSafe = getThreadSafe(); if (!skipDebug && pdebug != null) { pdebug.println("SecureRandom." + algorithm + @@ -653,8 +691,14 @@ public class SecureRandom extends java.util.Random { * * @see #getSeed */ - public synchronized void setSeed(byte[] seed) { - secureRandomSpi.engineSetSeed(seed); + public void setSeed(byte[] seed) { + if (threadSafe) { + secureRandomSpi.engineSetSeed(seed); + } else { + synchronized (this) { + secureRandomSpi.engineSetSeed(seed); + } + } } /** @@ -679,7 +723,7 @@ public class SecureRandom extends java.util.Random { * yet been initialized at that point. */ if (seed != 0) { - this.secureRandomSpi.engineSetSeed(longToByteArray(seed)); + setSeed(longToByteArray(seed)); } } @@ -690,7 +734,13 @@ public class SecureRandom extends java.util.Random { */ @Override public void nextBytes(byte[] bytes) { - secureRandomSpi.engineNextBytes(bytes); + if (threadSafe) { + secureRandomSpi.engineNextBytes(bytes); + } else { + synchronized (this) { + secureRandomSpi.engineNextBytes(bytes); + } + } } /** @@ -707,12 +757,19 @@ public class SecureRandom extends java.util.Random { * * @since 9 */ - public synchronized void nextBytes( - byte[] bytes, SecureRandomParameters params) { + public void nextBytes(byte[] bytes, SecureRandomParameters params) { if (params == null) { throw new IllegalArgumentException("params cannot be null"); } - secureRandomSpi.engineNextBytes(Objects.requireNonNull(bytes), params); + if (threadSafe) { + secureRandomSpi.engineNextBytes( + Objects.requireNonNull(bytes), params); + } else { + synchronized (this) { + secureRandomSpi.engineNextBytes( + Objects.requireNonNull(bytes), params); + } + } } /** @@ -756,6 +813,7 @@ public class SecureRandom extends java.util.Random { * * @param numBytes the number of seed bytes to generate. * + * @throws IllegalArgumentException if {@code numBytes} is negative * @return the seed bytes. * * @see #setSeed @@ -782,7 +840,13 @@ public class SecureRandom extends java.util.Random { if (numBytes < 0) { throw new IllegalArgumentException("numBytes cannot be negative"); } - return secureRandomSpi.engineGenerateSeed(numBytes); + if (threadSafe) { + return secureRandomSpi.engineGenerateSeed(numBytes); + } else { + synchronized (this) { + return secureRandomSpi.engineGenerateSeed(numBytes); + } + } } /** @@ -917,8 +981,14 @@ public class SecureRandom extends java.util.Random { * * @since 9 */ - public synchronized void reseed() { - secureRandomSpi.engineReseed(null); + public void reseed() { + if (threadSafe) { + secureRandomSpi.engineReseed(null); + } else { + synchronized (this) { + secureRandomSpi.engineReseed(null); + } + } } /** @@ -937,11 +1007,17 @@ public class SecureRandom extends java.util.Random { * * @since 9 */ - public synchronized void reseed(SecureRandomParameters params) { + public void reseed(SecureRandomParameters params) { if (params == null) { throw new IllegalArgumentException("params cannot be null"); } - secureRandomSpi.engineReseed(params); + if (threadSafe) { + secureRandomSpi.engineReseed(params); + } else { + synchronized (this) { + secureRandomSpi.engineReseed(params); + } + } } // Declare serialVersionUID to be compatible with JDK1.1 diff --git a/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java b/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java index 9aa24f57bc8..65a0ce0164d 100644 --- a/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java +++ b/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java @@ -58,6 +58,26 @@ package java.security; * a {@code SecureRandomParameters} argument will never * return an instance of this implementation. The * {@link #engineGetParameters()} method must return {@code null}. + *

    + * See {@link SecureRandom} for additional details on thread safety. By + * default, a {@code SecureRandomSpi} implementation is considered to be + * not safe for use by multiple concurrent threads and {@code SecureRandom} + * will synchronize access to each of the applicable engine methods + * (see {@link SecureRandom} for the list of methods). However, if a + * {@code SecureRandomSpi} implementation is thread-safe, the + * service provider attribute "ThreadSafe" should be set to "true" during + * its registration, as follows: + *

    + * put("SecureRandom.AlgName ThreadSafe", "true");
    + *
    + * or + *
    + * putService(new Service(this, "SecureRandom", "AlgName", className,
    + *          null, Map.of("ThreadSafe", "true")));
    + *
    + * {@code SecureRandom} will call the applicable engine methods + * without any synchronization. * * @since 1.2 */ diff --git a/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java b/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java index ea090fa6898..31164695ecc 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java @@ -96,25 +96,32 @@ final class SunEntries { if (nativeAvailable && useNativePRNG) { map.put("SecureRandom.NativePRNG", "sun.security.provider.NativePRNG"); + map.put("SecureRandom.NativePRNG ThreadSafe", "true"); } map.put("SecureRandom.DRBG", "sun.security.provider.DRBG"); + map.put("SecureRandom.DRBG ThreadSafe", "true"); map.put("SecureRandom.SHA1PRNG", "sun.security.provider.SecureRandom"); + + map.put("SecureRandom.SHA1PRNG ThreadSafe", "true"); if (nativeAvailable && !useNativePRNG) { map.put("SecureRandom.NativePRNG", "sun.security.provider.NativePRNG"); + map.put("SecureRandom.NativePRNG ThreadSafe", "true"); } if (NativePRNG.Blocking.isAvailable()) { map.put("SecureRandom.NativePRNGBlocking", "sun.security.provider.NativePRNG$Blocking"); + map.put("SecureRandom.NativePRNGBlocking ThreadSafe", "true"); } if (NativePRNG.NonBlocking.isAvailable()) { map.put("SecureRandom.NativePRNGNonBlocking", "sun.security.provider.NativePRNG$NonBlocking"); + map.put("SecureRandom.NativePRNGNonBlocking ThreadSafe", "true"); } /* @@ -329,6 +336,7 @@ final class SunEntries { map.put("AlgorithmParameters.DSA ImplementedIn", "Software"); map.put("KeyFactory.DSA ImplementedIn", "Software"); map.put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); + map.put("SecureRandom.DRBG ImplementedIn", "Software"); map.put("CertificateFactory.X.509 ImplementedIn", "Software"); map.put("KeyStore.JKS ImplementedIn", "Software"); map.put("CertPathValidator.PKIX ImplementedIn", "Software"); diff --git a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java index 70165388eef..b7fbf801e86 100644 --- a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java +++ b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java @@ -33,6 +33,8 @@ import java.security.InvalidParameterException; import java.security.ProviderException; import java.util.HashMap; import java.util.Arrays; +import java.util.Map; + import static sun.security.util.SecurityConstants.PROVIDER_VER; /** @@ -133,8 +135,11 @@ public final class SunMSCAPI extends Provider { /* * Secure random */ + HashMap srattrs = new HashMap<>(1); + srattrs.put("ThreadSafe", "true"); putService(new ProviderService(p, "SecureRandom", - "Windows-PRNG", "sun.security.mscapi.PRNG")); + "Windows-PRNG", "sun.security.mscapi.PRNG", + null, srattrs)); /* * Key store diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java index 98b5e21ea2c..a9b6de30d82 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java @@ -987,7 +987,8 @@ public final class SunPKCS11 extends AuthProvider { P11Service(Token token, String type, String algorithm, String className, String[] al, long mechanism) { - super(token.provider, type, algorithm, className, toList(al), null); + super(token.provider, type, algorithm, className, toList(al), + type.equals(SR) ? Map.of("ThreadSafe", "true") : null); this.token = token; this.mechanism = mechanism & 0xFFFFFFFFL; } diff --git a/jdk/test/java/security/SecureRandom/NoSync.java b/jdk/test/java/security/SecureRandom/NoSync.java new file mode 100644 index 00000000000..032833c4a7f --- /dev/null +++ b/jdk/test/java/security/SecureRandom/NoSync.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.util.Date; +import java.util.concurrent.atomic.AtomicBoolean; + +/* + * @test + * @bug 7004967 + * @run main/othervm NoSync + * @summary SecureRandom should be more explicit about threading + */ +public class NoSync { + public static void main(String[] args) throws Exception { + for (Provider p : Security.getProviders()) { + for (Provider.Service s : p.getServices()) { + if (s.getType().equals("SecureRandom") && + !s.getAlgorithm().contains("Block")) { + test(SecureRandom.getInstance(s.getAlgorithm(), p)); + } + } + } + Security.setProperty("securerandom.drbg.config", "HMAC_DRBG"); + test(SecureRandom.getInstance("DRBG")); + Security.setProperty("securerandom.drbg.config", "CTR_DRBG"); + test(SecureRandom.getInstance("DRBG")); + } + + static void test(SecureRandom sr) throws Exception { + test(sr, 20, 3000); + // All out-of-box impl should have the ThreadSafe attribute + String attr = sr.getProvider().getProperty("SecureRandom." + + sr.getAlgorithm() + " ThreadSafe"); + if (!"true".equals(attr)) { + throw new Exception("Not ThreadSafe: " + attr); + } + } + + public static void test(SecureRandom sr, int tnum, int rnum) + throws Exception { + + System.out.println(sr); + System.out.println(sr.getAlgorithm() + " " + sr.getProvider().getName()); + + System.out.println(new Date()); + boolean reseed = sr.getParameters() != null; + Thread[] threads = new Thread[tnum]; + AtomicBoolean failed = new AtomicBoolean(false); + Thread.UncaughtExceptionHandler h = (t, e) -> { + failed.set(true); + e.printStackTrace(); + }; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { + @Override + public void run() { + for (int j = 0; j < rnum; j++) { + sr.nextBytes(new byte[j%100+100]); + sr.setSeed((long)j); + if (reseed) { + sr.reseed(); + } + } + } + }; + threads[i].setUncaughtExceptionHandler(h); + threads[i].start(); + } + for (int i = 0; i < threads.length; i++) { + threads[i].join(); + } + System.out.println(new Date()); + System.out.println(); + if (failed.get()) { + throw new RuntimeException("Failed"); + } + } +} diff --git a/jdk/test/java/security/SecureRandom/ThreadSafe.java b/jdk/test/java/security/SecureRandom/ThreadSafe.java new file mode 100644 index 00000000000..fda344b199f --- /dev/null +++ b/jdk/test/java/security/SecureRandom/ThreadSafe.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Provider; +import java.security.SecureRandom; +import java.security.SecureRandomSpi; +import java.util.Map; + +/* + * @test + * @bug 7004967 + * @summary SecureRandom should be more explicit about threading + */ +public class ThreadSafe { + public static void main(String[] args) throws Exception { + Provider p = new P(); + NoSync.test(SecureRandom.getInstance("S1", p), 5, 5); + try { + NoSync.test(SecureRandom.getInstance("S2", p), 5, 5); + throw new Exception("Failed"); + } catch (RuntimeException re) { + // Good + } + NoSync.test(SecureRandom.getInstance("S3", p), 5, 5); + try { + NoSync.test(SecureRandom.getInstance("S4", p), 5, 5); + throw new Exception("Failed"); + } catch (RuntimeException re) { + // Good + } + } + + public static class P extends Provider { + public P() { + + super("P", 1.0d, "Haha"); + + // Good. No attribute. + put("SecureRandom.S1", S.class.getName()); + + // Bad. Boasting ThreadSafe but isn't + put("SecureRandom.S2", S.class.getName()); + put("SecureRandom.S2 ThreadSafe", "true"); + + // Good. No attribute. + putService(new Service(this, "SecureRandom", "S3", + S.class.getName(), null, null)); + + // Bad. Boasting ThreadSafe but isn't + putService(new Service(this, "SecureRandom", "S4", + S.class.getName(), null, Map.of("ThreadSafe", "true"))); + } + } + + // This implementation is not itself thread safe. + public static class S extends SecureRandomSpi { + @java.lang.Override + protected void engineSetSeed(byte[] seed) { + return; + } + + private volatile boolean inCall = false; + @Override + protected void engineNextBytes(byte[] bytes) { + if (inCall) { + throw new RuntimeException("IN CALL"); + } + inCall = true; + try { + Thread.sleep(100); + } catch (Exception e) { + // OK + } + inCall = false; + } + + @Override + protected byte[] engineGenerateSeed(int numBytes) { + return new byte[numBytes]; + } + } +} From 09591861d0795266cf6371f52c6bf5cc55ede40c Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Thu, 17 Nov 2016 19:38:14 +0100 Subject: [PATCH 057/402] 8169880: Remove the sun.reflect.noCaches option Reviewed-by: shade, psandoz, mchung --- .../share/classes/java/lang/Class.java | 46 +------------------ 1 file changed, 1 insertion(+), 45 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/Class.java b/jdk/src/java.base/share/classes/java/lang/Class.java index 725d237aff6..16949ed5057 100644 --- a/jdk/src/java.base/share/classes/java/lang/Class.java +++ b/jdk/src/java.base/share/classes/java/lang/Class.java @@ -2704,9 +2704,6 @@ public final class Class implements java.io.Serializable, * Reflection support. */ - // Caches for certain reflective results - private static boolean useCaches = true; - // reflection data that might get invalidated when JVM TI RedefineClasses() is called private static class ReflectionData { volatile Field[] declaredFields; @@ -2739,8 +2736,7 @@ public final class Class implements java.io.Serializable, SoftReference> reflectionData = this.reflectionData; int classRedefinedCount = this.classRedefinedCount; ReflectionData rd; - if (useCaches && - reflectionData != null && + if (reflectionData != null && (rd = reflectionData.get()) != null && rd.redefinedCount == classRedefinedCount) { return rd; @@ -2752,8 +2748,6 @@ public final class Class implements java.io.Serializable, private ReflectionData newReflectionData(SoftReference> oldReflectionData, int classRedefinedCount) { - if (!useCaches) return null; - while (true) { ReflectionData rd = new ReflectionData<>(classRedefinedCount); // try to CAS it... @@ -2819,7 +2813,6 @@ public final class Class implements java.io.Serializable, // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyField. private Field[] privateGetDeclaredFields(boolean publicOnly) { - checkInitted(); Field[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2842,7 +2835,6 @@ public final class Class implements java.io.Serializable, // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyField. private Field[] privateGetPublicFields(Set> traversedInterfaces) { - checkInitted(); Field[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2902,7 +2894,6 @@ public final class Class implements java.io.Serializable, // objects must NOT be propagated to the outside world, but must // instead be copied via ReflectionFactory.copyConstructor. private Constructor[] privateGetDeclaredConstructors(boolean publicOnly) { - checkInitted(); Constructor[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2937,7 +2928,6 @@ public final class Class implements java.io.Serializable, // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyMethod. private Method[] privateGetDeclaredMethods(boolean publicOnly) { - checkInitted(); Method[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -3134,7 +3124,6 @@ public final class Class implements java.io.Serializable, // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyMethod. private Method[] privateGetPublicMethods() { - checkInitted(); Method[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -3490,39 +3479,6 @@ public final class Class implements java.io.Serializable, } private static ReflectionFactory reflectionFactory; - // To be able to query system properties as soon as they're available - private static boolean initted = false; - private static void checkInitted() { - if (initted) return; - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() { - // Tests to ensure the system properties table is fully - // initialized. This is needed because reflection code is - // called very early in the initialization process (before - // command-line arguments have been parsed and therefore - // these user-settable properties installed.) We assume that - // if System.out is non-null then the System class has been - // fully initialized and that the bulk of the startup code - // has been run. - - if (System.out == null) { - // java.lang.System not yet fully initialized - return null; - } - - // Doesn't use Boolean.getBoolean to avoid class init. - String val = - System.getProperty("sun.reflect.noCaches"); - if (val != null && val.equals("true")) { - useCaches = false; - } - - initted = true; - return null; - } - }); - } - /** * Returns the elements of this enum class or null if this * Class object does not represent an enum type. From b02932fab854704174c6b964aad2580895c89814 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Thu, 17 Nov 2016 12:24:51 -0800 Subject: [PATCH 058/402] 8169838: java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java failed intermittently Reviewed-by: martin --- .../Spliterator/SpliteratorTraversingAndSplittingTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java index 6d00fd6a3e3..474204384a8 100644 --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java @@ -25,7 +25,7 @@ * @test * @summary Spliterator traversing and splitting tests * @run testng SpliteratorTraversingAndSplittingTest - * @bug 8020016 8071477 + * @bug 8020016 8071477 8072784 8169838 */ import org.testng.annotations.DataProvider; @@ -892,9 +892,6 @@ public class SpliteratorTraversingAndSplittingTest { { "index 0", IntStream.of(0).toArray() }, { "index 255", IntStream.of(255).toArray() }, { "index 0 and 255", IntStream.of(0, 255).toArray() }, - { "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE).toArray() }, - { "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1).toArray() }, - { "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE).toArray() }, { "every bit", IntStream.range(0, 255).toArray() }, { "step 2", IntStream.range(0, 255).map(f -> f * 2).toArray() }, { "step 3", IntStream.range(0, 255).map(f -> f * 3).toArray() }, From e2729d2bea2770fbd7e305271131e31169b4abfc Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Fri, 18 Nov 2016 12:11:32 +0800 Subject: [PATCH 059/402] 8169826: ProblemList update for tools/pack200/CommandLineTests.java Reviewed-by: mchung --- jdk/test/ProblemList.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index f3ec6cdbdae..1253efdfa33 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -250,7 +250,7 @@ sanity/client/SwingSet/src/ButtonDemoScreenshotTest.java 8157338 generic- # core_tools -tools/pack200/CommandLineTests.java 7143279,8059906 generic-all +tools/pack200/CommandLineTests.java 8059906 generic-all tools/launcher/FXLauncherTest.java 8068049 linux-all,macosx-all From 1c762c2b33b383ee082a7d19dcd86311bda35c48 Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Fri, 18 Nov 2016 14:39:03 +0800 Subject: [PATCH 060/402] 8169836: ProblemList update for java/lang/management/MemoryMXBean/PendingAllGC.sh Reviewed-by: mchung --- jdk/test/ProblemList.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 1253efdfa33..6a6571c58a4 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -135,7 +135,7 @@ java/lang/instrument/RetransformBigClass.sh 8065756 generic- java/lang/instrument/BootClassPath/BootClassPathTest.sh 8072130 macosx-all java/lang/management/MemoryMXBean/Pending.java 8158837 generic-all -java/lang/management/MemoryMXBean/PendingAllGC.sh 8158760 generic-all +java/lang/management/MemoryMXBean/PendingAllGC.sh 8158837 generic-all ############################################################################ From 2007b3c02e84a1e46c5954a17b518455065eea4e Mon Sep 17 00:00:00 2001 From: Denis Kononenko Date: Wed, 16 Nov 2016 18:11:56 +0300 Subject: [PATCH 061/402] 8167240: Write new tests to cover functionality of existing 'jimage' options New tests were implemented Reviewed-by: jlaskey, anazarov, shurailine --- jdk/test/tools/jimage/JImageBasicsTest.java | 89 +++++++ jdk/test/tools/jimage/JImageCliTest.java | 120 ++++++++++ jdk/test/tools/jimage/JImageExtractTest.java | 181 +++++++++++++++ jdk/test/tools/jimage/JImageInfoTest.java | 74 ++++++ jdk/test/tools/jimage/JImageListTest.java | 229 +++++++++++++++++++ jdk/test/tools/jimage/JImageToolTest.java | 14 +- jdk/test/tools/jimage/JImageVerifyTest.java | 94 ++++++++ 7 files changed, 792 insertions(+), 9 deletions(-) create mode 100644 jdk/test/tools/jimage/JImageBasicsTest.java create mode 100644 jdk/test/tools/jimage/JImageCliTest.java create mode 100644 jdk/test/tools/jimage/JImageExtractTest.java create mode 100644 jdk/test/tools/jimage/JImageInfoTest.java create mode 100644 jdk/test/tools/jimage/JImageListTest.java create mode 100644 jdk/test/tools/jimage/JImageVerifyTest.java diff --git a/jdk/test/tools/jimage/JImageBasicsTest.java b/jdk/test/tools/jimage/JImageBasicsTest.java new file mode 100644 index 00000000000..adfc8106d89 --- /dev/null +++ b/jdk/test/tools/jimage/JImageBasicsTest.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage basic options, i.e. --version, -h + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageBasicsTest + */ + +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageBasicsTest extends JImageCliTest { + + public void testVersion() { + jimage("--version") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.contains(System.getProperty("java.version")), "Contains java version."); + }); + } + + public void testFullVersion() { + jimage("--full-version") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.contains(System.getProperty("java.version")), "Contains java version."); + }); + } + + public void testHelp() { + jimage("--help") + .assertSuccess() + .resultChecker(r -> verifyHelpOutput(r.output)); + } + + public void testShortHelp() { + jimage("-h") + .assertSuccess() + .resultChecker(r -> verifyHelpOutput(r.output)); + } + + public void testUnknownAction() { + jimage("unknown") + .assertFailure() + .assertShowsError(); + } + + public void testUnknownOption() { + jimage("--unknown") + .assertFailure() + .assertShowsError(); + } + + private void verifyHelpOutput(String output) { + assertTrue(output.startsWith("Usage: jimage"), "Usage is printed."); + assertTrue(output.contains("extract"), "Option 'extract' is found."); + assertTrue(output.contains("info"), "Option 'info' is found."); + assertTrue(output.contains("list"), "Option 'list' is found."); + assertTrue(output.contains("verify"), "Option 'verify' is found."); + } + + public static void main(String[] args) throws Throwable { + new JImageBasicsTest().runTests(); + } +} + diff --git a/jdk/test/tools/jimage/JImageCliTest.java b/jdk/test/tools/jimage/JImageCliTest.java new file mode 100644 index 00000000000..da924d5ff94 --- /dev/null +++ b/jdk/test/tools/jimage/JImageCliTest.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static jdk.test.lib.Asserts.assertFalse; +import static jdk.test.lib.Asserts.assertTrue; +import static jdk.test.lib.Asserts.fail; + +/** + * This class is intended to be a base class for classes which are about to test + * command line interface of jimage. + */ +public class JImageCliTest { + + private String bootImagePath; + + public JImageCliTest() { + Path imagePath = Paths.get(System.getProperty("java.home"), "lib", "modules"); + if (Files.exists(imagePath)) { + this.bootImagePath = imagePath.toAbsolutePath().toString(); + } + } + + public void assertMatches(String regex, String output) { + Pattern pattern = Pattern.compile(regex); + if (!pattern.matcher(output).find()) { + fail(String.format("Expected to find a string match for [%s] in output \n[\n%s\n]\n.", + pattern, output)); + } + } + + /** + * Returns a path to a tested image to share it across tests. By default it returns a path to the boot image + * of tested JDK. This behavior can be redefined by descendants. + */ + public String getImagePath() { + return bootImagePath; + } + + /** + * Runs jimage task with the supplied arguments. + */ + protected static JImageResult jimage(String... args) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + System.out.println("jimage " + Arrays.asList(args)); + int exitCode = jdk.tools.jimage.Main.run(args, new PrintWriter(ps)); + return new JImageResult(exitCode, new String(baos.toByteArray(), UTF_8)); + } + + protected static class JImageResult { + final int exitCode; + final String output; + + JImageResult(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + + JImageResult assertSuccess() { assertTrue(exitCode == 0, output); return this; } + JImageResult assertFailure() { assertFalse(exitCode == 0, output); return this; } + + // a helper to ensure the error output doesn't exhibit implementation details + JImageResult assertShowsError() { + assertTrue(output.contains("Error"), + String.format("Output contains error, output=[%s]\n", output)); + assertFalse(output.contains("Exception"), + String.format("Output doesn't contain a stacktrace, output=[%s]\n", output)); + return this; + } + + JImageResult resultChecker(Consumer r) { r.accept(this); return this; } + } + + protected final void runTests() throws Throwable { + if (getImagePath() != null) { + for (Method m : getClass().getDeclaredMethods()) { + if (m.getName().startsWith("test")) { + System.out.printf("Invoking %s\n", m.getName()); + m.invoke(this); + } + } + } else { + System.out.println("This is not an image build. Skipping."); + } + } + +} + diff --git a/jdk/test/tools/jimage/JImageExtractTest.java b/jdk/test/tools/jimage/JImageExtractTest.java new file mode 100644 index 00000000000..9c015471414 --- /dev/null +++ b/jdk/test/tools/jimage/JImageExtractTest.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'extract' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main/othervm JImageExtractTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageExtractTest extends JImageCliTest { + public void testExtract() throws IOException { + jimage("extract", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(Paths.get(".")); + } + + public void testExtractHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("extract", "--help") + .assertSuccess() + .resultChecker(r -> { + // extract - descriptive text + assertMatches("\\s+extract\\s+-\\s+.*", r.output); + }); + } + } + + public void testExtractToDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } + + public void testExtractNoImageSpecified() { + jimage("extract", "") + .assertFailure() + .assertShowsError(); + } + + public void testExtractNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + jimage("extract", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("extract", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToUnspecifiedDir() { + jimage("extract", "--dir", "--", getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToNotExistingDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + Files.delete(tmp); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } + + public void testExtractFromDir() { + Path imagePath = Paths.get(getImagePath()); + Path imageDirPath = imagePath.subpath(0, imagePath.getNameCount() - 1); + jimage("extract", imageDirPath.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToDirBySymlink() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + try { + Path symlink = Files.createSymbolicLink(Paths.get(".", "symlink"), tmp); + jimage("extract", "--dir", symlink.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } catch (UnsupportedOperationException e) { + // symlinks are not supported + // nothing to test + } + } + + public void testExtractToReadOnlyDir() throws IOException { + Set perms = PosixFilePermissions.fromString("r-xr--r--"); + FileAttribute> atts = PosixFilePermissions.asFileAttribute(perms); + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName(), atts); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToNotEmptyDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + Files.createFile(Paths.get(tmp.toString(), ".not_empty")); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToFile() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_a_dir"); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + private void verifyExplodedImage(Path imagePath) throws IOException { + Set allModules = Files.walk(imagePath, 1).collect(Collectors.toSet()); + assertTrue(allModules.stream().anyMatch(p -> "java.base".equals(p.getFileName().toString())), + "Exploded image contains java.base module."); + + Set badModules = allModules.stream() + .filter(p -> !Files.exists(p.resolve("module-info.class"))) + .collect(Collectors.toSet()); + assertEquals(badModules, new HashSet() {{ add(imagePath); }}, + "There are no exploded modules with missing 'module-info.class'"); + } + + public static void main(String[] args) throws Throwable { + new JImageExtractTest().runTests(); + } +} + diff --git a/jdk/test/tools/jimage/JImageInfoTest.java b/jdk/test/tools/jimage/JImageInfoTest.java new file mode 100644 index 00000000000..45eaece46bb --- /dev/null +++ b/jdk/test/tools/jimage/JImageInfoTest.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'info' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageInfoTest + */ + +import java.util.Arrays; + +public class JImageInfoTest extends JImageCliTest { + public void testInfo() { + jimage("info", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertMatches("(?m)^\\s+Major Version: +[1-9]\\d*$.*", r.output); + assertMatches("(?m)^\\s+Minor Version: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Flags: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Resource Count: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Table Length: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Offsets Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Redirects Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Locations Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Strings Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Index Size: +\\d+$.*", r.output); + }); + } + + public void testInfoHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("info", opt) + .assertSuccess() + .resultChecker(r -> { + // info - descriptive text + assertMatches("\\s+info\\s+-\\s+.*", r.output); + }); + } + } + + public void testInfoUnknownOption() { + jimage("info", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageInfoTest().runTests(); + } +} + diff --git a/jdk/test/tools/jimage/JImageListTest.java b/jdk/test/tools/jimage/JImageListTest.java new file mode 100644 index 00000000000..e49e14e2ccb --- /dev/null +++ b/jdk/test/tools/jimage/JImageListTest.java @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'list' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageListTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertFalse; +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageListTest extends JImageCliTest { + public void testList() { + jimage("list", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + String[] lines = r.output.split(System.lineSeparator()); + assertTrue(lines.length > 0, "Option --list has output."); + assertTrue(lines[0].startsWith("jimage: " + getImagePath()), + "Output should start with jimage path."); + + List modules = Stream.of(lines) + .filter(s -> s.startsWith("Module: ")) + .map(s -> s.substring(s.indexOf(':') + 1).trim()) + .collect(Collectors.toList()); + assertTrue(modules.size() > 0, "Image contains at least one module."); + assertTrue(modules.indexOf("java.base") > 0, "Module java.base found."); + }); + } + + public void testListHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("list", opt) + .assertSuccess() + .resultChecker(r -> { + // list - descriptive text + assertMatches("\\s+list\\s+-\\s+.*", r.output); + }); + } + } + + public void testListVerbose() { + jimage("list", "--verbose", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertMatches("Offset\\s+Size\\s+Compressed\\s+Entry", r.output); + + String[] lines = r.output.split("[" + System.lineSeparator() + "]+"); + assertTrue(lines.length > 0, "Option --list has output."); + assertTrue(lines[0].startsWith("jimage: " + getImagePath()), + "Output should start with jimage path."); + + List modules = Stream.of(lines) + .filter(s -> s.startsWith("Module: ")) + .map(s -> s.substring(s.indexOf(':') + 1).trim()) + .collect(Collectors.toList()); + assertTrue(modules.size() > 0, "Image contains at least one module."); + assertTrue(modules.indexOf("java.base") > 0, "Module java.base found."); + + Set entries = Stream.of(lines) + .filter(s -> { return !s.startsWith("Module: ") && !s.startsWith("Offset"); }) + // Offset \d+ Size \d+ Compressed \d+ Entry \.* + .filter(s -> !s.matches("\\s+\\d+\\s+\\d+\\s+\\d+\\s+.*")) + .collect(Collectors.toSet()); + assertEquals(entries, new HashSet<>() {{ add("jimage: " + getImagePath()); }}, + "All entries should be in format: Offset Size Compressed Entry"); + }); + } + + public void testListIncludeAllWithGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllGlob = jimage("list", "--include", "**", getImagePath()).assertSuccess(); + assertEquals(listAllGlob.output, listAll.output, "--include ** should produce the same output"); + } + + public void testListIncludeWithGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/util/zip")) + .collect(Collectors.toSet()); + + JImageResult listJavaUtil = jimage("list", "--include", "/java.base/java/util/zip/**", getImagePath()).assertSuccess(); + Set actual = Stream.of(listJavaUtil.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(actual, expected, "All java.util.zip classes are listed"); + } + + public void testListIncludeNoMatchWithGlob() { + JImageResult listNotMatching = jimage("list", "--include", "not_matching", getImagePath()).assertSuccess(); + Set entries = Stream.of(listNotMatching.output.split("["+ System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(entries, Collections.emptySet(), "No java.util classes are listed"); + } + + public void testListIncludeAllWithExplicitGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllGlob = jimage("list", "--include", "glob:**", getImagePath()).assertSuccess(); + assertEquals(listAllGlob.output, listAll.output, "--include glob:** should produce the same output"); + } + + public void testListIncludeAllWithRegex() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllRegex = jimage("list", "--include", "regex:.*", getImagePath()).assertSuccess(); + assertEquals(listAllRegex.output, listAll.output, "--include regex:.* should produce the same output"); + } + + public void testListIncludeWithRegex() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/text/")) + .collect(Collectors.toSet()); + assertFalse(expected.isEmpty(), "There should be classes from java.text package"); + + JImageResult listJavaText = jimage("list", "--include", "regex:/java.base/java/text/.*", getImagePath()).assertSuccess(); + Set actual = Stream.of(listJavaText.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + + assertEquals(actual, expected, "All java.text classes are listed"); + } + + public void testListIncludeNoMatchWithRegex() { + JImageResult listNotMatching = jimage("list", "--include", "regex:not_matching", + getImagePath()).assertSuccess(); + Set entries = Stream.of(listNotMatching.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(entries, Collections.emptySet(), "No classes are listed"); + } + + public void testListIncludeMultiplePatterns() throws IOException { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/time/") || s.startsWith("java/util/zip")) + .collect(Collectors.toSet()); + assertFalse(expected.isEmpty(), "There should be classes from java.time and java.io packages"); + + JImageResult listMatched = jimage("list", "--include", "glob:/java.base/java/time/**,regex:/java.base/java/util/zip/.*", + getImagePath()).assertSuccess(); + Set actual = Stream.of(listMatched.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + + assertEquals(actual, expected, "All java.time and java.util.zip classes are listed"); + } + + public void testListNoImageSpecified() { + jimage("list", "") + .assertFailure() + .assertShowsError(); + } + + public void testListEmptyFile() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "empty_file"); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + Files.write(tmp, "This is not an image".getBytes()); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListWithUnknownOption() { + jimage("list", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageListTest().runTests(); + } +} + diff --git a/jdk/test/tools/jimage/JImageToolTest.java b/jdk/test/tools/jimage/JImageToolTest.java index da6cb9f740e..c508eba0cfc 100644 --- a/jdk/test/tools/jimage/JImageToolTest.java +++ b/jdk/test/tools/jimage/JImageToolTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test * @library /lib/testlibrary - * @build jdk.testlibrary.* - * @summary Test to see if jimage tool extracts and recreates correctly. + * @build jdk.testlibrary.ProcessTools + * @summary Test to check if jimage tool exists and is working * @run main/timeout=360 JImageToolTest */ @@ -42,7 +42,7 @@ import jdk.testlibrary.ProcessTools; public class JImageToolTest { private static void jimage(String... jimageArgs) throws Exception { ArrayList args = new ArrayList<>(); - args.add("-ms8m"); + args.add("-ms64m"); args.add("jdk.tools.jimage.Main"); args.addAll(Arrays.asList(jimageArgs)); @@ -61,11 +61,7 @@ public class JImageToolTest { if (Files.exists(jimagePath) && Files.exists(modulesimagePath)) { String jimage = jimagePath.toAbsolutePath().toString(); - String bootimage = modulesimagePath.toAbsolutePath().toString(); - String extractDir = Paths.get(".", "extract").toAbsolutePath().toString(); - jimage("list", bootimage); - jimage("verify", bootimage); - jimage("extract", "--dir", extractDir, bootimage); + jimage("--version"); System.out.println("Test successful"); } else { System.out.println("Test skipped, not an images build"); diff --git a/jdk/test/tools/jimage/JImageVerifyTest.java b/jdk/test/tools/jimage/JImageVerifyTest.java new file mode 100644 index 00000000000..bb763c45704 --- /dev/null +++ b/jdk/test/tools/jimage/JImageVerifyTest.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'verify' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageVerifyTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; + +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageVerifyTest extends JImageCliTest { + + public void testVerify() { + jimage("verify", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.startsWith("jimage: " + getImagePath()), + "Contains verified image's path"); + }); + } + + public void testVerifyHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("verify", opt) + .assertSuccess() + .resultChecker(r -> { + // verify - descriptive text + assertMatches("\\s+verify\\s+-\\s+.*", r.output); + }); + } + } + + public void testVerifyImageNotSpecified() { + jimage("verify", "") + .assertFailure() + .assertShowsError(); + } + + public void testVerifyNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + jimage("verify", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testVerifyNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("verify", "") + .assertFailure() + .assertShowsError(); + } + + public void testVerifyWithUnknownOption() { + jimage("verify", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageVerifyTest().runTests(); + } + +} From 97761183393399f3d8c565343646cb7153d08c9e Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Fri, 18 Nov 2016 15:33:30 +0300 Subject: [PATCH 062/402] 8169658: TESTBUG: javax/rmi tests have undeclared dependencies Reviewed-by: rriggs --- .../PortableRemoteObject/8146975/RmiIiopReturnValueTest.java | 2 ++ .../javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java index 8ab76ca3e95..38f2c519845 100644 --- a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java +++ b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java @@ -27,6 +27,8 @@ * @key intermittent * @summary test RMI-IIOP with value object return * @modules java.corba + * java.naming + * java.rmi * @library /lib/testlibrary * @build jdk.testlibrary.* * @compile Test.java Test3.java Test4.java diff --git a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java index 4d2d279c995..998a66ab954 100644 --- a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java +++ b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java @@ -27,6 +27,8 @@ * @summary test RMI-IIOP call with ConcurrentHashMap as an argument * @library /lib/testlibrary * @modules java.corba + * java.naming + * java.rmi * @build jdk.testlibrary.* * @compile Test.java HelloInterface.java HelloServer.java HelloClient.java * HelloImpl.java _HelloImpl_Tie.java _HelloInterface_Stub.java ConcurrentHashMapTest.java From 709d9ee9d027d4983ce4a399a3fc733213ad00fe Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Sat, 19 Nov 2016 12:22:35 +0100 Subject: [PATCH 063/402] 8169993: Class::desiredAssertionStatus should call getClassLoader0 Reviewed-by: psandoz --- jdk/src/java.base/share/classes/java/lang/Class.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/java/lang/Class.java b/jdk/src/java.base/share/classes/java/lang/Class.java index 16949ed5057..36d458720c0 100644 --- a/jdk/src/java.base/share/classes/java/lang/Class.java +++ b/jdk/src/java.base/share/classes/java/lang/Class.java @@ -3434,7 +3434,7 @@ public final class Class implements java.io.Serializable, * @since 1.4 */ public boolean desiredAssertionStatus() { - ClassLoader loader = getClassLoader(); + ClassLoader loader = getClassLoader0(); // If the loader is null this is a system class, so ask the VM if (loader == null) return desiredAssertionStatus0(this); From 671d12ce6b3aed7a63fd734e484bd63f6dca588c Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Sun, 20 Nov 2016 07:57:57 -0800 Subject: [PATCH 064/402] 8169909: java agent fails to add to class path when the initial module is a named module Reviewed-by: alanb --- .../jdk/internal/loader/ClassLoaders.java | 4 +- .../modules/AppendToClassPathModuleTest.java | 59 ++++++++++ .../modules/AppendToClassPathModuleTest.sh | 67 ++++++++++++ .../modules/src/test/jdk/test/Main.java | 43 ++++++++ .../modules/src/test/module-info.java | 25 +++++ .../modules/classpath/JavaClassPathTest.java | 101 +++++++++++++++--- .../classpath/src/m/jdk/test/Main.java | 9 +- 7 files changed, 290 insertions(+), 18 deletions(-) create mode 100644 jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java create mode 100644 jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh create mode 100644 jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java create mode 100644 jdk/test/java/lang/instrument/modules/src/test/module-info.java diff --git a/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java b/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java index 7ed01991bb1..64492508dc0 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java +++ b/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java @@ -72,13 +72,13 @@ public class ClassLoaders { // If neither is specified then default to -cp // If -cp is not specified and -m is specified, the value of // java.class.path is an empty string, then no class path. - URLClassPath ucp = null; + URLClassPath ucp = new URLClassPath(new URL[0]); String mainMid = System.getProperty("jdk.module.main"); String cp = System.getProperty("java.class.path"); if (cp == null) cp = ""; if (mainMid == null || cp.length() > 0) - ucp = toURLClassPath(cp); + addClassPathToUCP(cp, ucp); // create the class loaders BOOT_LOADER = new BootClassLoader(bcp); diff --git a/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java new file mode 100644 index 00000000000..78c5e615330 --- /dev/null +++ b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8169909 + * @library src /lib/testlibrary + * @build test/* + * @run shell AppendToClassPathModuleTest.sh + * @run main AppendToClassPathModuleTest + */ + +import java.util.Map; +import static jdk.testlibrary.ProcessTools.*; + +/** + * Launch a modular test with no class path and no CLASSPATH set. + * The java agent appends to the "hidden" directory to the class path + * at runtime. + */ +public class AppendToClassPathModuleTest { + public static void main(String... args) throws Throwable { + String modulepath = System.getProperty("test.module.path"); + ProcessBuilder pb = + createJavaProcessBuilder("-javaagent:Agent.jar", + "--module-path", modulepath, + "-m", "test/jdk.test.Main"); + + // remove CLASSPATH environment variable + Map env = pb.environment(); + String value = env.remove("CLASSPATH"); + + int exitCode = executeCommand(pb).getExitValue(); + if (exitCode != 0) { + throw new RuntimeException("Test failed: " + exitCode); + } + } + +} diff --git a/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh new file mode 100644 index 00000000000..5937acba058 --- /dev/null +++ b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh @@ -0,0 +1,67 @@ +#!/bin/sh + +# +# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +if [ "${TESTSRC}" = "" ] +then + echo "TESTSRC not set. Test cannot execute. Failed." + exit 1 +fi +echo "TESTSRC=${TESTSRC}" + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." + exit 1 +fi +echo "TESTJAVA=${TESTJAVA}" + +if [ "${COMPILEJAVA}" = "" ] +then + COMPILEJAVA="${TESTJAVA}" +fi +echo "COMPILEJAVA=${COMPILEJAVA}" + +if [ "${TESTCLASSES}" = "" ] +then + echo "TESTCLASSES not set. Test cannot execute. Failed." + exit 1 +fi + +echo "TESTCLASSES=${TESTCLASSES}" + +mkdir -p hidden +${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ + -d hidden ${TESTSRC}/../ExampleForClassPath.java + +mkdir -p classes +${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ + -d classes ${TESTSRC}/../InstrumentationHandoff.java + +echo "Manifest-Version: 1.0" > Agent.mf +echo "Class-Path: hidden/" >> Agent.mf +echo "Premain-Class: InstrumentationHandoff" >> Agent.mf + +${TESTJAVA}/bin/jar ${TESTTOOLVMOPTS} cvfm Agent.jar \ + Agent.mf -C classes InstrumentationHandoff.class diff --git a/jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java b/jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java new file mode 100644 index 00000000000..94b05e41712 --- /dev/null +++ b/jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test; + +/** + * Launched by AppendToClassPathModuleTest. + */ +public class Main { + public static void main(String... args) throws Exception { + // "java.class.path" system property is expected to be empty. + String value = System.getProperty("java.class.path"); + if (!value.isEmpty()) { + throw new RuntimeException("Non-empty java.class.path=" + value); + } + + // load the "hidden" class that should be loaded by the system loader + Class c = Class.forName("ExampleForClassPath"); + if (c.getClassLoader() != ClassLoader.getSystemClassLoader()) { + throw new RuntimeException(c + " loaderd by " + c.getClassLoader()); + } + } +} diff --git a/jdk/test/java/lang/instrument/modules/src/test/module-info.java b/jdk/test/java/lang/instrument/modules/src/test/module-info.java new file mode 100644 index 00000000000..92ea019a3eb --- /dev/null +++ b/jdk/test/java/lang/instrument/modules/src/test/module-info.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +module test { +} diff --git a/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java b/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java index 72afcb06fc0..634a27fa95c 100644 --- a/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java +++ b/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java @@ -21,12 +21,14 @@ * questions. */ +import java.io.BufferedWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.spi.ToolProvider; import jdk.testlibrary.OutputAnalyzer; import org.testng.annotations.BeforeTest; @@ -42,6 +44,7 @@ import static jdk.testlibrary.ProcessTools.*; * @summary Test the default class path if -Djava.class.path is set * @library /lib/testlibrary * @modules jdk.compiler + * jdk.jartool * @build CompilerUtils jdk.testlibrary.* * @run testng JavaClassPathTest */ @@ -50,6 +53,7 @@ public class JavaClassPathTest { private static final Path SRC_DIR = Paths.get(System.getProperty("test.src"), "src"); private static final Path MODS_DIR = Paths.get("mods"); + private static final Path LIB_DIR = Paths.get("lib"); private static final String TEST_MODULE = "m"; private static final String TEST_MAIN = "jdk.test.Main"; @@ -66,27 +70,47 @@ public class JavaClassPathTest { Path res = Paths.get("jdk/test/res.properties"); Files.createFile(res); + + ToolProvider jartool = ToolProvider.findFirst("jar").orElseThrow( + () -> new RuntimeException("jar tool not found") + ); + + Path jarfile = LIB_DIR.resolve("m.jar"); + Files.createDirectories(LIB_DIR); + assertTrue(jartool.run(System.out, System.err, "cfe", + jarfile.toString(), TEST_MAIN, + file.toString()) == 0); + + Path manifest = LIB_DIR.resolve("manifest"); + try (BufferedWriter writer = Files.newBufferedWriter(manifest)) { + writer.write("CLASS-PATH: lib/m.jar"); + } + jarfile = LIB_DIR.resolve("m1.jar"); + assertTrue(jartool.run(System.out, System.err, "cfme", + jarfile.toString(), manifest.toString(), TEST_MAIN, + file.toString()) == 0); } @DataProvider(name = "classpath") public Object[][] classpath() { return new Object[][]{ // true indicates that class path default to current working directory - { "", true }, - { "-Djava.class.path", true }, - { "-Djava.class.path=", true }, - { "-Djava.class.path=.", true }, + { "", "." }, + { "-Djava.class.path", "." }, + { "-Djava.class.path=", "" }, + { "-Djava.class.path=.", "." }, }; } @Test(dataProvider = "classpath") - public void testUnnamedModule(String option, boolean expected) throws Throwable { + public void testUnnamedModule(String option, String expected) throws Throwable { List args = new ArrayList<>(); if (!option.isEmpty()) { args.add(option); } args.add(TEST_MAIN); - args.add(Boolean.toString(expected)); + args.add(Boolean.toString(true)); + args.add(expected); assertTrue(execute(args).getExitValue() == 0); } @@ -95,15 +119,14 @@ public class JavaClassPathTest { public Object[][] moduleAndClassPath() { return new Object[][]{ // true indicates that class path default to current working directory - { "", false }, - { "-Djava.class.path", false }, - { "-Djava.class.path=", false }, - { "-Djava.class.path=.", true }, + { "", "" }, + { "-Djava.class.path", "" }, + { "-Djava.class.path=", "" }, }; } @Test(dataProvider = "moduleAndClassPath") - public void testNamedModule(String option, boolean expected) throws Throwable { + public void testNamedModule(String option, String expected) throws Throwable { List args = new ArrayList<>(); if (!option.isEmpty()) { args.add(option); @@ -112,7 +135,61 @@ public class JavaClassPathTest { args.add(MODS_DIR.toString()); args.add("-m"); args.add(TEST_MODULE + "/" + TEST_MAIN); - args.add(Boolean.toString(expected)); + // not default to CWD + args.add(Boolean.toString(false)); + args.add(expected); + + + assertTrue(execute(args).getExitValue() == 0); + } + + @Test + public void testClassPath() throws Throwable { + List args = new ArrayList<>(); + args.add("-Djava.class.path=."); + args.add("--module-path"); + args.add(MODS_DIR.toString()); + args.add("-m"); + args.add(TEST_MODULE + "/" + TEST_MAIN); + args.add(Boolean.toString(true)); + args.add("."); + + assertTrue(execute(args).getExitValue() == 0); + } + + @Test + public void testJAR() throws Throwable { + String jarfile = LIB_DIR.resolve("m.jar").toString(); + List args = new ArrayList<>(); + args.add("-jar"); + args.add(jarfile); + args.add(Boolean.toString(false)); + args.add(jarfile); + + assertTrue(execute(args).getExitValue() == 0); + } + + /* + * Test CLASS-PATH attribute in manifest + */ + @Test + public void testClassPathAttribute() throws Throwable { + String jarfile = LIB_DIR.resolve("m1.jar").toString(); + + List args = new ArrayList<>(); + args.add("-jar"); + args.add(jarfile); + args.add(Boolean.toString(false)); + args.add(jarfile); + + assertTrue(execute(args).getExitValue() == 0); + + args.clear(); + args.add("-cp"); + args.add(jarfile); + args.add(TEST_MAIN); + args.add(Boolean.toString(false)); + args.add(jarfile); assertTrue(execute(args).getExitValue() == 0); } diff --git a/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java b/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java index 41e7cd8717d..8a6c671ae89 100644 --- a/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java +++ b/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java @@ -29,13 +29,14 @@ public class Main { static final String JAVA_CLASS_PATH = "java.class.path"; public static void main(String[] args) throws Exception { + boolean expected = args[0].equals("true"); + String cpath = args.length > 1 ? args[1] : ""; String value = System.getProperty(JAVA_CLASS_PATH); - if (value == null) { - throw new RuntimeException(JAVA_CLASS_PATH + " is expected non-null" + - " for compatibility"); + if (!value.equals(cpath)) { + throw new RuntimeException(JAVA_CLASS_PATH + "=" + value + + " expected=" + cpath); } - boolean expected = args[0].equals("true"); ClassLoader loader = ClassLoader.getSystemClassLoader(); URL url = loader.getResource("jdk/test/res.properties"); if ((expected && url == null) || (!expected && url != null)) { From 177ea1a2defc0a44160566a173365bf3c6615cf4 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Sun, 20 Nov 2016 17:39:09 -0800 Subject: [PATCH 065/402] 8168975: java/rmi/activation/Activatable tests fail due to "Port already in use" in RMID.restart() Reviewed-by: rriggs, chegar, darcy --- .../checkActivateRef/rmid.security.policy | 2 + .../checkAnnotations/rmid.security.policy | 2 + .../checkImplClassLoader/rmid.security.policy | 2 + .../checkRegisterInLog/rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../forceLogSnapshot/rmid.security.policy | 2 + .../inactiveGroup/rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../nestedActivate/rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../rmid.security.policy | 2 + .../restartLatecomer/rmid.security.policy | 2 + .../restartService/rmid.security.policy | 2 + .../shutdownGracefully/rmid.security.policy | 2 + .../unregisterInactive/rmid.security.policy | 2 + .../activateFails/rmid.security.policy | 2 + .../modifyDescriptor/ModifyDescriptor.java | 5 +- .../modifyDescriptor/rmid.security.policy | 4 ++ jdk/test/java/rmi/testlibrary/RMID.java | 57 +++++++++++++++---- .../rmi/testlibrary/RMIDSelectorProvider.java | 34 ++++++++++- 22 files changed, 121 insertions(+), 15 deletions(-) diff --git a/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy index cdf9ca15fae..4ca2dd3fbbd 100644 --- a/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy @@ -4,4 +4,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.rmi.server.useDynamicProxies=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy index 53ed1f0bd93..586dd8efc1b 100644 --- a/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy @@ -4,4 +4,6 @@ grant { permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy index c488914b790..69c222e3e63 100644 --- a/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy @@ -1,4 +1,6 @@ grant { permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy index 0471fc80946..b8a10fa78ae 100644 --- a/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy index b1f98628cf8..30b4e537750 100644 --- a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy @@ -4,4 +4,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Ddummyname=dummyvalue"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy index ca4b8e244d9..fd9ccf3da7b 100644 --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy @@ -3,4 +3,6 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java index 1675a7275c8..3e7798c687c 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,8 +33,9 @@ * java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport * java.rmi/sun.rmi.transport.tcp + * java.base/sun.nio.ch * @build TestLibrary RMID ActivationLibrary - * ActivateMe ModifyDescriptor_Stub + * ActivateMe ModifyDescriptor_Stub RMIDSelectorProvider * @run main/othervm/policy=security.policy/timeout=240 ModifyDescriptor */ diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy index f2d3e2c7795..0e94162f0bd 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy @@ -3,4 +3,8 @@ grant { permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission com.sun.rmi.rmid.ExecOptionPermission "-Dtest.message=hello"; permission com.sun.rmi.rmid.ExecOptionPermission "-Dtest.message=hello, again"; + permission java.lang.RuntimePermission "selectorProvider"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff --git a/jdk/test/java/rmi/testlibrary/RMID.java b/jdk/test/java/rmi/testlibrary/RMID.java index f83225f4d43..07628fb2358 100644 --- a/jdk/test/java/rmi/testlibrary/RMID.java +++ b/jdk/test/java/rmi/testlibrary/RMID.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ import java.io.*; import java.rmi.*; import java.rmi.activation.*; import java.rmi.registry.*; +import java.time.LocalTime; import java.util.concurrent.TimeoutException; /** @@ -44,6 +45,15 @@ public class RMID extends JavaVM { private static final long STARTTIME_MS = 15_000L; private static final long POLLTIME_MS = 100L; + // when restart rmid, it may take more time than usual because of + // "port in use" by a possible interloper (check JDK-8168975), + // so need to set a longer timeout for restart. + private static long restartTimeout; + // Same reason to inheritedChannel in RMIDSelectorProvider. + // Put it here rather than in RMIDSelectorProvider to adjust + // both timeout values together. + private static long inheritedChannelTimeout; + private static final String SYSTEM_NAME = ActivationSystem.class.getName(); // "java.rmi.activation.ActivationSystem" @@ -73,7 +83,8 @@ public class RMID extends JavaVM { } /** make test options and arguments */ - private static String makeOptions(int port, boolean debugExec) { + private static String makeOptions(int port, boolean debugExec, + boolean enableSelectorProvider) { String options = " -Dsun.rmi.server.activation.debugExec=" + debugExec; @@ -98,12 +109,24 @@ public class RMID extends JavaVM { // to avoid spurious timeouts on slow machines. options += " -Dsun.rmi.activation.execTimeout=60000"; - if (port == 0) { + // It's important to set handshakeTimeout to small value, for example + // 5 sec (default is 60 sec) to avoid wasting too much time when + // calling lookupSystem(port) in restart(), because + // 1. If use default value of this option, it will take about 2 minutes + // to finish lookupSystem(port) in 2 loops in restart(); + // 2. If set this option as 5 sec then lookupSystem(port) will return + // very quickly. + options += " -Dsun.rmi.transport.tcp.handshakeTimeout=5000"; + + if (port == 0 || enableSelectorProvider) { // Ephemeral port, so have the rmid child process create the // server socket channel and report its port number, over stdin. options += " -classpath " + TestParams.testClassPath; options += " --add-exports=java.base/sun.nio.ch=ALL-UNNAMED"; options += " -Djava.nio.channels.spi.SelectorProvider=RMIDSelectorProvider"; + options += " -Dtest.java.rmi.testlibrary.RMIDSelectorProvider.port=" + port; + options += " -Dtest.java.rmi.testlibrary.RMIDSelectorProvider.timeout=" + + inheritedChannelTimeout; // Disable redirection of System.err to /tmp options += " -Dsun.rmi.server.activation.disableErrRedirect=true"; @@ -112,6 +135,10 @@ public class RMID extends JavaVM { return options; } + private static String makeArgs() { + return makeArgs(false, 0); + } + private static String makeArgs(boolean includePortArg, int port) { String propagateManager = null; @@ -183,7 +210,7 @@ public class RMID extends JavaVM { boolean debugExec, boolean includePortArg, int port) { - String options = makeOptions(port, debugExec); + String options = makeOptions(port, debugExec, false); String args = makeArgs(includePortArg, port); RMID rmid = new RMID("sun.rmi.server.Activation", options, args, out, err, port); @@ -193,14 +220,14 @@ public class RMID extends JavaVM { } public static RMID createRMIDOnEphemeralPort() { - return createRMID(System.out, System.err, true, true, 0); + return createRMID(System.out, System.err, true, false, 0); } public static RMID createRMIDOnEphemeralPort(OutputStream out, OutputStream err, boolean debugExec) { - return createRMID(out, err, debugExec, true, 0); + return createRMID(out, err, debugExec, false, 0); } @@ -213,6 +240,9 @@ public class RMID extends JavaVM { { super(classname, options, args, out, err); this.port = port; + long waitTime = (long)(240_000 * TestLibrary.getTimeoutFactor()); + restartTimeout = (long)(waitTime * 0.9); + inheritedChannelTimeout = (long)(waitTime * 0.8); } /** @@ -280,11 +310,11 @@ public class RMID extends JavaVM { // if rmid is already running, then the test will fail with // a well recognized exception (port already in use...). - mesg("Starting rmid on port " + port + "."); + mesg("Starting rmid on port " + port + ", at " + LocalTime.now()); int p = super.startAndGetPort(); if (p != -1) port = p; - mesg("Started rmid on port " + port + "."); + mesg("Started rmid on port " + port + ", at " + LocalTime.now()); // int slopFactor = 1; // try { @@ -318,6 +348,7 @@ public class RMID extends JavaVM { // The rmid process is alive; check to see whether // it responds to a remote call. + mesg("looking up activation system, at " + LocalTime.now()); if (lookupSystem(port) != null) { /* * We need to set the java.rmi.activation.port value as the @@ -328,10 +359,11 @@ public class RMID extends JavaVM { */ System.setProperty("java.rmi.activation.port", Integer.toString(port)); mesg("Started successfully after " + - (System.currentTimeMillis() - startTime) + "ms."); + (System.currentTimeMillis() - startTime) + "ms, at " + LocalTime.now()); return; } + mesg("after fail to looking up activation system, at " + LocalTime.now()); if (System.currentTimeMillis() > deadline) { TestLibrary.bomb("Failed to start rmid, giving up after " + (System.currentTimeMillis() - startTime) + "ms.", null); @@ -347,9 +379,10 @@ public class RMID extends JavaVM { */ public void restart() throws IOException { destroy(); - options = makeOptions(port, true); - args = makeArgs(true, port); - start(); + options = makeOptions(port, true, true); + args = makeArgs(); + + start(restartTimeout); } /** diff --git a/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java b/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java index 4b9f09264d7..d837ebce6fc 100644 --- a/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java +++ b/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java @@ -22,6 +22,7 @@ */ import java.io.*; +import java.net.BindException; import java.net.InetSocketAddress; import java.net.ProtocolFamily; import java.nio.channels.Channel; @@ -31,6 +32,7 @@ import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.AbstractSelector; import java.nio.channels.spi.SelectorProvider; +import java.time.LocalTime; import static java.net.StandardSocketOptions.SO_REUSEADDR; import static java.net.StandardSocketOptions.SO_REUSEPORT; @@ -98,7 +100,37 @@ public class RMIDSelectorProvider extends SelectorProvider { channel.setOption(SO_REUSEPORT, true); } - channel.bind(new InetSocketAddress(0)); + // when it comes here, these properties should have been set with + // a valid value, but assign a default value anyway. + long timeout = Long.getLong( + "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", + 200_000); + long deadline = System.currentTimeMillis() + timeout; + int port = Integer.getInteger( + "test.java.rmi.testlibrary.RMIDSelectorProvider.port", 0); + while (true) { + try { + channel.bind(new InetSocketAddress(port)); + break; + } catch (BindException ex) { + System.out.format("RMIDSelectorProvider: " + + "failed to bind to port %d due to \"%s\", at %s%n", + port, ex.getMessage(), LocalTime.now()); + } + if (System.currentTimeMillis() > deadline) { + System.out.format("RMIDSelectorProvider: " + + "fail to bind to port %d after trying for " + + "%d seconds, exiting rmid process, at %s%n", + port, timeout/1000, LocalTime.now()); + channel.close(); + // can not start rmid on specific port, + // there is no need to continue run rmid. + System.exit(1); + } + try { + Thread.sleep(1000); + } catch(InterruptedException ignore) { } + } System.out.println(RMID.EPHEMERAL_MSG + channel.socket().getLocalPort()); } From 86bd9c2fd3a7f33d9119779c2cb209777d1a9c3e Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Gopularam Date: Mon, 21 Nov 2016 06:04:25 +0000 Subject: [PATCH 066/402] 8066291: Return unmodifiable set of zone IDs to optimize ZoneIdPrinterParser Cache the available zones to speed up parsing Reviewed-by: rriggs, scolebourne --- .../share/classes/java/time/ZoneId.java | 5 +++-- .../java/time/zone/ZoneRulesProvider.java | 16 ++++++++++++---- .../tck/java/time/zone/TCKZoneRulesProvider.java | 11 ++++++----- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/time/ZoneId.java b/jdk/src/java.base/share/classes/java/time/ZoneId.java index 5087888da4f..d3aa95b6443 100644 --- a/jdk/src/java.base/share/classes/java/time/ZoneId.java +++ b/jdk/src/java.base/share/classes/java/time/ZoneId.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,6 +76,7 @@ import java.time.temporal.UnsupportedTemporalTypeException; import java.time.zone.ZoneRules; import java.time.zone.ZoneRulesException; import java.time.zone.ZoneRulesProvider; +import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Objects; @@ -284,7 +285,7 @@ public abstract class ZoneId implements Serializable { * @return a modifiable copy of the set of zone IDs, not null */ public static Set getAvailableZoneIds() { - return ZoneRulesProvider.getAvailableZoneIds(); + return new HashSet(ZoneRulesProvider.getAvailableZoneIds()); } //----------------------------------------------------------------------- diff --git a/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java b/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java index 8e91eae0bbd..4014c23c083 100644 --- a/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java +++ b/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,6 +77,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.Collections; /** * Provider of time-zone rules to the system. @@ -137,6 +138,11 @@ public abstract class ZoneRulesProvider { */ private static final ConcurrentMap ZONES = new ConcurrentHashMap<>(512, 0.75f, 2); + /** + * The zone ID data + */ + private static volatile Set ZONE_IDS; + static { // if the property java.time.zone.DefaultZoneRulesProvider is // set then its value is the class name of the default provider @@ -194,10 +200,10 @@ public abstract class ZoneRulesProvider { *

    * These IDs are the string form of a {@link ZoneId}. * - * @return a modifiable copy of the set of zone IDs, not null + * @return the unmodifiable set of zone IDs, not null */ public static Set getAvailableZoneIds() { - return new HashSet<>(ZONES.keySet()); + return ZONE_IDS; } /** @@ -303,7 +309,7 @@ public abstract class ZoneRulesProvider { * @param provider the provider to register, not null * @throws ZoneRulesException if unable to complete the registration */ - private static void registerProvider0(ZoneRulesProvider provider) { + private static synchronized void registerProvider0(ZoneRulesProvider provider) { for (String zoneId : provider.provideZoneIds()) { Objects.requireNonNull(zoneId, "zoneId"); ZoneRulesProvider old = ZONES.putIfAbsent(zoneId, provider); @@ -313,6 +319,8 @@ public abstract class ZoneRulesProvider { ", currently loading from provider: " + provider); } } + Set combinedSet = new HashSet(ZONES.keySet()); + ZONE_IDS = Collections.unmodifiableSet(combinedSet); } /** diff --git a/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java b/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java index a30424f4572..f51bb396f50 100644 --- a/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java +++ b/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -91,10 +91,11 @@ public class TCKZoneRulesProvider { public void test_getAvailableGroupIds() { Set zoneIds = ZoneRulesProvider.getAvailableZoneIds(); assertEquals(zoneIds.contains("Europe/London"), true); - zoneIds.clear(); - assertEquals(zoneIds.size(), 0); - Set zoneIds2 = ZoneRulesProvider.getAvailableZoneIds(); - assertEquals(zoneIds2.contains("Europe/London"), true); + } + + @Test(expectedExceptions=UnsupportedOperationException.class) + public void test_getAvailableGroupIds_modifyZoneId() { + ZoneRulesProvider.getAvailableZoneIds().clear(); } //----------------------------------------------------------------------- From 87e6723568dc040b8545196e98b5103daf3f3bb0 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Sun, 20 Nov 2016 23:19:54 -0800 Subject: [PATCH 067/402] 8170062: Problem list java/lang/ClassLoader/platformClassLoader/DefinePlatformClass.java Reviewed-by: darcy --- jdk/test/ProblemList.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 6a6571c58a4..d2731c6a46a 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -124,6 +124,7 @@ java/beans/Introspector/8132566/OverrideUserDefPropertyInfoTest.java 8132565 gen # jdk_lang java/lang/StringCoding/CheckEncodings.sh 7008363 generic-all +java/lang/ClassLoader/platformClassLoader/DefinePlatformClass.java 8169639 windows-all ############################################################################ From 5ba9f6de7d0e0bf2989783379fab60f7ffdb2723 Mon Sep 17 00:00:00 2001 From: Jim Laskey Date: Mon, 21 Nov 2016 10:08:20 -0400 Subject: [PATCH 068/402] 8168256: Plugin alias options in jlink --help output seems to be in an arbitrary order Reviewed-by: sundar, mchung --- .../classes/jdk/tools/jimage/JImageTask.java | 20 +- .../tools/jimage/resources/jimage.properties | 32 +-- .../jdk/tools/jlink/internal/JlinkTask.java | 2 +- .../jdk/tools/jlink/internal/TaskHelper.java | 200 ++++++++++-------- .../tools/jlink/resources/jlink.properties | 46 ++-- .../tools/jlink/resources/plugins.properties | 25 +-- 6 files changed, 171 insertions(+), 154 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java index 06d86a7653a..344b920a8bf 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java @@ -32,6 +32,7 @@ import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.PathMatcher; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.MissingResourceException; @@ -190,19 +191,12 @@ class JImageTask { if (options.help) { if (unhandled.isEmpty()) { log.println(TASK_HELPER.getMessage("main.usage", PROGNAME)); - - for (Option o : RECOGNIZED_OPTIONS) { - String name = o.aliases()[0]; - - if (name.startsWith("--")) { - name = name.substring(2); - } else if (name.startsWith("-")) { - name = name.substring(1); - } - - log.println(TASK_HELPER.getMessage("main.opt." + name)); - } - + Arrays.asList(RECOGNIZED_OPTIONS).stream() + .filter(option -> !option.isHidden()) + .sorted() + .forEach(option -> { + log.println(TASK_HELPER.getMessage(option.resourceName())); + }); log.println(TASK_HELPER.getMessage("main.opt.footer")); } else { try { diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties index 2b53cf8d64f..13faa3b40e4 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties @@ -60,34 +60,36 @@ error.prefix=Error: warn.prefix=Warning: main.opt.dir=\ -\ --dir Target directory for extract directive +\ --dir Target directory for extract directive main.opt.include=\ -\ --include Pattern list for filtering entries. - -main.opt.footer=\ -\n\ -\For options requiring a , the value will be a comma\ -\ separated list of elements each using one the following forms:\n\ -\ \n\ -\ glob:\n\ -\ regex: - +\ --include Pattern list for filtering entries. main.opt.full-version=\ -\ --full-version Print full version information +\ --full-version Print full version information main.opt.help=\ \ -h, --help Print usage message main.opt.verbose=\ -\ --verbose Listing prints entry size and offset attributes +\ --verbose Listing prints entry size and offset\n\ +\ attributes main.opt.version=\ -\ --version Print version information +\ --version Print version information main.command.files=\ -\ @ Read options from file +\ @ Read options from file + +main.opt.footer=\ +\n\ +\For options requiring a , the value will be a comma separated\n\ +\list of elements each using one the following forms:\n\ +\ \n\ +\ glob:\n\ +\ regex: + + err.not.a.task=task must be one of : {0} err.missing.arg=no value given for {0} diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java index bf7e9e03e55..01876ee5b56 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java @@ -134,7 +134,7 @@ public class JlinkTask { }, true, "--full-version"), new Option(false, (task, opt, arg) -> { task.options.ignoreSigning = true; - }, true, "--ignore-signing-information"),}; + }, "--ignore-signing-information"),}; private static final String PROGNAME = "jlink"; private final OptionsValues options = new OptionsValues(); diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java index 083bf048724..e9b5d885039 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java @@ -46,8 +46,8 @@ import java.util.Map.Entry; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; +import java.util.stream.Stream; -import jdk.tools.jlink.internal.plugins.ExcludeFilesPlugin; import jdk.tools.jlink.internal.plugins.ExcludeJmodSectionPlugin; import jdk.tools.jlink.plugin.Plugin; import jdk.tools.jlink.plugin.Plugin.Category; @@ -90,8 +90,7 @@ public final class TaskHelper { public boolean showUsage; } - public static class Option { - + public static class Option implements Comparable { public interface Processing { void process(T task, String opt, String arg) throws BadArgs; @@ -100,17 +99,34 @@ public final class TaskHelper { final boolean hasArg; final Processing processing; final boolean hidden; - final String[] aliases; + final String name; + final String shortname; + + public Option(boolean hasArg, Processing processing, boolean hidden, String name, String shortname) { + if (!name.startsWith("--")) { + throw new RuntimeException("option name missing --, " + name); + } + if (!shortname.isEmpty() && !shortname.startsWith("-")) { + throw new RuntimeException("short name missing -, " + shortname); + } - public Option(boolean hasArg, Processing processing, boolean hidden, String... aliases) { this.hasArg = hasArg; this.processing = processing; - this.aliases = aliases; this.hidden = hidden; + this.name = name; + this.shortname = shortname; } - public Option(boolean hasArg, Processing processing, String... aliases) { - this(hasArg, processing, false, aliases); + public Option(boolean hasArg, Processing processing, String name, String shortname) { + this(hasArg, processing, false, name, shortname); + } + + public Option(boolean hasArg, Processing processing, boolean hidden, String name) { + this(hasArg, processing, hidden, name, ""); + } + + public Option(boolean hasArg, Processing processing, String name) { + this(hasArg, processing, false, name, ""); } public boolean isHidden() { @@ -118,16 +134,10 @@ public final class TaskHelper { } public boolean matches(String opt) { - for (String a : aliases) { - if (a.equals(opt)) { - return true; - } else if (opt.startsWith("--") - && (hasArg && opt.startsWith(a + "="))) { - return true; - } - } - return false; - } + return opt.equals(name) || + opt.equals(shortname) || + hasArg && opt.startsWith("--") && opt.startsWith(name + "="); + } public boolean ignoreRest() { return false; @@ -137,28 +147,54 @@ public final class TaskHelper { processing.process(task, opt, arg); } - public String[] aliases() { - return aliases; + public String getName() { + return name; + } + + public String resourceName() { + return resourcePrefix() + name.substring(2); + } + + public String getShortname() { + return shortname; + } + + public String resourcePrefix() { + return "main.opt."; + } + + @Override + public int compareTo(Object object) { + if (!(object instanceof Option)) { + throw new RuntimeException("comparing non-Option"); + } + + Option option = (Option)object; + + return name.compareTo(option.name); + } + + } + + private static class PluginOption extends Option { + public PluginOption(boolean hasArg, + Processing processing, boolean hidden, String name, String shortname) { + super(hasArg, processing, hidden, name, shortname); + } + + public PluginOption(boolean hasArg, + Processing processing, boolean hidden, String name) { + super(hasArg, processing, hidden, name, ""); + } + + public String resourcePrefix() { + return "plugin.opt."; } } - private static class PlugOption extends Option { - - public PlugOption(boolean hasArg, - Processing processing, boolean hidden, String... aliases) { - super(hasArg, processing, hidden, aliases); - } - - public PlugOption(boolean hasArg, - Processing processing, String... aliases) { - super(hasArg, processing, aliases); - } - } - - private final class PluginsOptions { + private final class PluginsHelper { private static final String PLUGINS_PATH = "--plugin-module-path"; - private static final String POST_PROCESS = "--post-process-path"; private Layer pluginsLayer = Layer.boot(); private final List plugins; @@ -170,10 +206,10 @@ public final class TaskHelper { // Each such occurrence results in a Map of arguments. So, there could be multiple // args maps per plugin instance. private final Map>> pluginToMaps = new HashMap<>(); - private final List pluginsOptions = new ArrayList<>(); - private final List mainOptions = new ArrayList<>(); + private final List pluginsOptions = new ArrayList<>(); + private final List mainOptions = new ArrayList<>(); - private PluginsOptions(String pp) throws BadArgs { + private PluginsHelper(String pp) throws BadArgs { if (pp != null) { String[] dirs = pp.split(File.pathSeparator); @@ -193,13 +229,13 @@ public final class TaskHelper { addOrderedPluginOptions(plugin, optionsSeen); } } - mainOptions.add(new PlugOption(false, + mainOptions.add(new PluginOption(false, (task, opt, arg) -> { // This option is handled prior // to have the options parsed. }, - "--plugin-module-path")); - mainOptions.add(new PlugOption(true, (task, opt, arg) -> { + false, "--plugin-module-path")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { for (Plugin plugin : plugins) { if (plugin.getName().equals(arg)) { pluginToMaps.remove(plugin); @@ -208,24 +244,24 @@ public final class TaskHelper { } throw newBadArgs("err.no.such.plugin", arg); }, - "--disable-plugin")); - mainOptions.add(new PlugOption(true, (task, opt, arg) -> { + false, "--disable-plugin")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { Path path = Paths.get(arg); if (!Files.exists(path) || !Files.isDirectory(path)) { throw newBadArgs("err.image.must.exist", path); } existingImage = path.toAbsolutePath(); - }, true, POST_PROCESS)); - mainOptions.add(new PlugOption(true, + }, true, "--post-process-path")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { lastSorter = arg; }, true, "--resources-last-sorter")); - mainOptions.add(new PlugOption(false, + mainOptions.add(new PluginOption(false, (task, opt, arg) -> { listPlugins = true; }, - "--list-plugins")); + false, "--list-plugins")); } private List> argListFor(Plugin plugin) { @@ -261,8 +297,8 @@ public final class TaskHelper { } optionsSeen.add(option); - PlugOption plugOption - = new PlugOption(plugin.hasArguments(), + PluginOption plugOption + = new PluginOption(plugin.hasArguments(), (task, opt, arg) -> { if (!Utils.isFunctional(plugin)) { throw newBadArgs("err.provider.not.functional", @@ -312,7 +348,7 @@ public final class TaskHelper { } } }, - "--" + option); + false, "--" + option); pluginsOptions.add(plugOption); if (Utils.isFunctional(plugin)) { @@ -322,44 +358,44 @@ public final class TaskHelper { if (plugin instanceof DefaultCompressPlugin) { plugOption - = new PlugOption(false, + = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(DefaultCompressPlugin.NAME, DefaultCompressPlugin.LEVEL_2); - }, "-c"); + }, false, "--compress", "-c"); mainOptions.add(plugOption); } else if (plugin instanceof StripDebugPlugin) { plugOption - = new PlugOption(false, + = new PluginOption(false, (task, opt, arg) -> { addArgumentMap(plugin); - }, "-G"); + }, false, "--strip-debug", "-G"); mainOptions.add(plugOption); } else if (plugin instanceof ExcludeJmodSectionPlugin) { - plugOption = new PlugOption(false, (task, opt, arg) -> { + plugOption = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(ExcludeJmodSectionPlugin.NAME, ExcludeJmodSectionPlugin.MAN_PAGES); - }, "--no-man-pages"); + }, false, "--no-man-pages"); mainOptions.add(plugOption); - plugOption = new PlugOption(false, (task, opt, arg) -> { + plugOption = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(ExcludeJmodSectionPlugin.NAME, ExcludeJmodSectionPlugin.INCLUDE_HEADER_FILES); - }, "--no-header-files"); + }, false, "--no-header-files"); mainOptions.add(plugOption); } } } - private PlugOption getOption(String name) throws BadArgs { - for (PlugOption o : pluginsOptions) { + private PluginOption getOption(String name) throws BadArgs { + for (PluginOption o : pluginsOptions) { if (o.matches(name)) { return o; } } - for (PlugOption o : mainOptions) { + for (PluginOption o : mainOptions) { if (o.matches(name)) { return o; } @@ -461,7 +497,7 @@ public final class TaskHelper { private String getPluginsPath(String[] args) throws BadArgs { String pp = null; for (int i = 0; i < args.length; i++) { - if (args[i].equals(PluginsOptions.PLUGINS_PATH)) { + if (args[i].equals(PluginsHelper.PLUGINS_PATH)) { if (i == args.length - 1) { throw new BadArgs("err.no.plugins.path").showUsage(true); } else { @@ -498,13 +534,13 @@ public final class TaskHelper { // Must extract it prior to do any option analysis. // Required to interpret custom plugin options. // Unit tests can call Task multiple time in same JVM. - pluginOptions = new PluginsOptions(getPluginsPath(args)); + pluginOptions = new PluginsHelper(getPluginsPath(args)); // First extract plugins path if any String pp = null; List filteredArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { - if (args[i].equals(PluginsOptions.PLUGINS_PATH)) { + if (args[i].equals(PluginsHelper.PLUGINS_PATH)) { if (i == args.length - 1) { throw new BadArgs("err.no.plugins.path").showUsage(true); } else { @@ -529,7 +565,7 @@ public final class TaskHelper { for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { String name = args[i]; - PlugOption pluginOption = null; + PluginOption pluginOption = null; Option option = getOption(name); if (option == null) { pluginOption = pluginOptions.getOption(name); @@ -585,32 +621,13 @@ public final class TaskHelper { } public void showHelp(String progName) { - showHelp(progName, true); - } - - private void showHelp(String progName, boolean showsImageBuilder) { log.println(bundleHelper.getMessage("main.usage", progName)); - for (Option o : options) { - String name = o.aliases[0].substring(1); // there must always be at least one name - name = name.charAt(0) == '-' ? name.substring(1) : name; - if (o.isHidden() || name.equals("h")) { - continue; - } - log.println(bundleHelper.getMessage("main.opt." + name)); - } - - for (Option o : pluginOptions.mainOptions) { - if (o.aliases[0].equals(PluginsOptions.POST_PROCESS) - && !showsImageBuilder) { - continue; - } - String name = o.aliases[0].substring(1); // there must always be at least one name - name = name.charAt(0) == '-' ? name.substring(1) : name; - if (o.isHidden()) { - continue; - } - log.println(bundleHelper.getMessage("plugin.opt." + name)); - } + Stream.concat(options.stream(), pluginOptions.mainOptions.stream()) + .filter(option -> !option.isHidden()) + .sorted() + .forEach(option -> { + log.println(bundleHelper.getMessage(option.resourceName())); + }); log.println(bundleHelper.getMessage("main.command.files")); } @@ -619,6 +636,7 @@ public final class TaskHelper { log.println("\n" + bundleHelper.getMessage("main.extended.help")); List pluginList = PluginRepository. getPlugins(pluginOptions.pluginsLayer); + for (Plugin plugin : Utils.getSortedPlugins(pluginList)) { showPlugin(plugin, log); } @@ -671,7 +689,7 @@ public final class TaskHelper { } } - private PluginsOptions pluginOptions; + private PluginsHelper pluginOptions; private PrintWriter log; private final ResourceBundleHelper bundleHelper; diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties index 33454bc6ccb..a56c77be18d 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties @@ -24,49 +24,51 @@ # main.usage.summary=\ -Usage: {0} --module-path --add-modules --output \n\ -use --help for a list of possible options +Usage: {0} --module-path --add-modules --output\n\ +\ use --help for a list of possible options main.usage=\ -Usage: {0} --module-path --add-modules --output \n\ -\Possible options include: +Usage: {0} --module-path --add-modules --output +\ Possible options include: error.prefix=Error: warn.prefix=Warning: main.opt.help=\ -\ -h, --help Print this help message +\ -h, --help Print this help message main.opt.version=\ -\ --version Version information +\ --version Version information main.opt.module-path=\ -\ -p \n\ -\ --module-path Module path +\ -p, --module-path Module path main.opt.add-modules=\ -\ --add-modules [,...] Root modules to resolve +\ --add-modules [,...] Root modules to resolve main.opt.limit-modules=\ -\ --limit-modules [,...] Limit the universe of observable modules +\ --limit-modules [,...] Limit the universe of observable\n\ +\ modules main.opt.output=\ -\ --output Location of output path +\ --output Location of output path main.command.files=\ -\ @ Read options from file +\ @ Read options from file main.opt.endian=\ -\ --endian Byte order of generated jimage (default:native) +\ --endian Byte order of generated jimage\n\ +\ (default:native) main.opt.save-opts=\ -\ --save-opts Save jlink options in the given file +\ --save-opts Save jlink options in the given file main.opt.ignore-signing-information=\ -\ --ignore-signing-information Suppress a fatal error when signed modular JARs \ -\ are linked in the image. The signature related \ -\ files of the signed modular JARs are not copied \ -\ to the runtime image. +\ --ignore-signing-information Suppress a fatal error when signed\n\ +\ modular JARs are linked in the image.\n\ +\ The signature related files of the\n\ +\ signed modular JARs are not copied to\n\ +\ the runtime image. main.msg.bug=\ An exception has occurred in jlink. \ @@ -78,13 +80,13 @@ main.extended.help=\ \List of available plugins: main.extended.help.footer=\ -\For options requiring a , the value will be a comma\ -\ separated list of elements each using one the following forms:\n\ +\For options requiring a , the value will be a comma separated\n\ +\list of elements each using one the following forms:\n\ \ \n\ \ glob:\n\ \ regex:\n\ -\ @ where filename is the name of a file containing patterns to be\ -\ used, one pattern per line\n\ +\ @ where filename is the name of a file containing patterns to be\n\ +\ used, one pattern per line\n\ \n\ diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties index 3fcda64dcda..52e4529bc09 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties @@ -132,32 +132,33 @@ plugin.plugins.header=\ List of available plugin options: plugin.opt.list-plugins=\ -\ --list-plugins List available plugins +\ --list-plugins List available plugins plugin.opt.post-process-path=\ -\ --post-process-path Post process an existing image +\ --post-process-path Post process an existing image plugin.opt.resources-last-sorter=\ -\ --resources-last-sorter The last plugin allowed to sort resources +\ --resources-last-sorter The last plugin allowed to sort\n\ +\ resources plugin.opt.plugin-module-path=\ -\ --plugin-module-path Custom plugin module path +\ --plugin-module-path Custom plugin module path plugin.opt.disable-plugin=\ -\ --disable-plugin Disable the plugin mentioned +\ --disable-plugin Disable the plugin mentioned -plugin.opt.c=\ -\ -c, --compress=<0|1|2> Enable compression of resources\ -\n More details in --list-plugins option +plugin.opt.compress=\ +\ -c, --compress=<0|1|2> Enable compression of resources\n\ +\ More details in --list-plugins option -plugin.opt.G=\ -\ -G, --strip-debug Strip debug information +plugin.opt.strip-debug=\ +\ -G, --strip-debug Strip debug information plugin.opt.no-man-pages=\ -\ --no-man-pages Exclude man pages +\ --no-man-pages Exclude man pages plugin.opt.no-header-files=\ -\ --no-header-files Exclude include header files +\ --no-header-files Exclude include header files main.plugin.name=\ \Plugin Name From bf0b3da423b3ee508637611167acd9964c092800 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 21 Nov 2016 07:54:42 -0800 Subject: [PATCH 069/402] 8170112: Problem list failing jimage tests until JDK-8169713 is fixed Reviewed-by: jlaskey --- jdk/test/ProblemList.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index d2731c6a46a..d444dc2cec2 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -255,6 +255,10 @@ tools/pack200/CommandLineTests.java 8059906 generic- tools/launcher/FXLauncherTest.java 8068049 linux-all,macosx-all +tools/jimage/JImageExtractTest.java 8169713 generic-all +tools/jimage/JImageListTest.java 8169713 generic-all +tools/jimage/JImageVerifyTest.java 8169713 generic-all + ############################################################################ # jdk_jdi From 0a45ed3b0fd3abe0cfa956e6556268aef150e5af Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Mon, 21 Nov 2016 19:18:22 +0300 Subject: [PATCH 070/402] 8169721: [TESTBUG] com/sun/jndi tests have undeclared dependency on java.naming module Reviewed-by: rriggs, dfuchs --- jdk/test/com/sun/jndi/dns/CheckAccess.java | 6 ++++-- jdk/test/com/sun/jndi/dns/Test6991580.java | 7 ++++--- jdk/test/com/sun/jndi/ldap/TEST.properties | 1 + .../rmi/registry/RegistryContext/UnbindIdempotent.java | 5 ++++- 4 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 jdk/test/com/sun/jndi/ldap/TEST.properties diff --git a/jdk/test/com/sun/jndi/dns/CheckAccess.java b/jdk/test/com/sun/jndi/dns/CheckAccess.java index 265d99e8ea5..723ee28a983 100644 --- a/jdk/test/com/sun/jndi/dns/CheckAccess.java +++ b/jdk/test/com/sun/jndi/dns/CheckAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,11 +24,13 @@ /* * @test * @bug 6657619 + * @modules jdk.naming.dns * @summary DnsContext.debug is public static mutable (findbugs) * @author Vincent Ryan */ -import java.lang.reflect.*; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; /* * Check that the 'debug' class member is no longer publicly accessible. diff --git a/jdk/test/com/sun/jndi/dns/Test6991580.java b/jdk/test/com/sun/jndi/dns/Test6991580.java index b06f78a23de..b8763bbbd0b 100644 --- a/jdk/test/com/sun/jndi/dns/Test6991580.java +++ b/jdk/test/com/sun/jndi/dns/Test6991580.java @@ -30,13 +30,14 @@ import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -/** +/* * @test * @bug 6991580 8080108 8133035 * @requires os.family != "windows" * @summary IPv6 Nameservers in resolv.conf throws NumberFormatException - * @modules jdk.naming.dns/com.sun.jndi.dns - * @build IPv6NameserverPlatformParsingTest + * @modules java.desktop + * jdk.naming.dns/com.sun.jndi.dns + * @compile --add-modules jdk.naming.dns IPv6NameserverPlatformParsingTest.java * @run main/manual Test6991580 */ diff --git a/jdk/test/com/sun/jndi/ldap/TEST.properties b/jdk/test/com/sun/jndi/ldap/TEST.properties new file mode 100644 index 00000000000..88ac1ce7ea8 --- /dev/null +++ b/jdk/test/com/sun/jndi/ldap/TEST.properties @@ -0,0 +1 @@ +modules = java.naming diff --git a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java index 5709c2b5ca8..74f57678ac8 100644 --- a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java +++ b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * successfully. * @modules java.rmi/sun.rmi.registry java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport java.rmi/sun.rmi.transport.tcp + * jdk.naming.rmi * @library ../../../../../../java/rmi/testlibrary * @build TestLibrary * @run main UnbindIdempotent @@ -49,8 +50,10 @@ public class UnbindIdempotent { try { rctx = (Context)ictx.lookup("rmi://localhost:" + Integer.toString(registryPort)); + System.out.println("Got context: " + rctx.getClass()); } catch (NamingException e) { // Unable to set up for test. + System.err.println("WARNING: The test skipped due to NamingException: " + e); return; } From 924cb72be2930b9c457fa715aa4b460ea2dfe709 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 21 Nov 2016 12:06:10 -0800 Subject: [PATCH 071/402] 8170139: OpenNonIntegralNumberOfSampleframes.java still fails Reviewed-by: smarks --- jdk/test/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index d444dc2cec2..b252d116521 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -228,6 +228,8 @@ javax/sound/sampled/Clip/Drain/ClipDrain.java 7062792 generic-all javax/sound/sampled/Mixers/DisabledAssertionCrash.java 7067310 generic-all +javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java 8168881 generic-all + ############################################################################ # jdk_imageio From d4857ff0f3a25a263cdb6c0059bbae3245a28f23 Mon Sep 17 00:00:00 2001 From: David Dehaven Date: Mon, 7 Nov 2016 12:46:23 -0800 Subject: [PATCH 072/402] 8169289: JavaFX application in named module fails to launch if no main method Reviewed-by: mchung, ksrini --- .../classes/sun/launcher/LauncherHelper.java | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java index 45e781b9b4a..c5d87287a17 100644 --- a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java +++ b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java @@ -462,6 +462,8 @@ public final class LauncherHelper { * This method: * 1. Loads the main class from the module or class path * 2. Checks the public static void main method. + * 3. If the main class extends FX Application then call on FXHelper to + * perform the launch. * * @param printToStderr if set, all output will be routed to stderr * @param mode LaunchMode as determined by the arguments passed on the @@ -479,11 +481,23 @@ public final class LauncherHelper { Class mainClass = (mode == LM_MODULE) ? loadModuleMainClass(what) : loadMainClass(mode, what); - validateMainClass(mainClass); + // record the real main class for UI purposes + // neither method above can return null, they will abort() + appClass = mainClass; - // record main class if not already set - if (appClass == null) - appClass = mainClass; + /* + * Check if FXHelper can launch it using the FX launcher. In an FX app, + * the main class may or may not have a main method, so do this before + * validating the main class. + */ + if (JAVAFX_FXHELPER_CLASS_NAME_SUFFIX.equals(mainClass.getName()) || + doesExtendFXApplication(mainClass)) { + // Will abort() if there are problems with FX runtime + FXHelper.setFXLaunchParameters(what, mode); + mainClass = FXHelper.class; + } + + validateMainClass(mainClass); return mainClass; } @@ -530,7 +544,6 @@ public final class LauncherHelper { String cn = Normalizer.normalize(mainClass, Normalizer.Form.NFC); c = Class.forName(m, cn); - } if (c == null) { abort(null, "java.launcher.module.error2", mainClass, mainModule); @@ -542,8 +555,6 @@ public final class LauncherHelper { /** * Loads the main class from the class path (LM_CLASS or LM_JAR). - * If the main class extends FX Application then call on FXHelper to - * determine the main class to launch. */ private static Class loadMainClass(int mode, String what) { // get the class name @@ -570,7 +581,7 @@ public final class LauncherHelper { if (System.getProperty("os.name", "").contains("OS X") && Normalizer.isNormalized(cn, Normalizer.Form.NFD)) { try { - // On Mac OS X since all names with diacretic symbols are + // On Mac OS X since all names with diacritical marks are // given as decomposed it is possible that main class name // comes incorrectly from the command line and we have // to re-compose it @@ -583,21 +594,6 @@ public final class LauncherHelper { abort(cnfe, "java.launcher.cls.error1", cn); } } - - // record the main class - appClass = mainClass; - - /* - * Check if FXHelper can launch it using the FX launcher. In an FX app, - * the main class may or may not have a main method, so do this before - * validating the main class. - */ - if (JAVAFX_FXHELPER_CLASS_NAME_SUFFIX.equals(mainClass.getName()) || - doesExtendFXApplication(mainClass)) { - // Will abort() if there are problems with FX runtime - FXHelper.setFXLaunchParameters(what, mode); - return FXHelper.class; - } return mainClass; } @@ -773,9 +769,15 @@ public final class LauncherHelper { * java -cp somedir FXClass N/A LM_CLASS "LM_CLASS" * java -jar fxapp.jar Present LM_JAR "LM_JAR" * java -jar fxapp.jar Not Present LM_JAR "LM_JAR" + * java -m module/class [1] N/A LM_MODULE "LM_MODULE" + * java -m module N/A LM_MODULE "LM_MODULE" + * + * [1] - JavaFX-Application-Class is ignored when modular args are used, even + * if present in a modular jar */ private static final String JAVAFX_LAUNCH_MODE_CLASS = "LM_CLASS"; private static final String JAVAFX_LAUNCH_MODE_JAR = "LM_JAR"; + private static final String JAVAFX_LAUNCH_MODE_MODULE = "LM_MODULE"; /* * FX application launcher and launch method, so we can launch @@ -835,6 +837,9 @@ public final class LauncherHelper { case LM_JAR: fxLaunchMode = JAVAFX_LAUNCH_MODE_JAR; break; + case LM_MODULE: + fxLaunchMode = JAVAFX_LAUNCH_MODE_MODULE; + break; default: // should not have gotten this far... throw new InternalError(mode + ": Unknown launch mode"); From f683694e4f7f0c7884ac6f9a921c2e611a285151 Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Tue, 8 Nov 2016 06:22:31 +0000 Subject: [PATCH 073/402] 8169318: Dump the reproduced packet in DTLSOverDatagram.java Reviewed-by: mullan --- jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java b/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java index 10886497267..9c938090750 100644 --- a/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java +++ b/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java @@ -176,7 +176,10 @@ public class DTLSOverDatagram { boolean finished = onReceiveTimeout( engine, peerAddr, side, packets); + log(side, "Reproduced " + packets.size() + " packets"); for (DatagramPacket p : packets) { + printHex("Reproduced packet", + p.getData(), p.getOffset(), p.getLength()); socket.send(p); } @@ -334,7 +337,7 @@ public class DTLSOverDatagram { String side, List packets) throws Exception { boolean endLoops = false; - int loops = MAX_HANDSHAKE_LOOPS; + int loops = MAX_HANDSHAKE_LOOPS / 2; while (!endLoops && (serverException == null) && (clientException == null)) { @@ -350,7 +353,8 @@ public class DTLSOverDatagram { SSLEngineResult.Status rs = r.getStatus(); SSLEngineResult.HandshakeStatus hs = r.getHandshakeStatus(); - log(side, "====packet(" + loops + ", " + rs + ", " + hs + ")===="); + log(side, "----produce handshake packet(" + + loops + ", " + rs + ", " + hs + ")----"); if (rs == SSLEngineResult.Status.BUFFER_OVERFLOW) { // the client maximum fragment size config does not work? throw new Exception("Buffer overflow: " + From c8aad861dcaa92bc7d7295ae09ea132b3dc51976 Mon Sep 17 00:00:00 2001 From: Nishit Jain Date: Tue, 8 Nov 2016 14:48:55 +0530 Subject: [PATCH 074/402] 8166994: Improve sun.util.locale.LocaleMatcher Reviewed-by: okutsu, naoto, peytoia --- .../sun/util/locale/LocaleMatcher.java | 34 +++++++-- jdk/test/java/util/Locale/Bug8166994.java | 74 +++++++++++++++++++ 2 files changed, 101 insertions(+), 7 deletions(-) create mode 100644 jdk/test/java/util/Locale/Bug8166994.java diff --git a/jdk/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java b/jdk/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java index 3af00e4ce9e..8426b264621 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/LocaleMatcher.java @@ -365,7 +365,7 @@ public final class LocaleMatcher { continue; } - String rangeForRegex = range.replaceAll("\\x2A", "\\\\p{Alnum}*"); + String rangeForRegex = range.replace("*", "\\p{Alnum}*"); while (rangeForRegex.length() > 0) { for (String tag : tags) { tag = tag.toLowerCase(Locale.ROOT); @@ -399,7 +399,7 @@ public final class LocaleMatcher { continue; } - String rangeForRegex = range.replaceAll("\\x2A", "\\\\p{Alnum}*"); + String rangeForRegex = range.replace("*", "\\p{Alnum}*"); while (rangeForRegex.length() > 0) { if (tag.matches(rangeForRegex)) { return true; @@ -447,7 +447,7 @@ public final class LocaleMatcher { } public static List parse(String ranges) { - ranges = ranges.replaceAll(" ", "").toLowerCase(Locale.ROOT); + ranges = ranges.replace(" ", "").toLowerCase(Locale.ROOT); if (ranges.startsWith("accept-language:")) { ranges = ranges.substring(16); // delete unnecessary prefix } @@ -536,6 +536,21 @@ public final class LocaleMatcher { return list; } + /** + * A faster alternative approach to String.replaceFirst(), if the given + * string is a literal String, not a regex. + */ + private static String replaceFirstSubStringMatch(String range, + String substr, String replacement) { + int pos = range.indexOf(substr); + if (pos == -1) { + return range; + } else { + return range.substring(0, pos) + replacement + + range.substring(pos + substr.length()); + } + } + private static String[] getEquivalentsForLanguage(String range) { String r = range; @@ -544,13 +559,16 @@ public final class LocaleMatcher { String equiv = LocaleEquivalentMaps.singleEquivMap.get(r); // Return immediately for performance if the first matching // subtag is found. - return new String[] {range.replaceFirst(r, equiv)}; + return new String[]{replaceFirstSubStringMatch(range, + r, equiv)}; } else if (LocaleEquivalentMaps.multiEquivsMap.containsKey(r)) { String[] equivs = LocaleEquivalentMaps.multiEquivsMap.get(r); + String[] result = new String[equivs.length]; for (int i = 0; i < equivs.length; i++) { - equivs[i] = range.replaceFirst(r, equivs[i]); + result[i] = replaceFirstSubStringMatch(range, + r, equivs[i]); } - return equivs; + return result; } // Truncate the last subtag simply. @@ -578,7 +596,9 @@ public final class LocaleMatcher { int len = index + subtag.length(); if (range.length() == len || range.charAt(len) == '-') { - return range.replaceFirst(subtag, LocaleEquivalentMaps.regionVariantEquivMap.get(subtag)); + return replaceFirstSubStringMatch(range, subtag, + LocaleEquivalentMaps.regionVariantEquivMap + .get(subtag)); } } } diff --git a/jdk/test/java/util/Locale/Bug8166994.java b/jdk/test/java/util/Locale/Bug8166994.java new file mode 100644 index 00000000000..7dea676107a --- /dev/null +++ b/jdk/test/java/util/Locale/Bug8166994.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8166884 + * @summary Checks the subsequent call to parse the same language ranges + * which must generate the same list of language ranges + * i.e. the priority list containing equivalents, as in the + * first call + */ + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +public class Bug8166994 { + + public static void main(String[] args) { + List list = Arrays.asList("ccq-aa", "ybd-aa", "rki-aa"); + String ranges = "ccq-aa"; + testParseConsistency(list, ranges); + + // consecutive call to check the language range parse consistency + testParseConsistency(list, ranges); + + // another case with ranges consisting of multiple equivalents and + // single equivalents + list = Arrays.asList("gfx-xz", "oun-xz", "mwj-xz", "vaj-xz", + "taj-xy", "tsf-xy"); + ranges = "gfx-xz, taj-xy"; + testParseConsistency(list, ranges); + // consecutive call to check the language range parse consistency + testParseConsistency(list, ranges); + + } + + private static void testParseConsistency(List list, String ranges) { + List priorityList = parseRanges(ranges); + if (!list.equals(priorityList)) { + throw new RuntimeException("Failed to parse the language range [" + + ranges + "], Expected: " + list + " Found: " + + priorityList); + } + } + + private static List parseRanges(String s) { + return Locale.LanguageRange.parse(s).stream() + .map(Locale.LanguageRange::getRange) + .collect(Collectors.toList()); + } + +} + From 89e21fa7244709d5d16a2defd79674263190976b Mon Sep 17 00:00:00 2001 From: Alexander Zvegintsev Date: Tue, 8 Nov 2016 13:45:06 +0300 Subject: [PATCH 075/402] 8166594: Taskbar.setWindowProgressValue() spec does not specify expected visual behavior of setWindowProgressValue() Reviewed-by: serb, ssadetsky --- .../share/classes/java/awt/Taskbar.java | 24 ++++++++++++++++--- .../native/libawt/windows/awt_Taskbar.cpp | 9 ++++++- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java b/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java index 5510da3bdac..112ccb59001 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java @@ -407,10 +407,21 @@ public class Taskbar { } /** - * Displays progress for specified window. + * Displays a determinate progress bar in the task area for the specified + * window. + *
    + * The visual behavior is platform and {@link State} dependent. + *
    + * This call cancels the {@link State#INDETERMINATE INDETERMINATE} state + * of the window. + *
    + * Note that when multiple windows is grouped in the task area + * the behavior is platform specific. * * @param w window to update - * @param value from 0 to 100, other to disable progress indication + * @param value from 0 to 100, other to switch to {@link State#OFF} state + * and disable progress indication + * @see #setWindowProgressState(java.awt.Window, State) * @throws SecurityException if a security manager exists and it denies the * {@code RuntimePermission("canProcessApplicationEvents")} permission. * @throws UnsupportedOperationException if the current platform @@ -426,14 +437,21 @@ public class Taskbar { /** * Sets a progress state for a specified window. + *
    + * Each state displays a progress in a platform-dependent way. + *
    + * Note than switching from {@link State#INDETERMINATE INDETERMINATE} state + * to any of determinate states may reset value set by + * {@link #setWindowProgressValue(java.awt.Window, int) setWindowProgressValue} * * @param w window * @param state to change to * @see State#OFF * @see State#NORMAL * @see State#PAUSED - * @see State#INDETERMINATE * @see State#ERROR + * @see State#INDETERMINATE + * @see #setWindowProgressValue(java.awt.Window, int) * @throws SecurityException if a security manager exists and it denies the * {@code RuntimePermission("canProcessApplicationEvents")} permission. * @throws UnsupportedOperationException if the current platform diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp index ebb07187322..19a6fd743b4 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp @@ -58,7 +58,11 @@ JNIEXPORT jboolean JNICALL Java_sun_awt_windows_WTaskbarPeer_nativeInit JNIEXPORT void JNICALL Java_sun_awt_windows_WTaskbarPeer_setProgressValue (JNIEnv *, jobject, jlong window, jint value) { - m_Taskbar->SetProgressValue((HWND)window, value, 100); + if (value < 0 || value > 100) { + m_Taskbar->SetProgressState((HWND)window, TBPF_NOPROGRESS); + } else { + m_Taskbar->SetProgressValue((HWND)window, value, 100); + } } @@ -88,6 +92,9 @@ JNIEXPORT void JNICALL Java_sun_awt_windows_WTaskbarPeer_setProgressState flag = TBPF_NOPROGRESS; } else if (strcmp(valueNative, "NORMAL") == 0) { flag = TBPF_NORMAL; + + // Switching from TBPF_INDETERMINATE to TBPF_NORMAL has no effect + m_Taskbar->SetProgressState((HWND)window, TBPF_PAUSED); } else if (strcmp(valueNative, "PAUSED") == 0) { flag = TBPF_PAUSED; } else if (strcmp(valueNative, "INDETERMINATE") == 0) { From a13cbb364c6f409955319b48db636b62c2ec5d85 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Tue, 8 Nov 2016 13:23:16 +0100 Subject: [PATCH 076/402] 8168911: Increased number of classes initialized during initialization of SignatureFileVerifier Reviewed-by: ascarpino --- .../util/AbstractAlgorithmConstraints.java | 8 +++-- .../security/util/AlgorithmDecomposer.java | 16 ++++----- .../util/DisabledAlgorithmConstraints.java | 36 ++++++++++++------- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java b/jdk/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java index 3c0b1324109..2f7bc0c16af 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java +++ b/jdk/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java @@ -46,8 +46,12 @@ public abstract class AbstractAlgorithmConstraints // Get algorithm constraints from the specified security property. static String[] getAlgorithms(String propertyName) { String property = AccessController.doPrivileged( - (PrivilegedAction) () -> Security.getProperty( - propertyName)); + new PrivilegedAction() { + @Override + public String run() { + return Security.getProperty(propertyName); + } + }); String[] algorithmsInProperty = null; if (property != null && !property.isEmpty()) { diff --git a/jdk/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java b/jdk/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java index bff76cf1721..1774cabb8fb 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java +++ b/jdk/src/java.base/share/classes/sun/security/util/AlgorithmDecomposer.java @@ -34,20 +34,18 @@ import java.util.regex.Pattern; */ public class AlgorithmDecomposer { - private static final Pattern transPattern = Pattern.compile("/"); - // '(? decomposeImpl(String algorithm) { + Set elements = new HashSet<>(); // algorithm/mode/padding - String[] transTockens = transPattern.split(algorithm); + String[] transTokens = algorithm.split("/"); - Set elements = new HashSet<>(); - for (String transTocken : transTockens) { - if (transTocken == null || transTocken.length() == 0) { + for (String transToken : transTokens) { + if (transToken == null || transToken.isEmpty()) { continue; } @@ -57,10 +55,10 @@ public class AlgorithmDecomposer { // with // withand // within - String[] tokens = pattern.split(transTocken); + String[] tokens = PATTERN.split(transToken); for (String token : tokens) { - if (token == null || token.length() == 0) { + if (token == null || token.isEmpty()) { continue; } diff --git a/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java b/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java index 737d68f4881..73914fe30ae 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java +++ b/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java @@ -39,6 +39,7 @@ import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.StringTokenizer; import java.util.TimeZone; import java.util.regex.Pattern; import java.util.regex.Matcher; @@ -240,10 +241,11 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { private static class Constraints { private Map> constraintsMap = new HashMap<>(); - private static final Pattern keySizePattern = Pattern.compile( - "keySize\\s*(<=|<|==|!=|>|>=)\\s*(\\d+)"); - private static final Pattern denyAfterPattern = Pattern.compile( - "denyAfter\\s+(\\d{4})-(\\d{2})-(\\d{2})"); + + private static class Holder { + private static final Pattern DENY_AFTER_PATTERN = Pattern.compile( + "denyAfter\\s+(\\d{4})-(\\d{2})-(\\d{2})"); + } public Constraints(String[] constraintArray) { for (String constraintEntry : constraintArray) { @@ -267,9 +269,11 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { toUpperCase(Locale.ENGLISH)); policy = constraintEntry.substring(space + 1); } else { - constraintsMap.computeIfAbsent( - constraintEntry.toUpperCase(Locale.ENGLISH), - k -> new HashSet<>()); + algorithm = constraintEntry.toUpperCase(Locale.ENGLISH); + if (!constraintsMap.containsKey(algorithm)) { + constraintsMap.putIfAbsent(algorithm, + new HashSet<>()); + } continue; } @@ -283,15 +287,21 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { for (String entry : policy.split("&")) { entry = entry.trim(); - Matcher matcher = keySizePattern.matcher(entry); - if (matcher.matches()) { + Matcher matcher; + if (entry.startsWith("keySize")) { if (debug != null) { debug.println("Constraints set to keySize: " + entry); } + StringTokenizer tokens = new StringTokenizer(entry); + if (!"keySize".equals(tokens.nextToken())) { + throw new IllegalArgumentException("Error in " + + "security property. Constraint unknown: " + + entry); + } c = new KeySizeConstraint(algorithm, - KeySizeConstraint.Operator.of(matcher.group(1)), - Integer.parseInt(matcher.group(2))); + KeySizeConstraint.Operator.of(tokens.nextToken()), + Integer.parseInt(tokens.nextToken())); } else if (entry.equalsIgnoreCase("jdkCA")) { if (debug != null) { @@ -305,7 +315,9 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints { c = new jdkCAConstraint(algorithm); jdkCALimit = true; - } else if(matcher.usePattern(denyAfterPattern).matches()) { + } else if(entry.startsWith("denyAfter") && + (matcher = Holder.DENY_AFTER_PATTERN.matcher(entry)) + .matches()) { if (debug != null) { debug.println("Constraints set to denyAfter"); } From 060ce7c7391a86cff24cdac8a35111bdc95f408d Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Tue, 8 Nov 2016 12:36:13 -0800 Subject: [PATCH 077/402] 8165782: java.util.jar.JarFile.runtimeVersion() spec needs clarification Reviewed-by: mchung, alanb --- .../share/classes/java/util/jar/JarFile.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java index 6b3abf50d78..b3c69df7892 100644 --- a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java +++ b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java @@ -192,9 +192,10 @@ class JarFile extends ZipFile { public static final String MANIFEST_NAME = META_INF + "MANIFEST.MF"; /** - * The version that represents the unversioned configuration of a multi-release jar file. + * Returns the version that represents the unversioned configuration of a + * multi-release jar file. * - * @return Runtime.Version that represents the unversioned configuration + * @return the version that represents the unversioned configuration * * @since 9 */ @@ -203,13 +204,16 @@ class JarFile extends ZipFile { } /** - * The version that represents the effective runtime versioned configuration of a - * multi-release jar file. In most cases, {@code runtimeVersion()} is equal to - * {@code Runtime.version()}. However, if the {@code jdk.util.jar.version} property is set, - * {@code runtimeVersion()} is derived from that property and may not be equal to - * {@code Runtime.version()}. + * Returns the version that represents the effective runtime versioned + * configuration of a multi-release jar file. + *

    + * By default the major version number of the returned {@code Version} will + * be equal to the major version number of {@code Runtime.version()}. + * However, if the {@code jdk.util.jar.version} property is set, the + * returned {@code Version} is derived from that property and major version + * numbers may not be equal. * - * @return Runtime.Version that represents the runtime versioned configuration + * @return the version that represents the runtime versioned configuration * * @since 9 */ From e7fe2a82ca2e5ee190569a7bfaaae6e079f1f6f7 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Tue, 8 Nov 2016 12:36:21 -0800 Subject: [PATCH 078/402] 8166735: JarFile#getVersion spec clarification for unversioned jars Reviewed-by: mchung, alanb --- jdk/src/java.base/share/classes/java/util/jar/JarFile.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java index b3c69df7892..abf4b2fefab 100644 --- a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java +++ b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java @@ -339,6 +339,10 @@ class JarFile extends ZipFile { /** * Returns the maximum version used when searching for versioned entries. + *

    + * If this {@code JarFile} is not a multi-release jar file or is not + * configured to be processed as such, then the version returned will be the + * same as that returned from {@link #baseVersion()}. * * @return the maximum version * @since 9 From 398942a17f06f5a8b080961fe10d17ce855c3be0 Mon Sep 17 00:00:00 2001 From: Xueming Shen Date: Tue, 8 Nov 2016 14:29:14 -0800 Subject: [PATCH 079/402] 8168862: Tighten permissions granted to the jdk.zipfs module Reviewed-by: mullan, mchung, lancea, bpb --- jdk/src/java.base/share/lib/security/default.policy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/lib/security/default.policy b/jdk/src/java.base/share/lib/security/default.policy index 966898459a7..74c8463ea3c 100644 --- a/jdk/src/java.base/share/lib/security/default.policy +++ b/jdk/src/java.base/share/lib/security/default.policy @@ -181,6 +181,6 @@ grant codeBase "jrt:/jdk.security.jgss" { grant codeBase "jrt:/jdk.zipfs" { permission java.io.FilePermission "<>", "read,write,delete"; permission java.lang.RuntimePermission "fileSystemProvider"; - permission java.util.PropertyPermission "*", "read"; + permission java.util.PropertyPermission "os.name", "read"; }; From 31c4b07045bc6a4b220d389430715e9dbb09bbb3 Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Tue, 8 Nov 2016 15:55:11 -0800 Subject: [PATCH 080/402] 8168882: keytool doesn't print certificate info if disabled algorithm was used for signing a jar Reviewed-by: weijun, mullan --- .../sun/security/tools/keytool/Main.java | 8 +- jdk/test/lib/security/SecurityTools.java | 122 ++++++++++++++++++ .../security/tools/keytool/KeyToolTest.java | 10 +- .../sun/security/tools/keytool/PrintSSL.java | 27 +++- .../sun/security/tools/keytool/ReadJar.java | 86 ++++++++++++ .../sun/security/tools/keytool/readjar.sh | 57 -------- 6 files changed, 244 insertions(+), 66 deletions(-) create mode 100644 jdk/test/lib/security/SecurityTools.java create mode 100644 jdk/test/sun/security/tools/keytool/ReadJar.java delete mode 100644 jdk/test/sun/security/tools/keytool/readjar.sh diff --git a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java index 6e26cc62128..9730938c927 100644 --- a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,8 +84,10 @@ import sun.security.util.Pem; import sun.security.x509.*; import static java.security.KeyStore.*; +import java.security.Security; import static sun.security.tools.keytool.Main.Command.*; import static sun.security.tools.keytool.Main.Option.*; +import sun.security.util.DisabledAlgorithmConstraints; /** * This tool manages keystores. @@ -2428,6 +2430,10 @@ public final class Main { private void doPrintCert(final PrintStream out) throws Exception { if (jarfile != null) { + // reset "jdk.certpath.disabledAlgorithms" security property + // to be able to read jars which were signed with weak algorithms + Security.setProperty(DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS, ""); + JarFile jf = new JarFile(jarfile, true); Enumeration entries = jf.entries(); Set ss = new HashSet<>(); diff --git a/jdk/test/lib/security/SecurityTools.java b/jdk/test/lib/security/SecurityTools.java new file mode 100644 index 00000000000..601aa8a999c --- /dev/null +++ b/jdk/test/lib/security/SecurityTools.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import jdk.testlibrary.JDKToolLauncher; +import jdk.testlibrary.OutputAnalyzer; +import jdk.testlibrary.ProcessTools; + +public class SecurityTools { + + public static final String NO_ALIAS = null; + + // keytool + + public static OutputAnalyzer keytool(List options) + throws Throwable { + + JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("keytool") + .addVMArg("-Duser.language=en") + .addVMArg("-Duser.country=US"); + for (String option : options) { + if (option.startsWith("-J")) { + launcher.addVMArg(option.substring(2)); + } else { + launcher.addToolArg(option); + } + } + return ProcessTools.executeCommand(launcher.getCommand()); + } + + public static OutputAnalyzer keytool(String options) throws Throwable { + return keytool(options.split("\\s+")); + } + + public static OutputAnalyzer keytool(String... options) throws Throwable { + return keytool(List.of(options)); + } + + // jarsigner + + public static OutputAnalyzer jarsigner(String jar, String alias, + List options) throws Throwable { + JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jarsigner") + .addVMArg("-Duser.language=en") + .addVMArg("-Duser.country=US"); + for (String option : options) { + if (option.startsWith("-J")) { + launcher.addVMArg(option.substring(2)); + } else { + launcher.addToolArg(option); + } + } + launcher.addToolArg(jar); + if (alias != null) { + launcher.addToolArg(alias); + } + return ProcessTools.executeCommand(launcher.getCommand()); + } + + public static OutputAnalyzer jarsigner(String jar, String alias, + String options) throws Throwable { + + return jarsigner(jar, alias, options.split("\\s+")); + } + + public static OutputAnalyzer jarsigner(String jar, String alias, + String... options) throws Throwable { + + return jarsigner(jar, alias, List.of(options)); + } + + public static OutputAnalyzer sign(String jar, String alias, String... options) + throws Throwable { + + return jarsigner(jar, alias, + mergeOptions("-J-Djava.security.egd=file:/dev/./urandom", options)); + } + + public static OutputAnalyzer verify(String jar, String... options) + throws Throwable { + + return jarsigner(jar, NO_ALIAS, mergeOptions("-verify", options)); + } + + // helper methods + + private static List mergeOptions( + String firstOption, String... secondPart) { + + return mergeOptions(List.of(firstOption), secondPart); + } + + private static List mergeOptions( + List firstPart, String... secondPart) { + + List options = new ArrayList<>(firstPart); + Collections.addAll(options, secondPart); + return options; + } +} diff --git a/jdk/test/sun/security/tools/keytool/KeyToolTest.java b/jdk/test/sun/security/tools/keytool/KeyToolTest.java index 7e19d510767..4a58232a27f 100644 --- a/jdk/test/sun/security/tools/keytool/KeyToolTest.java +++ b/jdk/test/sun/security/tools/keytool/KeyToolTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1211,18 +1211,26 @@ public class KeyToolTest { void sqePrintcertTest() throws Exception { remove("x.jks"); remove("mykey.cert"); + remove("myweakkey.cert"); testOK("", "-keystore x.jks -storetype JKS -storepass changeit " + "-keypass changeit -genkeypair -dname CN=olala"); testOK("", "-keystore x.jks -storetype JKS -storepass changeit " + "-export -file mykey.cert -alias mykey"); + testOK("", "-keystore x.jks -storetype JKS -storepass changeit " + + "-keypass changeit -genkeypair -dname CN=weak -keyalg rsa " + + "-keysize 512 -sigalg MD5withRSA -alias myweakkey"); + testOK("", "-keystore x.jks -storetype JKS -storepass changeit " + + "-export -file myweakkey.cert -alias myweakkey"); testFail("", "-printcert -file badkeystore"); testFail("", "-printcert -file a/b/c/d"); testOK("", "-printcert -file mykey.cert"); + testOK("", "-printcert -file myweakkey.cert"); FileInputStream fin = new FileInputStream("mykey.cert"); testOK(fin, "-printcert"); fin.close(); remove("x.jks"); remove("mykey.cert"); + remove("myweakkey.cert"); } // 8074935: jdk8 keytool doesn't validate pem files for RFC 1421 correctness diff --git a/jdk/test/sun/security/tools/keytool/PrintSSL.java b/jdk/test/sun/security/tools/keytool/PrintSSL.java index 04684f65998..2e600fcd0e5 100644 --- a/jdk/test/sun/security/tools/keytool/PrintSSL.java +++ b/jdk/test/sun/security/tools/keytool/PrintSSL.java @@ -24,20 +24,32 @@ /* * @test * @bug 6480981 8160624 - * @modules java.base/sun.security.tools.keytool * @summary keytool should be able to import certificates from remote SSL server + * @library /lib/security + * @library /lib/testlibrary * @run main/othervm PrintSSL */ -import java.io.IOException; import java.net.ServerSocket; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.concurrent.CountDownLatch; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; +import jdk.testlibrary.OutputAnalyzer; public class PrintSSL { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Throwable { + Files.deleteIfExists(Paths.get("keystore")); + + // make sure that "-printcert" works with weak algorithms + OutputAnalyzer out = SecurityTools.keytool("-genkeypair " + + "-keystore keystore -storepass passphrase " + + "-keypass passphrase -keyalg rsa -keysize 512 " + + "-sigalg MD5withRSA -alias rsa_alias -dname CN=Server"); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); int port = new Server().start(); if(port == -1) { @@ -47,7 +59,10 @@ public class PrintSSL { String cmd = String.format( "-debug %s -printcert -sslserver localhost:%s", ((vmOpt == null) ? "" : vmOpt ), port); - sun.security.tools.keytool.Main.main(cmd.split("\\s+")); + + out = SecurityTools.keytool(cmd); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); } private static class Server implements Runnable { @@ -68,9 +83,7 @@ public class PrintSSL { public void run() { System.setProperty("javax.net.ssl.keyStorePassword", "passphrase"); - System.setProperty("javax.net.ssl.keyStore", - System.getProperty("test.src", "./") - + "/../../../../javax/net/ssl/etc/keystore"); + System.setProperty("javax.net.ssl.keyStore", "keystore"); SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); try (ServerSocket server = sslssf.createServerSocket(0)) { diff --git a/jdk/test/sun/security/tools/keytool/ReadJar.java b/jdk/test/sun/security/tools/keytool/ReadJar.java new file mode 100644 index 00000000000..9e6739cc68b --- /dev/null +++ b/jdk/test/sun/security/tools/keytool/ReadJar.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 6890872 8168882 + * @summary keytool -printcert to recognize signed jar files + * @library /lib/security + * @library /lib/testlibrary + */ + +import java.nio.file.Files; +import java.nio.file.Paths; +import jdk.testlibrary.JarUtils; +import jdk.testlibrary.OutputAnalyzer; + +public class ReadJar { + + public static void main(String[] args) throws Throwable { + testWithMD5(); + } + + // make sure that -printcert option works + // if a weak algorithm was used for signing a jar + private static void testWithMD5() throws Throwable { + // create jar files + JarUtils.createJar("test_md5.jar", "test"); + JarUtils.createJar("test_rsa.jar", "test"); + + // create a keystore and generate keys for jar signing + Files.deleteIfExists(Paths.get("keystore")); + + OutputAnalyzer out = SecurityTools.keytool("-genkeypair " + + "-keystore keystore -storepass password " + + "-keypass password -keyalg rsa -alias rsa_alias -dname CN=A"); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); + + out = SecurityTools.jarsigner("test_rsa.jar", "rsa_alias", + "-keystore keystore -storepass password "); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); + + printCert("test_rsa.jar"); + + out = SecurityTools.jarsigner("test_md5.jar", "rsa_alias", + "-keystore keystore -storepass password " + + "-sigalg MD5withRSA -digestalg MD5"); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); + + printCert("test_md5.jar"); + } + + private static void printCert(String jar) throws Throwable { + OutputAnalyzer out = SecurityTools.keytool("-printcert -jarfile " + jar); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); + out.shouldNotContain("Not a signed jar file"); + + out = SecurityTools.keytool("-printcert -rfc -jarfile " + jar); + System.out.println(out.getOutput()); + out.shouldHaveExitValue(0); + out.shouldNotContain("Not a signed jar file"); + } +} diff --git a/jdk/test/sun/security/tools/keytool/readjar.sh b/jdk/test/sun/security/tools/keytool/readjar.sh deleted file mode 100644 index b041924e0d9..00000000000 --- a/jdk/test/sun/security/tools/keytool/readjar.sh +++ /dev/null @@ -1,57 +0,0 @@ -# -# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# @test -# @bug 6890872 -# @summary keytool -printcert to recognize signed jar files -# - -if [ "${TESTJAVA}" = "" ] ; then - JAVAC_CMD=`which javac` - TESTJAVA=`dirname $JAVAC_CMD`/.. - COMPILEJAVA=${TESTJAVA} -fi - -# set platform-dependent variables -OS=`uname -s` -case "$OS" in - Windows_* ) - FS="\\" - ;; - * ) - FS="/" - ;; -esac - -KS=readjar.jks -rm $KS -$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit -keypass changeit -keystore $KS \ - -keyalg rsa -alias x -dname CN=X -genkeypair -$COMPILEJAVA${FS}bin${FS}jar ${TESTTOOLVMOPTS} cvf readjar.jar $KS -$COMPILEJAVA${FS}bin${FS}jarsigner ${TESTTOOLVMOPTS} -storepass changeit -keystore $KS readjar.jar x - -$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -printcert -jarfile readjar.jar || exit 1 -$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -printcert -jarfile readjar.jar -rfc || exit 1 - -exit 0 - From 5e03e2fcd5edb344250443db6a68696986824e43 Mon Sep 17 00:00:00 2001 From: Bradford Wetmore Date: Tue, 8 Nov 2016 16:54:28 -0800 Subject: [PATCH 081/402] 8169229: RSAClientKeyExchange debug info is incorrect Reviewed-by: xuelei --- .../classes/sun/security/ssl/RSAClientKeyExchange.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/jdk/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java index 6cb2b650de5..98504af5536 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/RSAClientKeyExchange.java @@ -257,7 +257,13 @@ final class RSAClientKeyExchange extends HandshakeMessage { @Override void print(PrintStream s) throws IOException { - s.println("*** ClientKeyExchange, RSA PreMasterSecret, " + - protocolVersion); + String version = "version not available/extractable"; + + byte[] ba = preMaster.getEncoded(); + if (ba != null && ba.length >= 2) { + version = ProtocolVersion.valueOf(ba[0], ba[1]).name; + } + + s.println("*** ClientKeyExchange, RSA PreMasterSecret, " + version); } } From d0b96b7e6a1cb491f036d7b44fda0a12e964a275 Mon Sep 17 00:00:00 2001 From: Ramanand Patil Date: Tue, 8 Nov 2016 18:02:50 +0530 Subject: [PATCH 082/402] 8169191: (tz) Support tzdata2016i Reviewed-by: martin, okutsu --- jdk/make/data/tzdata/VERSION | 2 +- jdk/make/data/tzdata/antarctica | 7 +- jdk/make/data/tzdata/asia | 17 ++- jdk/make/data/tzdata/australasia | 18 ++- jdk/make/data/tzdata/europe | 143 ++++++++++-------- jdk/make/data/tzdata/zone.tab | 3 +- jdk/test/sun/util/calendar/zi/tzdata/VERSION | 2 +- .../sun/util/calendar/zi/tzdata/antarctica | 7 +- jdk/test/sun/util/calendar/zi/tzdata/asia | 17 ++- .../sun/util/calendar/zi/tzdata/australasia | 18 ++- jdk/test/sun/util/calendar/zi/tzdata/europe | 143 ++++++++++-------- jdk/test/sun/util/calendar/zi/tzdata/zone.tab | 3 +- 12 files changed, 232 insertions(+), 148 deletions(-) diff --git a/jdk/make/data/tzdata/VERSION b/jdk/make/data/tzdata/VERSION index 7009f248679..3fbffda8d33 100644 --- a/jdk/make/data/tzdata/VERSION +++ b/jdk/make/data/tzdata/VERSION @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2016h +tzdata2016i diff --git a/jdk/make/data/tzdata/antarctica b/jdk/make/data/tzdata/antarctica index f96947abc7c..2398ac51b07 100644 --- a/jdk/make/data/tzdata/antarctica +++ b/jdk/make/data/tzdata/antarctica @@ -87,13 +87,18 @@ # Background: # http://www.timeanddate.com/news/time/antartica-time-changes-2010.html +# From Steffen Thorsen (2016-10-28): +# Australian Antarctica Division informed us that Casey changed time +# zone to UTC+11 in "the morning of 22nd October 2016". + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Antarctica/Casey 0 - -00 1969 8:00 - +08 2009 Oct 18 2:00 11:00 - +11 2010 Mar 5 2:00 8:00 - +08 2011 Oct 28 2:00 11:00 - +11 2012 Feb 21 17:00u - 8:00 - +08 + 8:00 - +08 2016 Oct 22 + 11:00 - +11 Zone Antarctica/Davis 0 - -00 1957 Jan 13 7:00 - +07 1964 Nov 0 - -00 1969 Feb diff --git a/jdk/make/data/tzdata/asia b/jdk/make/data/tzdata/asia index 71711a946d1..7d540324cdb 100644 --- a/jdk/make/data/tzdata/asia +++ b/jdk/make/data/tzdata/asia @@ -794,9 +794,19 @@ Zone Asia/Macau 7:34:20 - LMT 1912 Jan 1 ############################################################################### # Cyprus -# + # Milne says the Eastern Telegraph Company used 2:14:00. Stick with LMT. +# IATA SSIM (1998-09) has Cyprus using EU rules for the first time. + +# From Paul Eggert (2016-09-09): +# Yesterday's Cyprus Mail reports that Northern Cyprus followed Turkey's +# lead and switched from +02/+03 to +03 year-round. +# http://cyprus-mail.com/2016/09/08/two-time-zones-cyprus-turkey-will-not-turn-clocks-back-next-month/ # +# From Even Scharning (2016-10-31): +# Looks like the time zone split in Cyprus went through last night. +# http://cyprus-mail.com/2016/10/30/cyprus-new-division-two-time-zones-now-reality/ + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Cyprus 1975 only - Apr 13 0:00 1:00 S Rule Cyprus 1975 only - Oct 12 0:00 0 - @@ -811,7 +821,10 @@ Rule Cyprus 1981 1998 - Mar lastSun 0:00 1:00 S Zone Asia/Nicosia 2:13:28 - LMT 1921 Nov 14 2:00 Cyprus EE%sT 1998 Sep 2:00 EUAsia EE%sT -# IATA SSIM (1998-09) has Cyprus using EU rules for the first time. +Zone Asia/Famagusta 2:15:48 - LMT 1921 Nov 14 + 2:00 Cyprus EE%sT 1998 Sep + 2:00 EUAsia EE%sT 2016 Sep 8 + 3:00 - +03 # Classically, Cyprus belongs to Asia; e.g. see Herodotus, Histories, I.72. # However, for various reasons many users expect to find it under Europe. diff --git a/jdk/make/data/tzdata/australasia b/jdk/make/data/tzdata/australasia index 23153b171fa..81ef5215942 100644 --- a/jdk/make/data/tzdata/australasia +++ b/jdk/make/data/tzdata/australasia @@ -725,11 +725,13 @@ Rule Tonga 1999 only - Oct 7 2:00s 1:00 S Rule Tonga 2000 only - Mar 19 2:00s 0 - Rule Tonga 2000 2001 - Nov Sun>=1 2:00 1:00 S Rule Tonga 2001 2002 - Jan lastSun 2:00 0 - +Rule Tonga 2016 max - Nov Sun>=1 2:00 1:00 S +Rule Tonga 2017 max - Jan Sun>=15 3:00 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Pacific/Tongatapu 12:19:20 - LMT 1901 - 12:20 - TOT 1941 # Tonga Time - 13:00 - TOT 1999 - 13:00 Tonga TO%sT + 12:20 - +1220 1941 + 13:00 - +13 1999 + 13:00 Tonga +13/+14 # Tuvalu # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1735,9 +1737,17 @@ Zone Pacific/Wallis 12:15:20 - LMT 1901 # of January the standard time in the Kingdom shall be moved backward by one # hour to 1:00am. -# From Pulu 'Anau (2002-11-05): +# From Pulu ʻAnau (2002-11-05): # The law was for 3 years, supposedly to get renewed. It wasn't. +# From Pulu ʻAnau (2016-10-27): +# http://mic.gov.to/news-today/press-releases/6375-daylight-saving-set-to-run-from-6-november-2016-to-15-january-2017 +# Cannot find anyone who knows the rules, has seen the duration or has seen +# the cabinet decision, but it appears we are following Fiji's rule set. +# +# From Tim Parenti (2016-10-26): +# Assume Tonga will observe DST from the first Sunday in November at 02:00 +# through the third Sunday in January at 03:00, like Fiji, for now. # Wake diff --git a/jdk/make/data/tzdata/europe b/jdk/make/data/tzdata/europe index d182dbb6ba8..df464859fb3 100644 --- a/jdk/make/data/tzdata/europe +++ b/jdk/make/data/tzdata/europe @@ -1523,73 +1523,84 @@ Zone Atlantic/Reykjavik -1:28 - LMT 1908 # But these events all occurred before the 1970 cutoff, # so record only the time in Rome. # -# From Paul Eggert (2006-03-22): -# For Italian DST we have three sources: Shanks & Pottenger, Whitman, and -# F. Pollastri -# Day-light Saving Time in Italy (2006-02-03) -# http://toi.iriti.cnr.it/uk/ienitlt.html -# ('FP' below), taken from an Italian National Electrotechnical Institute -# publication. When the three sources disagree, guess who's right, as follows: +# From Michael Deckers (2016-10-24): +# http://www.ac-ilsestante.it/MERIDIANE/ora_legale quotes a law of 1893-08-10 +# ... [translated as] "The preceding dispositions will enter into +# force at the instant at which, according to the time specified in +# the 1st article, the 1st of November 1893 will begin...." # -# year FP Shanks&P. (S) Whitman (W) Go with: -# 1916 06-03 06-03 24:00 06-03 00:00 FP & W -# 09-30 09-30 24:00 09-30 01:00 FP; guess 24:00s -# 1917 04-01 03-31 24:00 03-31 00:00 FP & S -# 09-30 09-29 24:00 09-30 01:00 FP & W -# 1918 03-09 03-09 24:00 03-09 00:00 FP & S -# 10-06 10-05 24:00 10-06 01:00 FP & W -# 1919 03-01 03-01 24:00 03-01 00:00 FP & S -# 10-04 10-04 24:00 10-04 01:00 FP; guess 24:00s -# 1920 03-20 03-20 24:00 03-20 00:00 FP & S -# 09-18 09-18 24:00 10-01 01:00 FP; guess 24:00s -# 1944 04-02 04-03 02:00 S (see C-Eur) -# 09-16 10-02 03:00 FP; guess 24:00s -# 1945 09-14 09-16 24:00 FP; guess 24:00s -# 1970 05-21 05-31 00:00 S -# 09-20 09-27 00:00 S +# From Pierpaolo Bernardi (2016-10-20): +# The authoritative source for time in Italy is the national metrological +# institute, which has a summary page of historical DST data at +# http://www.inrim.it/res/tf/ora_legale_i.shtml +# (2016-10-24): +# http://www.renzobaldini.it/le-ore-legali-in-italia/ +# has still different data for 1944. It divides Italy in two, as +# there were effectively two governments at the time, north of Gothic +# Line German controlled territory, official government RSI, and south +# of the Gothic Line, controlled by allied armies. +# +# From Brian Inglis (2016-10-23): +# Viceregal LEGISLATIVE DECREE. 14 September 1944, no. 219. +# Restoration of Standard Time. (044U0219) (OJ 62 of 30.9.1944) ... +# Given the R. law decreed on 1944-03-29, no. 92, by which standard time is +# advanced to sixty minutes later starting at hour two on 1944-04-02; ... +# Starting at hour three on the date 1944-09-17 standard time will be resumed. +# +# From Paul Eggert (2016-10-27): +# Go with INRiM for DST rules, except as corrected by Inglis for 1944 +# for the Kingdom of Italy. This is consistent with Renzo Baldini. +# Model Rome's occupation by using using C-Eur rules from 1943-09-10 +# to 1944-06-04; although Rome was an open city during this period, it +# was effectively controlled by Germany. # # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Italy 1916 only - Jun 3 0:00s 1:00 S -Rule Italy 1916 only - Oct 1 0:00s 0 - -Rule Italy 1917 only - Apr 1 0:00s 1:00 S -Rule Italy 1917 only - Sep 30 0:00s 0 - -Rule Italy 1918 only - Mar 10 0:00s 1:00 S -Rule Italy 1918 1919 - Oct Sun>=1 0:00s 0 - -Rule Italy 1919 only - Mar 2 0:00s 1:00 S -Rule Italy 1920 only - Mar 21 0:00s 1:00 S -Rule Italy 1920 only - Sep 19 0:00s 0 - -Rule Italy 1940 only - Jun 15 0:00s 1:00 S -Rule Italy 1944 only - Sep 17 0:00s 0 - -Rule Italy 1945 only - Apr 2 2:00 1:00 S -Rule Italy 1945 only - Sep 15 0:00s 0 - -Rule Italy 1946 only - Mar 17 2:00s 1:00 S -Rule Italy 1946 only - Oct 6 2:00s 0 - -Rule Italy 1947 only - Mar 16 0:00s 1:00 S -Rule Italy 1947 only - Oct 5 0:00s 0 - -Rule Italy 1948 only - Feb 29 2:00s 1:00 S -Rule Italy 1948 only - Oct 3 2:00s 0 - -Rule Italy 1966 1968 - May Sun>=22 0:00 1:00 S -Rule Italy 1966 1969 - Sep Sun>=22 0:00 0 - -Rule Italy 1969 only - Jun 1 0:00 1:00 S -Rule Italy 1970 only - May 31 0:00 1:00 S -Rule Italy 1970 only - Sep lastSun 0:00 0 - -Rule Italy 1971 1972 - May Sun>=22 0:00 1:00 S -Rule Italy 1971 only - Sep lastSun 1:00 0 - -Rule Italy 1972 only - Oct 1 0:00 0 - -Rule Italy 1973 only - Jun 3 0:00 1:00 S -Rule Italy 1973 1974 - Sep lastSun 0:00 0 - -Rule Italy 1974 only - May 26 0:00 1:00 S -Rule Italy 1975 only - Jun 1 0:00s 1:00 S -Rule Italy 1975 1977 - Sep lastSun 0:00s 0 - -Rule Italy 1976 only - May 30 0:00s 1:00 S -Rule Italy 1977 1979 - May Sun>=22 0:00s 1:00 S -Rule Italy 1978 only - Oct 1 0:00s 0 - -Rule Italy 1979 only - Sep 30 0:00s 0 - +Rule Italy 1916 only - Jun 3 24:00 1:00 S +Rule Italy 1916 1917 - Sep 30 24:00 0 - +Rule Italy 1917 only - Mar 31 24:00 1:00 S +Rule Italy 1918 only - Mar 9 24:00 1:00 S +Rule Italy 1918 only - Oct 6 24:00 0 - +Rule Italy 1919 only - Mar 1 24:00 1:00 S +Rule Italy 1919 only - Oct 4 24:00 0 - +Rule Italy 1920 only - Mar 20 24:00 1:00 S +Rule Italy 1920 only - Sep 18 24:00 0 - +Rule Italy 1940 only - Jun 14 24:00 1:00 S +Rule Italy 1942 only - Nov 2 2:00s 0 - +Rule Italy 1943 only - Mar 29 2:00s 1:00 S +Rule Italy 1943 only - Oct 4 2:00s 0 - +Rule Italy 1944 only - Apr 2 2:00s 1:00 S +Rule Italy 1944 only - Sep 17 2:00s 0 - +Rule Italy 1945 only - Apr 2 2:00 1:00 S +Rule Italy 1945 only - Sep 15 1:00 0 - +Rule Italy 1946 only - Mar 17 2:00s 1:00 S +Rule Italy 1946 only - Oct 6 2:00s 0 - +Rule Italy 1947 only - Mar 16 0:00s 1:00 S +Rule Italy 1947 only - Oct 5 0:00s 0 - +Rule Italy 1948 only - Feb 29 2:00s 1:00 S +Rule Italy 1948 only - Oct 3 2:00s 0 - +Rule Italy 1966 1968 - May Sun>=22 0:00s 1:00 S +Rule Italy 1966 only - Sep 24 24:00 0 - +Rule Italy 1967 1969 - Sep Sun>=22 0:00s 0 - +Rule Italy 1969 only - Jun 1 0:00s 1:00 S +Rule Italy 1970 only - May 31 0:00s 1:00 S +Rule Italy 1970 only - Sep lastSun 0:00s 0 - +Rule Italy 1971 1972 - May Sun>=22 0:00s 1:00 S +Rule Italy 1971 only - Sep lastSun 0:00s 0 - +Rule Italy 1972 only - Oct 1 0:00s 0 - +Rule Italy 1973 only - Jun 3 0:00s 1:00 S +Rule Italy 1973 1974 - Sep lastSun 0:00s 0 - +Rule Italy 1974 only - May 26 0:00s 1:00 S +Rule Italy 1975 only - Jun 1 0:00s 1:00 S +Rule Italy 1975 1977 - Sep lastSun 0:00s 0 - +Rule Italy 1976 only - May 30 0:00s 1:00 S +Rule Italy 1977 1979 - May Sun>=22 0:00s 1:00 S +Rule Italy 1978 only - Oct 1 0:00s 0 - +Rule Italy 1979 only - Sep 30 0:00s 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Rome 0:49:56 - LMT 1866 Sep 22 - 0:49:56 - RMT 1893 Nov 1 0:00s # Rome Mean - 1:00 Italy CE%sT 1942 Nov 2 2:00s - 1:00 C-Eur CE%sT 1944 Jul + 0:49:56 - RMT 1893 Oct 31 23:49:56 # Rome Mean + 1:00 Italy CE%sT 1943 Sep 10 + 1:00 C-Eur CE%sT 1944 Jun 4 1:00 Italy CE%sT 1980 1:00 EU CE%sT @@ -1788,6 +1799,10 @@ Zone Europe/Luxembourg 0:24:36 - LMT 1904 Jun # See Europe/Belgrade. # Malta +# +# From Paul Eggert (2016-10-21): +# Assume 1900-1972 was like Rome, overriding Shanks. +# # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Malta 1973 only - Mar 31 0:00s 1:00 S Rule Malta 1973 only - Sep 29 0:00s 0 - @@ -1798,8 +1813,6 @@ Rule Malta 1975 1980 - Sep Sun>=15 2:00 0 - Rule Malta 1980 only - Mar 31 2:00 1:00 S # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Malta 0:58:04 - LMT 1893 Nov 2 0:00s # Valletta - 1:00 Italy CE%sT 1942 Nov 2 2:00s - 1:00 C-Eur CE%sT 1945 Apr 2 2:00s 1:00 Italy CE%sT 1973 Mar 31 1:00 Malta CE%sT 1981 1:00 EU CE%sT @@ -1931,7 +1944,7 @@ Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15 # Amsterdam mean time. # The data entries before 1945 are taken from -# http://www.staff.science.uu.nl/~gent0113/idl/idl.htm +# http://www.staff.science.uu.nl/~gent0113/wettijd/wettijd.htm # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Neth 1916 only - May 1 0:00 1:00 NST # Netherlands Summer Time diff --git a/jdk/make/data/tzdata/zone.tab b/jdk/make/data/tzdata/zone.tab index db050608240..2de07ef7112 100644 --- a/jdk/make/data/tzdata/zone.tab +++ b/jdk/make/data/tzdata/zone.tab @@ -175,7 +175,8 @@ CU +2308-08222 America/Havana CV +1455-02331 Atlantic/Cape_Verde CW +1211-06900 America/Curacao CX -1025+10543 Indian/Christmas -CY +3510+03322 Asia/Nicosia +CY +3510+03322 Asia/Nicosia Cyprus (most areas) +CY +3507+03357 Asia/Famagusta Northern Cyprus CZ +5005+01426 Europe/Prague DE +5230+01322 Europe/Berlin Germany (most areas) DE +4742+00841 Europe/Busingen Busingen diff --git a/jdk/test/sun/util/calendar/zi/tzdata/VERSION b/jdk/test/sun/util/calendar/zi/tzdata/VERSION index 7009f248679..3fbffda8d33 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/VERSION +++ b/jdk/test/sun/util/calendar/zi/tzdata/VERSION @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2016h +tzdata2016i diff --git a/jdk/test/sun/util/calendar/zi/tzdata/antarctica b/jdk/test/sun/util/calendar/zi/tzdata/antarctica index f96947abc7c..2398ac51b07 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/antarctica +++ b/jdk/test/sun/util/calendar/zi/tzdata/antarctica @@ -87,13 +87,18 @@ # Background: # http://www.timeanddate.com/news/time/antartica-time-changes-2010.html +# From Steffen Thorsen (2016-10-28): +# Australian Antarctica Division informed us that Casey changed time +# zone to UTC+11 in "the morning of 22nd October 2016". + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Antarctica/Casey 0 - -00 1969 8:00 - +08 2009 Oct 18 2:00 11:00 - +11 2010 Mar 5 2:00 8:00 - +08 2011 Oct 28 2:00 11:00 - +11 2012 Feb 21 17:00u - 8:00 - +08 + 8:00 - +08 2016 Oct 22 + 11:00 - +11 Zone Antarctica/Davis 0 - -00 1957 Jan 13 7:00 - +07 1964 Nov 0 - -00 1969 Feb diff --git a/jdk/test/sun/util/calendar/zi/tzdata/asia b/jdk/test/sun/util/calendar/zi/tzdata/asia index 71711a946d1..7d540324cdb 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/asia +++ b/jdk/test/sun/util/calendar/zi/tzdata/asia @@ -794,9 +794,19 @@ Zone Asia/Macau 7:34:20 - LMT 1912 Jan 1 ############################################################################### # Cyprus -# + # Milne says the Eastern Telegraph Company used 2:14:00. Stick with LMT. +# IATA SSIM (1998-09) has Cyprus using EU rules for the first time. + +# From Paul Eggert (2016-09-09): +# Yesterday's Cyprus Mail reports that Northern Cyprus followed Turkey's +# lead and switched from +02/+03 to +03 year-round. +# http://cyprus-mail.com/2016/09/08/two-time-zones-cyprus-turkey-will-not-turn-clocks-back-next-month/ # +# From Even Scharning (2016-10-31): +# Looks like the time zone split in Cyprus went through last night. +# http://cyprus-mail.com/2016/10/30/cyprus-new-division-two-time-zones-now-reality/ + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Cyprus 1975 only - Apr 13 0:00 1:00 S Rule Cyprus 1975 only - Oct 12 0:00 0 - @@ -811,7 +821,10 @@ Rule Cyprus 1981 1998 - Mar lastSun 0:00 1:00 S Zone Asia/Nicosia 2:13:28 - LMT 1921 Nov 14 2:00 Cyprus EE%sT 1998 Sep 2:00 EUAsia EE%sT -# IATA SSIM (1998-09) has Cyprus using EU rules for the first time. +Zone Asia/Famagusta 2:15:48 - LMT 1921 Nov 14 + 2:00 Cyprus EE%sT 1998 Sep + 2:00 EUAsia EE%sT 2016 Sep 8 + 3:00 - +03 # Classically, Cyprus belongs to Asia; e.g. see Herodotus, Histories, I.72. # However, for various reasons many users expect to find it under Europe. diff --git a/jdk/test/sun/util/calendar/zi/tzdata/australasia b/jdk/test/sun/util/calendar/zi/tzdata/australasia index 23153b171fa..81ef5215942 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/australasia +++ b/jdk/test/sun/util/calendar/zi/tzdata/australasia @@ -725,11 +725,13 @@ Rule Tonga 1999 only - Oct 7 2:00s 1:00 S Rule Tonga 2000 only - Mar 19 2:00s 0 - Rule Tonga 2000 2001 - Nov Sun>=1 2:00 1:00 S Rule Tonga 2001 2002 - Jan lastSun 2:00 0 - +Rule Tonga 2016 max - Nov Sun>=1 2:00 1:00 S +Rule Tonga 2017 max - Jan Sun>=15 3:00 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Pacific/Tongatapu 12:19:20 - LMT 1901 - 12:20 - TOT 1941 # Tonga Time - 13:00 - TOT 1999 - 13:00 Tonga TO%sT + 12:20 - +1220 1941 + 13:00 - +13 1999 + 13:00 Tonga +13/+14 # Tuvalu # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1735,9 +1737,17 @@ Zone Pacific/Wallis 12:15:20 - LMT 1901 # of January the standard time in the Kingdom shall be moved backward by one # hour to 1:00am. -# From Pulu 'Anau (2002-11-05): +# From Pulu ʻAnau (2002-11-05): # The law was for 3 years, supposedly to get renewed. It wasn't. +# From Pulu ʻAnau (2016-10-27): +# http://mic.gov.to/news-today/press-releases/6375-daylight-saving-set-to-run-from-6-november-2016-to-15-january-2017 +# Cannot find anyone who knows the rules, has seen the duration or has seen +# the cabinet decision, but it appears we are following Fiji's rule set. +# +# From Tim Parenti (2016-10-26): +# Assume Tonga will observe DST from the first Sunday in November at 02:00 +# through the third Sunday in January at 03:00, like Fiji, for now. # Wake diff --git a/jdk/test/sun/util/calendar/zi/tzdata/europe b/jdk/test/sun/util/calendar/zi/tzdata/europe index d182dbb6ba8..df464859fb3 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/europe +++ b/jdk/test/sun/util/calendar/zi/tzdata/europe @@ -1523,73 +1523,84 @@ Zone Atlantic/Reykjavik -1:28 - LMT 1908 # But these events all occurred before the 1970 cutoff, # so record only the time in Rome. # -# From Paul Eggert (2006-03-22): -# For Italian DST we have three sources: Shanks & Pottenger, Whitman, and -# F. Pollastri -# Day-light Saving Time in Italy (2006-02-03) -# http://toi.iriti.cnr.it/uk/ienitlt.html -# ('FP' below), taken from an Italian National Electrotechnical Institute -# publication. When the three sources disagree, guess who's right, as follows: +# From Michael Deckers (2016-10-24): +# http://www.ac-ilsestante.it/MERIDIANE/ora_legale quotes a law of 1893-08-10 +# ... [translated as] "The preceding dispositions will enter into +# force at the instant at which, according to the time specified in +# the 1st article, the 1st of November 1893 will begin...." # -# year FP Shanks&P. (S) Whitman (W) Go with: -# 1916 06-03 06-03 24:00 06-03 00:00 FP & W -# 09-30 09-30 24:00 09-30 01:00 FP; guess 24:00s -# 1917 04-01 03-31 24:00 03-31 00:00 FP & S -# 09-30 09-29 24:00 09-30 01:00 FP & W -# 1918 03-09 03-09 24:00 03-09 00:00 FP & S -# 10-06 10-05 24:00 10-06 01:00 FP & W -# 1919 03-01 03-01 24:00 03-01 00:00 FP & S -# 10-04 10-04 24:00 10-04 01:00 FP; guess 24:00s -# 1920 03-20 03-20 24:00 03-20 00:00 FP & S -# 09-18 09-18 24:00 10-01 01:00 FP; guess 24:00s -# 1944 04-02 04-03 02:00 S (see C-Eur) -# 09-16 10-02 03:00 FP; guess 24:00s -# 1945 09-14 09-16 24:00 FP; guess 24:00s -# 1970 05-21 05-31 00:00 S -# 09-20 09-27 00:00 S +# From Pierpaolo Bernardi (2016-10-20): +# The authoritative source for time in Italy is the national metrological +# institute, which has a summary page of historical DST data at +# http://www.inrim.it/res/tf/ora_legale_i.shtml +# (2016-10-24): +# http://www.renzobaldini.it/le-ore-legali-in-italia/ +# has still different data for 1944. It divides Italy in two, as +# there were effectively two governments at the time, north of Gothic +# Line German controlled territory, official government RSI, and south +# of the Gothic Line, controlled by allied armies. +# +# From Brian Inglis (2016-10-23): +# Viceregal LEGISLATIVE DECREE. 14 September 1944, no. 219. +# Restoration of Standard Time. (044U0219) (OJ 62 of 30.9.1944) ... +# Given the R. law decreed on 1944-03-29, no. 92, by which standard time is +# advanced to sixty minutes later starting at hour two on 1944-04-02; ... +# Starting at hour three on the date 1944-09-17 standard time will be resumed. +# +# From Paul Eggert (2016-10-27): +# Go with INRiM for DST rules, except as corrected by Inglis for 1944 +# for the Kingdom of Italy. This is consistent with Renzo Baldini. +# Model Rome's occupation by using using C-Eur rules from 1943-09-10 +# to 1944-06-04; although Rome was an open city during this period, it +# was effectively controlled by Germany. # # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Italy 1916 only - Jun 3 0:00s 1:00 S -Rule Italy 1916 only - Oct 1 0:00s 0 - -Rule Italy 1917 only - Apr 1 0:00s 1:00 S -Rule Italy 1917 only - Sep 30 0:00s 0 - -Rule Italy 1918 only - Mar 10 0:00s 1:00 S -Rule Italy 1918 1919 - Oct Sun>=1 0:00s 0 - -Rule Italy 1919 only - Mar 2 0:00s 1:00 S -Rule Italy 1920 only - Mar 21 0:00s 1:00 S -Rule Italy 1920 only - Sep 19 0:00s 0 - -Rule Italy 1940 only - Jun 15 0:00s 1:00 S -Rule Italy 1944 only - Sep 17 0:00s 0 - -Rule Italy 1945 only - Apr 2 2:00 1:00 S -Rule Italy 1945 only - Sep 15 0:00s 0 - -Rule Italy 1946 only - Mar 17 2:00s 1:00 S -Rule Italy 1946 only - Oct 6 2:00s 0 - -Rule Italy 1947 only - Mar 16 0:00s 1:00 S -Rule Italy 1947 only - Oct 5 0:00s 0 - -Rule Italy 1948 only - Feb 29 2:00s 1:00 S -Rule Italy 1948 only - Oct 3 2:00s 0 - -Rule Italy 1966 1968 - May Sun>=22 0:00 1:00 S -Rule Italy 1966 1969 - Sep Sun>=22 0:00 0 - -Rule Italy 1969 only - Jun 1 0:00 1:00 S -Rule Italy 1970 only - May 31 0:00 1:00 S -Rule Italy 1970 only - Sep lastSun 0:00 0 - -Rule Italy 1971 1972 - May Sun>=22 0:00 1:00 S -Rule Italy 1971 only - Sep lastSun 1:00 0 - -Rule Italy 1972 only - Oct 1 0:00 0 - -Rule Italy 1973 only - Jun 3 0:00 1:00 S -Rule Italy 1973 1974 - Sep lastSun 0:00 0 - -Rule Italy 1974 only - May 26 0:00 1:00 S -Rule Italy 1975 only - Jun 1 0:00s 1:00 S -Rule Italy 1975 1977 - Sep lastSun 0:00s 0 - -Rule Italy 1976 only - May 30 0:00s 1:00 S -Rule Italy 1977 1979 - May Sun>=22 0:00s 1:00 S -Rule Italy 1978 only - Oct 1 0:00s 0 - -Rule Italy 1979 only - Sep 30 0:00s 0 - +Rule Italy 1916 only - Jun 3 24:00 1:00 S +Rule Italy 1916 1917 - Sep 30 24:00 0 - +Rule Italy 1917 only - Mar 31 24:00 1:00 S +Rule Italy 1918 only - Mar 9 24:00 1:00 S +Rule Italy 1918 only - Oct 6 24:00 0 - +Rule Italy 1919 only - Mar 1 24:00 1:00 S +Rule Italy 1919 only - Oct 4 24:00 0 - +Rule Italy 1920 only - Mar 20 24:00 1:00 S +Rule Italy 1920 only - Sep 18 24:00 0 - +Rule Italy 1940 only - Jun 14 24:00 1:00 S +Rule Italy 1942 only - Nov 2 2:00s 0 - +Rule Italy 1943 only - Mar 29 2:00s 1:00 S +Rule Italy 1943 only - Oct 4 2:00s 0 - +Rule Italy 1944 only - Apr 2 2:00s 1:00 S +Rule Italy 1944 only - Sep 17 2:00s 0 - +Rule Italy 1945 only - Apr 2 2:00 1:00 S +Rule Italy 1945 only - Sep 15 1:00 0 - +Rule Italy 1946 only - Mar 17 2:00s 1:00 S +Rule Italy 1946 only - Oct 6 2:00s 0 - +Rule Italy 1947 only - Mar 16 0:00s 1:00 S +Rule Italy 1947 only - Oct 5 0:00s 0 - +Rule Italy 1948 only - Feb 29 2:00s 1:00 S +Rule Italy 1948 only - Oct 3 2:00s 0 - +Rule Italy 1966 1968 - May Sun>=22 0:00s 1:00 S +Rule Italy 1966 only - Sep 24 24:00 0 - +Rule Italy 1967 1969 - Sep Sun>=22 0:00s 0 - +Rule Italy 1969 only - Jun 1 0:00s 1:00 S +Rule Italy 1970 only - May 31 0:00s 1:00 S +Rule Italy 1970 only - Sep lastSun 0:00s 0 - +Rule Italy 1971 1972 - May Sun>=22 0:00s 1:00 S +Rule Italy 1971 only - Sep lastSun 0:00s 0 - +Rule Italy 1972 only - Oct 1 0:00s 0 - +Rule Italy 1973 only - Jun 3 0:00s 1:00 S +Rule Italy 1973 1974 - Sep lastSun 0:00s 0 - +Rule Italy 1974 only - May 26 0:00s 1:00 S +Rule Italy 1975 only - Jun 1 0:00s 1:00 S +Rule Italy 1975 1977 - Sep lastSun 0:00s 0 - +Rule Italy 1976 only - May 30 0:00s 1:00 S +Rule Italy 1977 1979 - May Sun>=22 0:00s 1:00 S +Rule Italy 1978 only - Oct 1 0:00s 0 - +Rule Italy 1979 only - Sep 30 0:00s 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Rome 0:49:56 - LMT 1866 Sep 22 - 0:49:56 - RMT 1893 Nov 1 0:00s # Rome Mean - 1:00 Italy CE%sT 1942 Nov 2 2:00s - 1:00 C-Eur CE%sT 1944 Jul + 0:49:56 - RMT 1893 Oct 31 23:49:56 # Rome Mean + 1:00 Italy CE%sT 1943 Sep 10 + 1:00 C-Eur CE%sT 1944 Jun 4 1:00 Italy CE%sT 1980 1:00 EU CE%sT @@ -1788,6 +1799,10 @@ Zone Europe/Luxembourg 0:24:36 - LMT 1904 Jun # See Europe/Belgrade. # Malta +# +# From Paul Eggert (2016-10-21): +# Assume 1900-1972 was like Rome, overriding Shanks. +# # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Malta 1973 only - Mar 31 0:00s 1:00 S Rule Malta 1973 only - Sep 29 0:00s 0 - @@ -1798,8 +1813,6 @@ Rule Malta 1975 1980 - Sep Sun>=15 2:00 0 - Rule Malta 1980 only - Mar 31 2:00 1:00 S # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Malta 0:58:04 - LMT 1893 Nov 2 0:00s # Valletta - 1:00 Italy CE%sT 1942 Nov 2 2:00s - 1:00 C-Eur CE%sT 1945 Apr 2 2:00s 1:00 Italy CE%sT 1973 Mar 31 1:00 Malta CE%sT 1981 1:00 EU CE%sT @@ -1931,7 +1944,7 @@ Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15 # Amsterdam mean time. # The data entries before 1945 are taken from -# http://www.staff.science.uu.nl/~gent0113/idl/idl.htm +# http://www.staff.science.uu.nl/~gent0113/wettijd/wettijd.htm # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Neth 1916 only - May 1 0:00 1:00 NST # Netherlands Summer Time diff --git a/jdk/test/sun/util/calendar/zi/tzdata/zone.tab b/jdk/test/sun/util/calendar/zi/tzdata/zone.tab index db050608240..2de07ef7112 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/zone.tab +++ b/jdk/test/sun/util/calendar/zi/tzdata/zone.tab @@ -175,7 +175,8 @@ CU +2308-08222 America/Havana CV +1455-02331 Atlantic/Cape_Verde CW +1211-06900 America/Curacao CX -1025+10543 Indian/Christmas -CY +3510+03322 Asia/Nicosia +CY +3510+03322 Asia/Nicosia Cyprus (most areas) +CY +3507+03357 Asia/Famagusta Northern Cyprus CZ +5005+01426 Europe/Prague DE +5230+01322 Europe/Berlin Germany (most areas) DE +4742+00841 Europe/Busingen Busingen From c8163c03882e542b410eee9096085e63dc630ddc Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Tue, 8 Nov 2016 16:18:41 +0300 Subject: [PATCH 083/402] 8169316: com/sun/net/httpserver tests have undeclared dependency on java.logging Reviewed-by: chegar --- jdk/test/com/sun/net/httpserver/TEST.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/com/sun/net/httpserver/TEST.properties b/jdk/test/com/sun/net/httpserver/TEST.properties index 4981030a154..45a2c1ca465 100644 --- a/jdk/test/com/sun/net/httpserver/TEST.properties +++ b/jdk/test/com/sun/net/httpserver/TEST.properties @@ -1 +1 @@ -modules = jdk.httpserver \ No newline at end of file +modules = jdk.httpserver java.logging From b68a13573ff1cd539628cb0254756273192d1952 Mon Sep 17 00:00:00 2001 From: Konstantin Shefov Date: Tue, 8 Nov 2016 17:10:12 +0300 Subject: [PATCH 084/402] 8004693: TEST_BUG: java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java fails Reviewed-by: azvegint, avstepan --- .../DefaultPolicyChange_Swing.java | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java b/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java index 93f481ff020..624f2a68597 100644 --- a/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java +++ b/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,32 +23,25 @@ /* @test - @bug 6741526 + @bug 6741526 8004693 @summary KeyboardFocusManager.setDefaultFocusTraversalPolicy(FocusTraversalPolicy) affects created components - @library ../../regtesthelpers - @build Sysout @author Andrei Dmitriev : area=awt-focus @run main DefaultPolicyChange_Swing */ import java.awt.*; + import javax.swing.*; import javax.swing.table.DefaultTableModel; -import test.java.awt.regtesthelpers.Sysout; public class DefaultPolicyChange_Swing { - public static void main(String []s) { - EventQueue.invokeLater(new Runnable(){ - public void run (){ - DefaultPolicyChange_Swing.runTestSwing(); - } - }); + + public static void main(final String[] s) throws Exception { + EventQueue.invokeAndWait(DefaultPolicyChange_Swing::runTestSwing); } + private static void runTestSwing(){ KeyboardFocusManager currentKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - FocusTraversalPolicy defaultFTP = currentKFM.getDefaultFocusTraversalPolicy(); - ContainerOrderFocusTraversalPolicy newFTP = new ContainerOrderFocusTraversalPolicy(); - JFrame jf = new JFrame("Test1"); JWindow jw = new JWindow(jf); @@ -71,22 +64,35 @@ public class DefaultPolicyChange_Swing { throw new RuntimeException("Failure! Swing toplevel must have LayoutFocusTraversalPolicy installed"); } + FocusTraversalPolicy[] defaultFTP = { + jf.getFocusTraversalPolicy(), jw.getFocusTraversalPolicy(), + jd.getFocusTraversalPolicy() + }; + jf.setVisible(true); System.out.println("Now will set another policy."); + ContainerOrderFocusTraversalPolicy newFTP = new ContainerOrderFocusTraversalPolicy(); currentKFM.setDefaultFocusTraversalPolicy(newFTP); - FocusTraversalPolicy resultFTP = jw.getFocusTraversalPolicy(); + FocusTraversalPolicy[] resultFTP = { + jf.getFocusTraversalPolicy(), jw.getFocusTraversalPolicy(), + jd.getFocusTraversalPolicy() + }; System.out.println("FTP current on jf= " + jf.getFocusTraversalPolicy()); System.out.println("FTP current on jw= " + jw.getFocusTraversalPolicy()); System.out.println("FTP current on jd= " + jd.getFocusTraversalPolicy()); - if (!resultFTP.equals(defaultFTP)) { - Sysout.println("Failure! FocusTraversalPolicy should not change"); - Sysout.println("Was: " + defaultFTP); - Sysout.println("Become: " + resultFTP); - throw new RuntimeException("Failure! FocusTraversalPolicy should not change"); + jf.dispose(); + + for (int i=0; i < 3; i++) { + if (!resultFTP[i].equals(defaultFTP[i])) { + System.out.println("Failure! FocusTraversalPolicy should not change"); + System.out.println("Was: " + defaultFTP[i]); + System.out.println("Become: " + resultFTP[i]); + throw new RuntimeException("Failure! FocusTraversalPolicy should not change"); + } } } } From 2af32d911b8a5749be82ce0fddfcd16725251a47 Mon Sep 17 00:00:00 2001 From: Mikhail Cherkasov Date: Tue, 8 Nov 2016 20:11:13 +0300 Subject: [PATCH 085/402] 8156723: JVM crash at sun.java2d.windows.GDIBlitLoops.nativeBlit Reviewed-by: serb --- .../native/libawt/java2d/windows/GDIWindowSurfaceData.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp b/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp index 95e737340fb..f6ba8b01308 100644 --- a/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp @@ -128,7 +128,7 @@ void SetupThreadGraphicsInfo(JNIEnv *env, GDIWinSDOps *wsdo) { return; } hDC = comp->GetDCFromComponent(); - if (hDC != NULL) { + if (hDC != NULL && wsdo->device != NULL) { ::SelectObject(hDC, nullbrush); ::SelectObject(hDC, nullpen); ::SelectClipRgn(hDC, (HRGN) NULL); From acae42fd30954875c5d0c1a4395715d0c3e4994c Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Tue, 8 Nov 2016 12:56:17 -0800 Subject: [PATCH 086/402] 8166379: IAE while invoking javadoc with --patch-module Reviewed-by: jjg --- .../jdk/javadoc/internal/tool/Start.java | 11 +++++++ .../jdk/javadoc/internal/tool/ToolOption.java | 33 +++++-------------- .../jdk/javadoc/tool/modules/Modules.java | 2 +- 3 files changed, 21 insertions(+), 25 deletions(-) diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java index c5b94f3500b..49cd9cdbff0 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/Start.java @@ -939,6 +939,17 @@ public class Start extends ToolOption.Helper { public void put(String name, String value) { compOpts.put(name, value); } + + @Override + public void remove(String name) { + compOpts.remove(name); + } + + @Override + public boolean handleFileManagerOption(com.sun.tools.javac.main.Option option, String value) { + fileManagerOpts.put(option, value); + return true; + } }; } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java index 1949e684dd9..7f4ef90868b 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java @@ -57,63 +57,56 @@ public enum ToolOption { BOOTCLASSPATH("-bootclasspath", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.BOOT_CLASS_PATH, arg); + Option.BOOT_CLASS_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, CLASS_PATH("--class-path -classpath -cp", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.CLASS_PATH, arg); + Option.CLASS_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, EXTDIRS("-extdirs", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.EXTDIRS, arg); + Option.EXTDIRS.process(helper.getOptionHelper(), primaryName, arg); } }, SOURCE_PATH("--source-path -sourcepath", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.SOURCE_PATH, arg); - } - }, - - SYSCLASSPATH("-sysclasspath", HIDDEN, true) { - @Override - public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.BOOT_CLASS_PATH, arg); + Option.SOURCE_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, MODULE_SOURCE_PATH("--module-source-path", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.MODULE_SOURCE_PATH, arg); + Option.MODULE_SOURCE_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, UPGRADE_MODULE_PATH("--upgrade-module-path", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.UPGRADE_MODULE_PATH, arg); + Option.UPGRADE_MODULE_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, SYSTEM("--system", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.SYSTEM, arg); + Option.SYSTEM.process(helper.getOptionHelper(), primaryName, arg); } }, MODULE_PATH("--module-path -p", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.MODULE_PATH, arg); + Option.MODULE_PATH.process(helper.getOptionHelper(), primaryName, arg); } }, @@ -141,7 +134,7 @@ public enum ToolOption { ENCODING("-encoding", STANDARD, true) { @Override public void process(Helper helper, String arg) { - helper.setFileManagerOpt(Option.ENCODING, arg); + Option.ENCODING.process(helper.getOptionHelper(), primaryName, arg); } }, @@ -290,14 +283,6 @@ public enum ToolOption { // ----- output control options ----- - PROMPT("-prompt", HIDDEN) { - @Override - public void process(Helper helper) { - helper.compOpts.put("-prompt", "-prompt"); - helper.promptOnError = true; - } - }, - QUIET("-quiet", STANDARD) { @Override public void process(Helper helper) { diff --git a/langtools/test/jdk/javadoc/tool/modules/Modules.java b/langtools/test/jdk/javadoc/tool/modules/Modules.java index 41114ea5806..39f94b666bf 100644 --- a/langtools/test/jdk/javadoc/tool/modules/Modules.java +++ b/langtools/test/jdk/javadoc/tool/modules/Modules.java @@ -296,7 +296,7 @@ public class Modules extends ModuleTestBase { checkMembersSelected("pkg2.B.f"); } -// @Test @ignore JDK-8166379 + @Test public void testPatchModuleOption(Path base) throws Exception { Path src = base.resolve("src"); Path modulePath = base.resolve("modules"); From 579a6df74726237ec667a20a7ce493e4adfef3b4 Mon Sep 17 00:00:00 2001 From: Dmitry Markov Date: Wed, 9 Nov 2016 15:20:30 +0300 Subject: [PATCH 087/402] 8169355: Diacritics input works incorrectly on Windows if Spanish (Latin American) keyboard layout is used Reviewed-by: ssadetsky --- .../native/libawt/windows/awt_Component.cpp | 2 +- .../SpanishDiacriticsTest.html | 40 +++++++++++++ .../SpanishDiacriticsTest.java | 57 +++++++++++++++++++ 3 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html create mode 100644 jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp index 1e889dcffcd..080fdc8062e 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp @@ -3523,7 +3523,7 @@ UINT AwtComponent::WindowsKeyToJavaChar(UINT wkey, UINT modifiers, TransOps ops, WORD wChar[2]; int converted = 1; - UINT ch = ::MapVirtualKey(wkey, 2); + UINT ch = ::MapVirtualKeyEx(wkey, 2, GetKeyboardLayout()); if (ch & 0x80000000) { // Dead key which is handled as a normal key isDeadKey = deadKeyActive = TRUE; diff --git a/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html new file mode 100644 index 00000000000..af6cd0c7610 --- /dev/null +++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html @@ -0,0 +1,40 @@ + + + + + SpanishDiacriticsTest + + + + +Test run requires the following keyboard layout to be installed: +Windows OS: Spanish (United States) with 'Latin American' keyboard layout + +1. A frame with a text field should be displayed at upper left corner +2. Set focus to the text field and switch to Spanish with 'Latin American' keyboard layout +3. Type the following: ' ' o - i.e. single quote two times (using [ key on US keyboard) then o character. + +If you the text field displays ''o, (i.e. o should be without acute) then the test is passed; otherwise failed. + + diff --git a/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java new file mode 100644 index 00000000000..78877061e60 --- /dev/null +++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169355 + * @summary Check if Spanish diacritical signs could be typed for TextField + * @author Dmitry Markov + * @run applet/manual=yesno SpanishDiacriticsTest.html +*/ + +import javax.swing.*; +import java.applet.Applet; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.concurrent.locks.LockSupport; + +public class SpanishDiacriticsTest extends Applet { + @Override + public void init() { + SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(); + JTextField textField = new JTextField(20); + textField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + LockSupport.parkNanos(1_000_000_000L); + } + }); + frame.add(textField); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + }); + } +} + From 2f430bc9e5203b0ee2ed2f4f019a8999e1eabb1d Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 15 Nov 2016 13:31:52 -0800 Subject: [PATCH 088/402] 8169736: Mark RmiIiopReturnValueTest.java as intermittently failing Reviewed-by: lancea --- .../rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java index 87f5d866507..8ab76ca3e95 100644 --- a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java +++ b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java @@ -24,6 +24,7 @@ /* * @test * @bug 8146975 + * @key intermittent * @summary test RMI-IIOP with value object return * @modules java.corba * @library /lib/testlibrary From 088852ae20c4686bc46cc397ff69462f9f94a467 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 9 Nov 2016 10:26:29 -0800 Subject: [PATCH 089/402] 8169339: Provide internal API to JavaFX to locate JDK fonts Reviewed-by: serb, kcr --- .../classes/sun/font/SunFontManager.java | 8 ++++ .../sun/font/lookup/JDKFontLookup.java | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java diff --git a/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java b/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java index 6ac092ed32e..0b175c35b6b 100644 --- a/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java +++ b/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java @@ -362,6 +362,14 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE { }); } + /** + * If the module image layout changes the location of JDK fonts, + * this will be updated to reflect that. + */ + public static final String getJDKFontDir() { + return jreFontDirName; + } + public TrueTypeFont getEUDCFont() { // Overridden in Windows. return null; diff --git a/jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java b/jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java new file mode 100644 index 00000000000..83af637cfb0 --- /dev/null +++ b/jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.font.lookup; + +import sun.font.SunFontManager; + +/** + * Implementation-class accessed by other JDK modules to + * locate the JDK-provided fonts. + */ +public final class JDKFontLookup { + + public final static String getJDKFontDir() { + return SunFontManager.getJDKFontDir(); + } +} From f385a9f5dd8c0cf0ca5e9585fdb94f96df479cdd Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 9 Nov 2016 11:28:13 -0800 Subject: [PATCH 090/402] 8155874: Fix java.desktop deprecation warnings about Class.newInstance Reviewed-by: serb, alexsch --- .../classes/com/apple/laf/AquaUtils.java | 4 ++-- .../sun/beans/decoder/DocumentHandler.java | 3 ++- .../com/sun/beans/finder/InstanceFinder.java | 2 +- .../com/sun/java/swing/plaf/gtk/GTKStyle.java | 8 ++----- .../sun/media/sound/JARSoundbankReader.java | 6 ++--- .../media/sound/ModelAbstractOscillator.java | 6 ++--- .../classes/java/awt/GraphicsEnvironment.java | 7 ++---- .../share/classes/java/awt/Toolkit.java | 10 ++++---- .../classes/java/awt/print/PrinterJob.java | 7 +++--- .../classes/java/beans/Introspector.java | 4 +++- .../share/classes/java/beans/MetaData.java | 4 ++-- .../java/beans/PropertyDescriptor.java | 4 ++-- .../classes/javax/swing/JEditorPane.java | 2 +- .../share/classes/javax/swing/UIManager.java | 23 +++++++++++++++---- .../javax/swing/text/html/ObjectView.java | 4 ++-- .../classes/sun/awt/FontConfiguration.java | 2 +- .../classes/sun/awt/shell/ShellFolder.java | 7 ++---- .../classes/sun/font/FontManagerFactory.java | 7 +++--- .../classes/sun/java2d/cmm/CMSManager.java | 2 +- .../java2d/loops/GraphicsPrimitiveProxy.java | 9 +++----- .../sun/java2d/pipe/RenderingEngine.java | 4 ++-- .../unix/classes/sun/font/XMap.java | 3 ++- 22 files changed, 62 insertions(+), 66 deletions(-) diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java index 5e7d160943c..1ebbc4b7ddb 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java @@ -179,8 +179,8 @@ final class AquaUtils { T getInstance() { try { ReflectUtil.checkPackageAccess(clazz); - return clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException ignored) { + return clazz.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException ignored) { } return null; } diff --git a/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java b/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java index a30cca32ffd..4289911b0da 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java @@ -280,7 +280,8 @@ public final class DocumentHandler extends DefaultHandler { public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ElementHandler parent = this.handler; try { - this.handler = getElementHandler(qName).newInstance(); + this.handler = + getElementHandler(qName).getDeclaredConstructor().newInstance(); this.handler.setOwner(this); this.handler.setParent(parent); } diff --git a/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java b/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java index 7a46ed70ff9..1080cbcaef7 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java @@ -94,7 +94,7 @@ class InstanceFinder { } if (this.type.isAssignableFrom(type)) { @SuppressWarnings("unchecked") - T tmp = (T) type.newInstance(); + T tmp = (T) type.getDeclaredConstructor().newInstance(); return tmp; } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java index e4281dd6a86..14f08601a25 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java @@ -1131,16 +1131,12 @@ class GTKStyle extends SynthStyle implements GTKConstants { getContextClassLoader()); if (methodName == null) { - return c.newInstance(); + return c.getDeclaredConstructor().newInstance(); } Method m = c.getMethod(methodName, (Class[])null); return m.invoke(c, (Object[])null); - } catch (ClassNotFoundException cnfe) { - } catch (IllegalAccessException iae) { - } catch (InvocationTargetException ite) { - } catch (NoSuchMethodException nsme) { - } catch (InstantiationException ie) { + } catch (ReflectiveOperationException e) { } return null; } diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java index db1a769fbd2..a5bb2b789ee 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java @@ -90,12 +90,10 @@ public final class JARSoundbankReader extends SoundbankReader { Class c = Class.forName(line.trim(), false, ucl); if (Soundbank.class.isAssignableFrom(c)) { ReflectUtil.checkPackageAccess(c); - Object o = c.newInstance(); + Object o = c.getDeclaredConstructor().newInstance(); soundbanks.add((Soundbank) o); } - } catch (ClassNotFoundException ignored) { - } catch (InstantiationException ignored) { - } catch (IllegalAccessException ignored) { + } catch (ReflectiveOperationException ignored) { } } line = r.readLine(); diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java index 0bbb5466cb8..599e59e5f72 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java @@ -137,10 +137,8 @@ public abstract class ModelAbstractOscillator public ModelOscillatorStream open(float samplerate) { ModelAbstractOscillator oscs; try { - oscs = this.getClass().newInstance(); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { + oscs = this.getClass().getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); } oscs.setSampleRate(samplerate); diff --git a/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java b/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java index ab2a8467e9a..01fcf17714d 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java +++ b/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java @@ -108,7 +108,7 @@ public abstract class GraphicsEnvironment { ClassLoader cl = ClassLoader.getSystemClassLoader(); geCls = Class.forName(nm, true, cl); } - ge = (GraphicsEnvironment)geCls.newInstance(); + ge = (GraphicsEnvironment)geCls.getConstructor().newInstance(); // long t1 = System.currentTimeMillis(); // System.out.println("GE creation took " + (t1-t0)+ "ms."); if (isHeadless()) { @@ -116,12 +116,9 @@ public abstract class GraphicsEnvironment { } } catch (ClassNotFoundException e) { throw new Error("Could not find class: "+nm); - } catch (InstantiationException e) { + } catch (ReflectiveOperationException | IllegalArgumentException e) { throw new Error("Could not instantiate Graphics Environment: " + nm); - } catch (IllegalAccessException e) { - throw new Error ("Could not access Graphics Environment: " - + nm); } return ge; } diff --git a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java index 9d00222ed2c..f4bfd11072e 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java @@ -468,7 +468,7 @@ public abstract class Toolkit { private static void fallbackToLoadClassForAT(String atName) { try { Class c = Class.forName(atName, false, ClassLoader.getSystemClassLoader()); - c.newInstance(); + c.getConstructor().newInstance(); } catch (ClassNotFoundException e) { newAWTError(e, "Assistive Technology not found: " + atName); } catch (InstantiationException e) { @@ -583,15 +583,13 @@ public abstract class Toolkit { } try { if (cls != null) { - toolkit = (Toolkit)cls.newInstance(); + toolkit = (Toolkit)cls.getConstructor().newInstance(); if (GraphicsEnvironment.isHeadless()) { toolkit = new HeadlessToolkit(toolkit); } } - } catch (final InstantiationException ignored) { - throw new AWTError("Could not instantiate Toolkit: " + nm); - } catch (final IllegalAccessException ignored) { - throw new AWTError("Could not access Toolkit: " + nm); + } catch (final ReflectiveOperationException ignored) { + throw new AWTError("Could not create Toolkit: " + nm); } return null; } diff --git a/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java b/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java index 5a1cf128607..0e4d7f96e05 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java +++ b/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java @@ -79,13 +79,12 @@ public abstract class PrinterJob { public PrinterJob run() { String nm = System.getProperty("java.awt.printerjob", null); try { - return (PrinterJob)Class.forName(nm).newInstance(); + return (PrinterJob)Class.forName(nm). + getConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new AWTError("PrinterJob not found: " + nm); - } catch (InstantiationException e) { + } catch (ReflectiveOperationException e) { throw new AWTError("Could not instantiate PrinterJob: " + nm); - } catch (IllegalAccessException e) { - throw new AWTError("Could not access PrinterJob: " + nm); } } }); diff --git a/jdk/src/java.desktop/share/classes/java/beans/Introspector.java b/jdk/src/java.desktop/share/classes/java/beans/Introspector.java index 7bf64ce02d6..4bab862d5ff 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/Introspector.java +++ b/jdk/src/java.desktop/share/classes/java/beans/Introspector.java @@ -36,6 +36,7 @@ import java.awt.Component; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -1280,11 +1281,12 @@ public class Introspector { */ static Object instantiate(Class sibling, String className) throws InstantiationException, IllegalAccessException, + NoSuchMethodException, InvocationTargetException, ClassNotFoundException { // First check with sibling's classloader (if any). ClassLoader cl = sibling.getClassLoader(); Class cls = ClassFinder.findClass(className, cl); - return cls.newInstance(); + return cls.getDeclaredConstructor().newInstance(); } } // end class Introspector diff --git a/jdk/src/java.desktop/share/classes/java/beans/MetaData.java b/jdk/src/java.desktop/share/classes/java/beans/MetaData.java index 1443ce2b54f..c5adc1cf912 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/MetaData.java +++ b/jdk/src/java.desktop/share/classes/java/beans/MetaData.java @@ -1261,9 +1261,9 @@ static final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Pe internalPersistenceDelegates.put(typeName, defaultPersistenceDelegate); try { String name = type.getName(); - Class c = Class.forName("java.beans.MetaData$" + name.replace('.', '_') + Class c = Class.forName("java.beans.MetaData$" + name.replace('.', '_') + "_PersistenceDelegate"); - pd = (PersistenceDelegate)c.newInstance(); + pd = (PersistenceDelegate)c.getDeclaredConstructor().newInstance(); internalPersistenceDelegates.put(typeName, pd); } catch (ClassNotFoundException e) { diff --git a/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java b/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java index 440c73b616e..3d142b8baf9 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java +++ b/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java @@ -470,14 +470,14 @@ public class PropertyDescriptor extends FeatureDescriptor { Constructor ctor = null; if (bean != null) { try { - ctor = cls.getConstructor(new Class[] { Object.class }); + ctor = cls.getDeclaredConstructor(new Class[] { Object.class }); } catch (Exception ex) { // Fall through } } try { if (ctor == null) { - editor = cls.newInstance(); + editor = cls.getDeclaredConstructor().newInstance(); } else { editor = ctor.newInstance(new Object[] { bean }); } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java index c8aad16e84e..aed7fd3b992 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java @@ -1196,7 +1196,7 @@ public class JEditorPane extends JTextComponent { // registerEditorKitForContentType(type, class, null). c = SwingUtilities.loadSystemClass(classname); } - k = (EditorKit) c.newInstance(); + k = (EditorKit) c.getDeclaredConstructor().newInstance(); kitRegistry.put(type, k); } catch (Throwable e) { k = null; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java b/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java index caadac4d28d..33e4a4c27c1 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java @@ -526,14 +526,16 @@ public class UIManager implements Serializable if (info.getName().equals(name)) { Class cls = Class.forName(UIManager.class.getModule(), info.getClassName()); - LookAndFeel laf = (LookAndFeel) cls.newInstance(); + LookAndFeel laf = + (LookAndFeel) cls.getDeclaredConstructor().newInstance(); if (!laf.isSupportedLookAndFeel()) { break; } return laf; } } - } catch (InstantiationException | IllegalAccessException ignore) { + } catch (ReflectiveOperationException | + IllegalArgumentException ignore) { } throw new UnsupportedLookAndFeelException(name); @@ -625,7 +627,16 @@ public class UIManager implements Serializable } else { Class lnfClass = SwingUtilities.loadSystemClass(className); - setLookAndFeel((LookAndFeel)(lnfClass.newInstance())); + try { + LookAndFeel laf = + (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); + setLookAndFeel(laf); + } catch (ReflectiveOperationException | IllegalArgumentException e) { + InstantiationException ex = + new InstantiationException("Wrapped Exception"); + ex.initCause(e); + throw ex; + } } } @@ -1093,7 +1104,8 @@ public class UIManager implements Serializable String className = getLAFState().swingProps.getProperty(multiplexingLAFKey, defaultName); try { Class lnfClass = SwingUtilities.loadSystemClass(className); - multiLookAndFeel = (LookAndFeel)lnfClass.newInstance(); + multiLookAndFeel = + (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); } catch (Exception exc) { System.err.println("UIManager: failed loading " + className); } @@ -1427,7 +1439,8 @@ public class UIManager implements Serializable String className = p.nextToken(); try { Class lnfClass = SwingUtilities.loadSystemClass(className); - LookAndFeel newLAF = (LookAndFeel)lnfClass.newInstance(); + LookAndFeel newLAF = + (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); newLAF.initialize(); auxLookAndFeels.addElement(newLAF); } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java index c40bdfc592b..f1f7e4f4f50 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java @@ -46,7 +46,7 @@ import sun.reflect.misc.ReflectUtil; *

    * If the class can successfully be loaded, an attempt will * be made to create an instance of it by calling - * Class.newInstance. An attempt will be made + * Class.getDeclaredConstructor().newInstance. An attempt will be made * to narrow the instance to type java.awt.Component * to display the object. *

    @@ -92,7 +92,7 @@ public class ObjectView extends ComponentView { ReflectUtil.checkPackageAccess(classname); Class c = Class.forName(classname, true,Thread.currentThread(). getContextClassLoader()); - Object o = c.newInstance(); + Object o = c.getDeclaredConstructor().newInstance(); if (o instanceof Component) { Component comp = (Component) o; setParameters(comp, attr); diff --git a/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java b/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java index d5190db0a0e..3945940be2d 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java @@ -971,7 +971,7 @@ public abstract class FontConfiguration { if (fcc != null) { try { - fc = (Charset) fcc.newInstance(); + fc = (Charset) fcc.getDeclaredConstructor().newInstance(); } catch (Exception e) { } } diff --git a/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java b/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java index 2b48a58de01..d01a401825d 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java @@ -226,13 +226,10 @@ public abstract class ShellFolder extends File { } try { shellFolderManager = - (ShellFolderManager)managerClass.newInstance(); - } catch (InstantiationException e) { + (ShellFolderManager)managerClass.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { throw new Error("Could not instantiate Shell Folder Manager: " + managerClass.getName()); - } catch (IllegalAccessException e) { - throw new Error ("Could not access Shell Folder Manager: " - + managerClass.getName()); } invoker = shellFolderManager.createInvoker(); diff --git a/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java b/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java index 4faa48e1f4d..695541f6d66 100644 --- a/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java +++ b/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java @@ -80,10 +80,9 @@ public final class FontManagerFactory { DEFAULT_CLASS); ClassLoader cl = ClassLoader.getSystemClassLoader(); Class fmClass = Class.forName(fmClassName, true, cl); - instance = (FontManager) fmClass.newInstance(); - } catch (ClassNotFoundException | - InstantiationException | - IllegalAccessException ex) { + instance = + (FontManager) fmClass.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException ex) { throw new InternalError(ex); } diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java b/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java index 6036a3c2636..fea14af51ed 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java @@ -57,7 +57,7 @@ public class CMSManager { if (cmmProviderClass != null) { try { Class cls = Class.forName(cmmProviderClass); - provider = (CMMServiceProvider)cls.newInstance(); + provider = (CMMServiceProvider)cls.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { } } diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java b/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java index 73f18a60946..1644b8c3be7 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java @@ -81,18 +81,15 @@ public class GraphicsPrimitiveProxy extends GraphicsPrimitive { + relativeClassName; try { Class clazz = Class.forName(name); - GraphicsPrimitive p = (GraphicsPrimitive) clazz.newInstance(); + GraphicsPrimitive p = + (GraphicsPrimitive) clazz.getDeclaredConstructor().newInstance(); if (!satisfiesSameAs(p)) { throw new RuntimeException("Primitive " + p + " incompatible with proxy for " + name); } return p; - } catch (ClassNotFoundException ex) { - throw new RuntimeException(ex.toString()); - } catch (InstantiationException ex) { - throw new RuntimeException(ex.toString()); - } catch (IllegalAccessException ex) { + } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex.toString()); } // A RuntimeException should never happen in a deployed JDK, because diff --git a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java index b8c3bc7d5fd..7896f13d971 100644 --- a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java +++ b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java @@ -127,7 +127,7 @@ public abstract class RenderingEngine { if (reClass != null) { try { Class cls = Class.forName(reClass); - reImpl = (RenderingEngine) cls.newInstance(); + reImpl = (RenderingEngine) cls.getConstructor().newInstance(); } catch (ReflectiveOperationException ignored0) { } } @@ -135,7 +135,7 @@ public abstract class RenderingEngine { final String marlinREClass = "sun.java2d.marlin.MarlinRenderingEngine"; try { Class cls = Class.forName(marlinREClass); - reImpl = (RenderingEngine) cls.newInstance(); + reImpl = (RenderingEngine) cls.getConstructor().newInstance(); } catch (ReflectiveOperationException ignored1) { } } diff --git a/jdk/src/java.desktop/unix/classes/sun/font/XMap.java b/jdk/src/java.desktop/unix/classes/sun/font/XMap.java index 39f3dfcaf6b..b2ace270b68 100644 --- a/jdk/src/java.desktop/unix/classes/sun/font/XMap.java +++ b/jdk/src/java.desktop/unix/classes/sun/font/XMap.java @@ -172,7 +172,8 @@ class XMap { if (className != null) { try { if (className.startsWith("sun.awt")) { - enc = ((Charset)Class.forName(className).newInstance()).newEncoder(); + enc = ((Charset)Class.forName(className).getDeclaredConstructor(). + newInstance()).newEncoder(); } else { enc = Charset.forName(className).newEncoder(); } From b9f35ce0be53cb545adf371ab21dc6e9f62067ef Mon Sep 17 00:00:00 2001 From: Prasanta Sadhukhan Date: Thu, 10 Nov 2016 12:23:14 +0530 Subject: [PATCH 091/402] 8160888: [PIT] What to expect of updated java/awt/print/PrinterJob/Margins.java Reviewed-by: prr --- .../java/awt/print/PrinterJob/Margins.java | 47 +++++++++++++++---- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/jdk/test/java/awt/print/PrinterJob/Margins.java b/jdk/test/java/awt/print/PrinterJob/Margins.java index c55ae8a6423..792246d1ef1 100644 --- a/jdk/test/java/awt/print/PrinterJob/Margins.java +++ b/jdk/test/java/awt/print/PrinterJob/Margins.java @@ -23,12 +23,12 @@ /** * @test - * @bug 6543815 6601097 + * @bug 6543815 6601097 8160888 * @summary Image should be sent to printer, no exceptions thrown. * The 3 printouts should have a rectangle which is the minimum * possible margins ie, the margins should be hardware margins * and not java default 1 inch margins. - * @run main/manual Margins + * @run main Margins */ import java.awt.print.PrinterJob; @@ -39,16 +39,36 @@ import java.awt.print.PrinterException; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; +import java.awt.Robot; +import java.awt.event.KeyEvent; public class Margins implements Printable { - public static void main(String args[]) { + public static void main(String args[]) throws Exception { + Robot robot = new Robot(); + Thread t = new Thread (() -> { + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + }); + PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pageFormat = job.defaultPage(); Paper paper = pageFormat.getPaper(); double wid = paper.getWidth(); double hgt = paper.getHeight(); paper.setImageableArea(0, -10, wid, hgt); + t.start(); + pageFormat = job.pageDialog(pageFormat); pageFormat.setPaper(paper); job.setPrintable(new Margins(), pageFormat); @@ -57,7 +77,7 @@ public class Margins implements Printable { } catch (PrinterException e) { } - paper.setImageableArea(0, 0, wid, hgt+72); + paper.setImageableArea(0, 0, wid, hgt + 72); pageFormat = job.pageDialog(pageFormat); pageFormat.setPaper(paper); @@ -100,12 +120,13 @@ public class Margins implements Printable { Paper paper = pf.getPaper(); - double wid = paper.getWidth(); - double hgt = paper.getHeight(); - - /* If imageable width/height is -ve, then print was done with 1" margin - * ie ix=72 iy=72 iw=451 ih=697 and wid=595 - * but with fix, we get print with hardware margin ie + int wid = (int)paper.getWidth(); + int hgt = (int)paper.getHeight(); + System.out.println("wid="+wid+" hgt="+hgt); + /* + * If imageable width/height is -ve, then print was done with 1" margin + * e.g. ix=72 iy=72 iw=451 ih=697 and paper wid=595 + * but with fix, we get print with hardware margin e.g. * ix=12, iy=12, iw=571, ih=817 */ if ((wid - iw > 72) || (hgt - ih > 72)) { @@ -115,6 +136,12 @@ public class Margins implements Printable { throw new RuntimeException("Printable width or height " + "exceeds paper width or height."); } + // runtime checking to see if the margins/printable area + // correspond to the entire size of the paper, for now, make it pass + // as for linux, the hwmargin is not taken into account - bug6574279 + if (ix == 0 && iy == 0 && (ix+iw == wid) && (iy+ih == hgt)) { + return PAGE_EXISTS; + } Graphics2D g2d = (Graphics2D)g; g2d.translate(ix, iy); From b40c63e9fbf5bc1078bb867690c9d282a630a09b Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Thu, 10 Nov 2016 17:27:01 +0100 Subject: [PATCH 092/402] 8166700: NPE during invoking getEnclosedElements() on javax.lang.model.element.Element instance representing a package Should not strip first parameter of a local class constructor for local classes in initializers. Reviewed-by: jjg --- .../com/sun/tools/javac/code/Scope.java | 8 +- .../com/sun/tools/javac/jvm/ClassReader.java | 7 +- .../model/LocalClasses/LocalClassesModel.java | 73 ++++++++ .../model/LocalClasses/LocalClassesModel.out | 12 ++ .../model/LocalClasses/LocalTest$1Local.jcod | 77 +++++++++ .../model/LocalClasses/LocalTest$2Local.jcod | 90 ++++++++++ .../model/LocalClasses/LocalTest$3Local.jcod | 79 +++++++++ .../model/LocalClasses/LocalTest$4Local.jcod | 92 ++++++++++ .../model/LocalClasses/LocalTest$5Local.jcod | 90 ++++++++++ .../model/LocalClasses/LocalTest.jcod | 160 ++++++++++++++++++ .../model/LocalClasses/LocalTest.orign | 43 +++++ 11 files changed, 729 insertions(+), 2 deletions(-) create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.out create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$1Local.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$2Local.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$3Local.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$4Local.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$5Local.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.jcod create mode 100644 langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.orign diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java index fbdb07ef248..5b7d30c80b0 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Scope.java @@ -137,12 +137,18 @@ public abstract class Scope { /** Returns true iff the given Symbol is in this scope or any outward scope. */ public boolean includes(final Symbol sym) { + return includes(sym, RECURSIVE); + } + + /** Returns true iff the given Symbol is in this scope, optionally checking outward scopes. + */ + public boolean includes(final Symbol sym, LookupKind lookupKind) { return getSymbolsByName(sym.name, new Filter() { @Override public boolean accepts(Symbol t) { return t == sym; } - }).iterator().hasNext(); + }, lookupKind).iterator().hasNext(); } /** Returns true iff this scope does not contain any Symbol. Does not inspect outward scopes. diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java index c1e0964aaef..1416d2b8b9b 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java @@ -62,6 +62,7 @@ import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Kinds.Kind.*; +import com.sun.tools.javac.code.Scope.LookupKind; import static com.sun.tools.javac.code.TypeTag.ARRAY; import static com.sun.tools.javac.code.TypeTag.CLASS; import static com.sun.tools.javac.code.TypeTag.TYPEVAR; @@ -2186,7 +2187,11 @@ public class ClassReader { // Sometimes anonymous classes don't have an outer // instance, however, there is no reliable way to tell so // we never strip this$n - if (!currentOwner.name.isEmpty()) + // ditto for local classes. Local classes that have an enclosing method set + // won't pass the "hasOuterInstance" check above, but those that don't have an + // enclosing method (i.e. from initializers) will pass that check. + boolean local = !currentOwner.owner.members().includes(currentOwner, LookupKind.NON_RECURSIVE); + if (!currentOwner.name.isEmpty() && !local) type = new MethodType(adjustMethodParams(flags, type.getParameterTypes()), type.getReturnType(), type.getThrownTypes(), diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java b/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java new file mode 100644 index 00000000000..9f8a3977305 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8166700 + * @summary Check that local classes originating in static initializer can be loaded properly. + * @modules jdk.compiler + * @build LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest + * @compile LocalClassesModel.java + * @compile/process/ref=LocalClassesModel.out -processor LocalClassesModel LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest + */ + +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.util.ElementFilter; + +@SupportedAnnotationTypes("*") +public class LocalClassesModel extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement root : ElementFilter.typesIn(roundEnv.getRootElements())) { + System.out.println(processingEnv.getElementUtils().getBinaryName(root)); + for (ExecutableElement constr : ElementFilter.constructorsIn(root.getEnclosedElements())) { + System.out.print(" ("); + boolean first = true; + for (VariableElement param : constr.getParameters()) { + if (!first) { + System.out.print(", "); + } + first = false; + System.out.print(param.asType().toString()); + } + System.out.println(")"); + } + } + + return false; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } +} \ No newline at end of file diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.out b/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.out new file mode 100644 index 00000000000..895193116f3 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.out @@ -0,0 +1,12 @@ +LocalTest$1Local + () +LocalTest$2Local + (LocalTest) +LocalTest$3Local + () +LocalTest$4Local + (LocalTest) +LocalTest$5Local + (LocalTest) +LocalTest + () diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$1Local.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$1Local.jcod new file mode 100644 index 00000000000..3ffaeecee84 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$1Local.jcod @@ -0,0 +1,77 @@ +class LocalTest$1Local { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Method #3 #12; // #1 + class #13; // #2 + class #16; // #3 + Utf8 ""; // #4 + Utf8 "()V"; // #5 + Utf8 "Code"; // #6 + Utf8 "LineNumberTable"; // #7 + Utf8 "SourceFile"; // #8 + Utf8 "LocalTest.java"; // #9 + Utf8 "EnclosingMethod"; // #10 + class #17; // #11 + NameAndType #4 #5; // #12 + Utf8 "LocalTest$1Local"; // #13 + Utf8 "Local"; // #14 + Utf8 "InnerClasses"; // #15 + Utf8 "java/lang/Object"; // #16 + Utf8 "LocalTest"; // #17 + } // Constant Pool + + 0x0020; // access + #2;// this_cpx + #3;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + } // fields + + [] { // methods + { // Member + 0x0000; // access + #4; // name_cpx + #5; // sig_cpx + [] { // Attributes + Attr(#6) { // Code + 1; // max_stack + 1; // max_locals + Bytes[]{ + 0x2AB70001B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#7) { // LineNumberTable + [] { // LineNumberTable + 0 3; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#8) { // SourceFile + #9; + } // end SourceFile + ; + Attr(#10) { // EnclosingMethod + #11 #0; + } // end EnclosingMethod + ; + Attr(#15) { // InnerClasses + [] { // InnerClasses + #2 #0 #14 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest$1Local diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$2Local.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$2Local.jcod new file mode 100644 index 00000000000..23808b81b1b --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$2Local.jcod @@ -0,0 +1,90 @@ +class LocalTest$2Local { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Field #3 #15; // #1 + Method #4 #16; // #2 + class #17; // #3 + class #20; // #4 + Utf8 "this$0"; // #5 + Utf8 "LLocalTest;"; // #6 + Utf8 ""; // #7 + Utf8 "(LLocalTest;)V"; // #8 + Utf8 "Code"; // #9 + Utf8 "LineNumberTable"; // #10 + Utf8 "SourceFile"; // #11 + Utf8 "LocalTest.java"; // #12 + Utf8 "EnclosingMethod"; // #13 + class #21; // #14 + NameAndType #5 #6; // #15 + NameAndType #7 #22; // #16 + Utf8 "LocalTest$2Local"; // #17 + Utf8 "Local"; // #18 + Utf8 "InnerClasses"; // #19 + Utf8 "java/lang/Object"; // #20 + Utf8 "LocalTest"; // #21 + Utf8 "()V"; // #22 + } // Constant Pool + + 0x0020; // access + #3;// this_cpx + #4;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + { // Member + 0x1010; // access + #5; // name_cpx + #6; // sig_cpx + [] { // Attributes + } // Attributes + } // Member + } // fields + + [] { // methods + { // Member + 0x0000; // access + #7; // name_cpx + #8; // sig_cpx + [] { // Attributes + Attr(#9) { // Code + 2; // max_stack + 2; // max_locals + Bytes[]{ + 0x2A2BB500012AB700; + 0x02B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#10) { // LineNumberTable + [] { // LineNumberTable + 0 6; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#11) { // SourceFile + #12; + } // end SourceFile + ; + Attr(#13) { // EnclosingMethod + #14 #0; + } // end EnclosingMethod + ; + Attr(#19) { // InnerClasses + [] { // InnerClasses + #3 #0 #18 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest$2Local diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$3Local.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$3Local.jcod new file mode 100644 index 00000000000..fd7d2681f2e --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$3Local.jcod @@ -0,0 +1,79 @@ +class LocalTest$3Local { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Method #3 #13; // #1 + class #14; // #2 + class #17; // #3 + Utf8 ""; // #4 + Utf8 "()V"; // #5 + Utf8 "Code"; // #6 + Utf8 "LineNumberTable"; // #7 + Utf8 "SourceFile"; // #8 + Utf8 "LocalTest.java"; // #9 + Utf8 "EnclosingMethod"; // #10 + class #18; // #11 + NameAndType #19 #5; // #12 + NameAndType #4 #5; // #13 + Utf8 "LocalTest$3Local"; // #14 + Utf8 "Local"; // #15 + Utf8 "InnerClasses"; // #16 + Utf8 "java/lang/Object"; // #17 + Utf8 "LocalTest"; // #18 + Utf8 "test1"; // #19 + } // Constant Pool + + 0x0020; // access + #2;// this_cpx + #3;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + } // fields + + [] { // methods + { // Member + 0x0000; // access + #4; // name_cpx + #5; // sig_cpx + [] { // Attributes + Attr(#6) { // Code + 1; // max_stack + 1; // max_locals + Bytes[]{ + 0x2AB70001B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#7) { // LineNumberTable + [] { // LineNumberTable + 0 9; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#8) { // SourceFile + #9; + } // end SourceFile + ; + Attr(#10) { // EnclosingMethod + #11 #12; + } // end EnclosingMethod + ; + Attr(#16) { // InnerClasses + [] { // InnerClasses + #2 #0 #15 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest$3Local diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$4Local.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$4Local.jcod new file mode 100644 index 00000000000..737dcb43c82 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$4Local.jcod @@ -0,0 +1,92 @@ +class LocalTest$4Local { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Field #3 #16; // #1 + Method #4 #17; // #2 + class #18; // #3 + class #21; // #4 + Utf8 "this$0"; // #5 + Utf8 "LLocalTest;"; // #6 + Utf8 ""; // #7 + Utf8 "(LLocalTest;)V"; // #8 + Utf8 "Code"; // #9 + Utf8 "LineNumberTable"; // #10 + Utf8 "SourceFile"; // #11 + Utf8 "LocalTest.java"; // #12 + Utf8 "EnclosingMethod"; // #13 + class #22; // #14 + NameAndType #23 #24; // #15 + NameAndType #5 #6; // #16 + NameAndType #7 #24; // #17 + Utf8 "LocalTest$4Local"; // #18 + Utf8 "Local"; // #19 + Utf8 "InnerClasses"; // #20 + Utf8 "java/lang/Object"; // #21 + Utf8 "LocalTest"; // #22 + Utf8 "test2"; // #23 + Utf8 "()V"; // #24 + } // Constant Pool + + 0x0020; // access + #3;// this_cpx + #4;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + { // Member + 0x1010; // access + #5; // name_cpx + #6; // sig_cpx + [] { // Attributes + } // Attributes + } // Member + } // fields + + [] { // methods + { // Member + 0x0000; // access + #7; // name_cpx + #8; // sig_cpx + [] { // Attributes + Attr(#9) { // Code + 2; // max_stack + 2; // max_locals + Bytes[]{ + 0x2A2BB500012AB700; + 0x02B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#10) { // LineNumberTable + [] { // LineNumberTable + 0 12; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#11) { // SourceFile + #12; + } // end SourceFile + ; + Attr(#13) { // EnclosingMethod + #14 #15; + } // end EnclosingMethod + ; + Attr(#20) { // InnerClasses + [] { // InnerClasses + #3 #0 #19 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest$4Local diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$5Local.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$5Local.jcod new file mode 100644 index 00000000000..f377dbec956 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest$5Local.jcod @@ -0,0 +1,90 @@ +class LocalTest$5Local { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Field #3 #16; // #1 + Method #4 #15; // #2 + class #17; // #3 + class #20; // #4 + Utf8 "this$0"; // #5 + Utf8 "LLocalTest;"; // #6 + Utf8 ""; // #7 + Utf8 "(LLocalTest;)V"; // #8 + Utf8 "Code"; // #9 + Utf8 "LineNumberTable"; // #10 + Utf8 "SourceFile"; // #11 + Utf8 "LocalTest.java"; // #12 + Utf8 "EnclosingMethod"; // #13 + class #21; // #14 + NameAndType #7 #22; // #15 + NameAndType #5 #6; // #16 + Utf8 "LocalTest$5Local"; // #17 + Utf8 "Local"; // #18 + Utf8 "InnerClasses"; // #19 + Utf8 "java/lang/Object"; // #20 + Utf8 "LocalTest"; // #21 + Utf8 "()V"; // #22 + } // Constant Pool + + 0x0020; // access + #3;// this_cpx + #4;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + { // Member + 0x1010; // access + #5; // name_cpx + #6; // sig_cpx + [] { // Attributes + } // Attributes + } // Member + } // fields + + [] { // methods + { // Member + 0x0000; // access + #7; // name_cpx + #8; // sig_cpx + [] { // Attributes + Attr(#9) { // Code + 2; // max_stack + 2; // max_locals + Bytes[]{ + 0x2A2BB500012AB700; + 0x02B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#10) { // LineNumberTable + [] { // LineNumberTable + 0 15; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#11) { // SourceFile + #12; + } // end SourceFile + ; + Attr(#13) { // EnclosingMethod + #14 #15; + } // end EnclosingMethod + ; + Attr(#19) { // InnerClasses + [] { // InnerClasses + #3 #0 #18 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest$5Local diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.jcod b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.jcod new file mode 100644 index 00000000000..7bde5b0329b --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.jcod @@ -0,0 +1,160 @@ +class LocalTest { + 0xCAFEBABE; + 0; // minor version + 52; // version + [] { // Constant Pool + ; // first element is empty + Method #3 #20; // #1 + class #21; // #2 + class #22; // #3 + class #23; // #4 + Utf8 "Local"; // #5 + Utf8 "InnerClasses"; // #6 + class #24; // #7 + class #25; // #8 + class #26; // #9 + class #27; // #10 + Utf8 "test1"; // #11 + Utf8 "()V"; // #12 + Utf8 "Code"; // #13 + Utf8 "LineNumberTable"; // #14 + Utf8 "test2"; // #15 + Utf8 ""; // #16 + Utf8 ""; // #17 + Utf8 "SourceFile"; // #18 + Utf8 "LocalTest.java"; // #19 + NameAndType #16 #12; // #20 + Utf8 "LocalTest"; // #21 + Utf8 "java/lang/Object"; // #22 + Utf8 "LocalTest$5Local"; // #23 + Utf8 "LocalTest$4Local"; // #24 + Utf8 "LocalTest$3Local"; // #25 + Utf8 "LocalTest$2Local"; // #26 + Utf8 "LocalTest$1Local"; // #27 + } // Constant Pool + + 0x0021; // access + #2;// this_cpx + #3;// super_cpx + + [] { // Interfaces + } // Interfaces + + [] { // fields + } // fields + + [] { // methods + { // Member + 0x0008; // access + #11; // name_cpx + #12; // sig_cpx + [] { // Attributes + Attr(#13) { // Code + 0; // max_stack + 0; // max_locals + Bytes[]{ + 0xB1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#14) { // LineNumberTable + [] { // LineNumberTable + 0 10; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member + 0x0000; // access + #15; // name_cpx + #12; // sig_cpx + [] { // Attributes + Attr(#13) { // Code + 0; // max_stack + 1; // max_locals + Bytes[]{ + 0xB1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#14) { // LineNumberTable + [] { // LineNumberTable + 0 13; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member + 0x0000; // access + #16; // name_cpx + #12; // sig_cpx + [] { // Attributes + Attr(#13) { // Code + 1; // max_stack + 1; // max_locals + Bytes[]{ + 0x2AB70001B1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#14) { // LineNumberTable + [] { // LineNumberTable + 0 14; + 4 16; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + ; + { // Member + 0x0008; // access + #17; // name_cpx + #12; // sig_cpx + [] { // Attributes + Attr(#13) { // Code + 0; // max_stack + 0; // max_locals + Bytes[]{ + 0xB1; + }; + [] { // Traps + } // end Traps + [] { // Attributes + Attr(#14) { // LineNumberTable + [] { // LineNumberTable + 0 4; + } + } // end LineNumberTable + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [] { // Attributes + Attr(#18) { // SourceFile + #19; + } // end SourceFile + ; + Attr(#6) { // InnerClasses + [] { // InnerClasses + #4 #0 #5 0; + #7 #0 #5 0; + #8 #0 #5 0; + #9 #0 #5 0; + #10 #0 #5 0; + } + } // end InnerClasses + } // Attributes +} // end class LocalTest diff --git a/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.orign b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.orign new file mode 100644 index 00000000000..7f56f2e4e68 --- /dev/null +++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalTest.orign @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/**The jcod files are generated from this file, compiled by JDK 8 javac. + */ +public class LocalTest { + static { + class Local { } + } + { + class Local { } + } + static void test1() { + class Local { } + } + void test2() { + class Local { } + } + LocalTest() { + class Local { } + } +} + From a1f6786ab948034e773c94ddc68f3a5f4ee43c04 Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Thu, 10 Nov 2016 13:29:34 -0800 Subject: [PATCH 093/402] 8169447: javac should detect/reject repeated use of --patch-module on command line Reviewed-by: jlahoda --- .../com/sun/tools/javac/main/Option.java | 54 +++++++++++-------- .../tools/javac/resources/javac.properties | 2 + .../tools/javac/modules/PatchModulesTest.java | 31 ++++++++++- 3 files changed, 62 insertions(+), 25 deletions(-) diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java index 756b0080bc2..7dd835f82fb 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java @@ -35,6 +35,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -43,6 +44,7 @@ import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.TreeSet; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -200,31 +202,37 @@ public enum Option { // The standard file manager code knows to split apart the NULL-separated components. @Override public boolean process(OptionHelper helper, String option, String arg) { - if (!arg.contains("=")) { // could be more strict regeex, e.g. "(?i)[a-z0-9_.]+=.*" - helper.error(Errors.LocnInvalidArgForXpatch(arg)); + if (arg.isEmpty()) { + helper.error("err.no.value.for.option", option); + return true; + } else if (getPattern().matcher(arg).matches()) { + String prev = helper.get(PATCH_MODULE); + if (prev == null) { + super.process(helper, option, arg); + return false; + } else { + String argModulePackage = arg.substring(0, arg.indexOf('=')); + boolean isRepeated = Arrays.stream(prev.split("\0")) + .map(s -> s.substring(0, s.indexOf('='))) + .collect(Collectors.toSet()) + .contains(argModulePackage); + if (isRepeated) { + helper.error("err.repeated.value.for.patch.module", argModulePackage); + return true; + } else { + super.process(helper, option, prev + '\0' + arg); + return false; + } + } + } else { + helper.error("err.bad.value.for.option", option, arg); + return true; } + } - String previous = helper.get(this); - if (previous == null) { - return super.process(helper, option, arg); - } - - Map map = new LinkedHashMap<>(); - for (String s : previous.split("\0")) { - int sep = s.indexOf('='); - map.put(s.substring(0, sep), s.substring(sep + 1)); - } - - int sep = arg.indexOf('='); - map.put(arg.substring(0, sep), arg.substring(sep + 1)); - - StringBuilder sb = new StringBuilder(); - map.forEach((m, p) -> { - if (sb.length() > 0) - sb.append('\0'); - sb.append(m).append('=').append(p); - }); - return super.process(helper, option, sb.toString()); + @Override + public Pattern getPattern() { + return Pattern.compile("([^/]+)=(,*[^,].*)"); } }, diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties index faa6db19881..6acb5db137d 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties @@ -361,6 +361,8 @@ javac.err.bad.value.for.option=\ bad value for {0} option: ''{1}'' javac.err.no.value.for.option=\ no value for {0} option +javac.err.repeated.value.for.patch.module=\ + --patch-module specified more than once for {0} ## messages diff --git a/langtools/test/tools/javac/modules/PatchModulesTest.java b/langtools/test/tools/javac/modules/PatchModulesTest.java index bf481c596e4..648ba4901ac 100644 --- a/langtools/test/tools/javac/modules/PatchModulesTest.java +++ b/langtools/test/tools/javac/modules/PatchModulesTest.java @@ -91,12 +91,28 @@ public class PatchModulesTest extends ModuleTestBase { } @Test - public void testLastOneWins(Path base) throws Exception { + public void testDuplicates(Path base) throws Exception { test(asList("java.base=a", "java.compiler=b", "java.base=c"), - "{java.base=[c], java.compiler=[b]}"); + false, "--patch-module specified more than once for java.base"); + } + + @Test + public void testEmpty(Path base) throws Exception { + test(asList(""), + false, "no value for --patch-module option"); + } + + @Test + public void testInvalid(Path base) throws Exception { + test(asList("java.base/java.lang=."), + false, "bad value for --patch-module option: 'java.base/java.lang=.'"); } void test(List patches, String expect) throws Exception { + test(patches, true, expect); + } + + void test(List patches, boolean expectOK, String expect) throws Exception { JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler(); StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { @@ -116,6 +132,17 @@ public class PatchModulesTest extends ModuleTestBase { Map patchMap = (Map) patchMapField.get(locations); String found = patchMap.toString(); + if (!found.equals(expect)) { + tb.out.println("Expect: " + expect); + tb.out.println("Found: " + found); + error("output not as expected"); + } + } catch (IllegalArgumentException e) { + if (expectOK) { + error("unexpected exception: " + e); + throw e; + } + String found = e.getMessage(); if (!found.equals(expect)) { tb.out.println("Expect: " + expect); tb.out.println("Found: " + found); From 7b4a4b80b54bdb9fd2c0a0ea62a479b0540b5015 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:51 +0000 Subject: [PATCH 094/402] Added tag jdk-9+144 for changeset 854ef5325653 --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 846b6a11335..27933595820 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -386,3 +386,4 @@ a5815c6098a241d3a1df64d22b84b3524e4a77df jdk-9+140 f64afae7f1a5608e438585bbf0bc23785e69cba0 jdk-9+141 2b3e5caafe3594ea507c37675c4d3086f415dc64 jdk-9+142 1fc62b1c629fb80fdaa639d3b59452a184f0d705 jdk-9+143 +8d337fd6333e28c48aa87880144b840aad82baaf jdk-9+144 From 41b6425f104b75f88fe6c0180fdf9b579b2dd211 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:52 +0000 Subject: [PATCH 095/402] Added tag jdk-9+144 for changeset 458b7becdccc --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 4ff5566b655..5ab3bfa0769 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -546,3 +546,4 @@ fec31089c2ef5a12dd64f401b0bf2e00f56ee0d0 jdk-9+140 160a00bc6ed0af1fdf8418fc65e6bddbbc0c536d jdk-9+141 7b48d63dfd6b8e2657288de3d7b1f153dee02d7e jdk-9+142 d87d5d430c42342f0320ca7f5cbe0cbd1f9d62ba jdk-9+143 +6187b582d02aee38341dc8ce4011906e9b364e9f jdk-9+144 From 40afef20ba5d22fc4cbb135b25317554c84bae77 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:52 +0000 Subject: [PATCH 096/402] Added tag jdk-9+144 for changeset 4a00f20b9fe2 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index c96fdd40202..7ec4e1bd79d 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -386,3 +386,4 @@ aa053a3faf266c12b4fd5272da431a3e08e4a3e3 jdk-9+136 b32f998da32b488ec7c4e9dbb3c750841b48e74d jdk-9+141 408c9c621938ca028e20bced0459f815de47eba8 jdk-9+142 6211236ef15ec796806357608b1dd1b70c258ece jdk-9+143 +d4f1dae174098e799c48948e866054c52e11a186 jdk-9+144 From 0e992818640a37060549af6290b9c1212b0c2a39 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:53 +0000 Subject: [PATCH 097/402] Added tag jdk-9+144 for changeset 773cd6c4b8e7 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index addee1762c9..900943ec381 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -386,3 +386,4 @@ a8d5fe567ae72b4931040e59dd4478363f9004f5 jdk-9+137 037c095ba0c345edbeaaab52fda913a76c3930c0 jdk-9+141 bdafa0cc34a97a2f8db4847a4efd34b407943591 jdk-9+142 ce81d03ad7320dca3d673374c1a33bc0efd9136a jdk-9+143 +99be33734ff62b75116b1202d49a4d4e1bda4226 jdk-9+144 From 609ef5def3db7f7954282a8bb3a45b3dfe444af7 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:53 +0000 Subject: [PATCH 098/402] Added tag jdk-9+144 for changeset f692ed885b0c --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index 790219ed5e4..5d90ddab9df 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -389,3 +389,4 @@ ab1d78d395d4cb8be426ff181211da1a4085cf01 jdk-9+134 b2c18f755228d1d19a86cd7d5fa1abb6b1495dfb jdk-9+141 59101416d90160cfcb4f45dfbccaec15e2c27a29 jdk-9+142 1c988e708a06257119d54d8a57e99e3b0f37ff18 jdk-9+143 +92523c51d6a48b0a83912ba3cc43bc57b8159c2a jdk-9+144 From 26da3a9538f84616fdcc98f3857d12c6b65461fd Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:55 +0000 Subject: [PATCH 099/402] Added tag jdk-9+144 for changeset a4ee110842fb --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index cafeca2beaf..4205f71b3ec 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -386,3 +386,4 @@ dd56c243c199a540c9f1fbff4855f0934b32a9d0 jdk-9+137 296c875051187918f8f3f87e9432036d13013d39 jdk-9+141 d245e56f4a79a8a8d18bd143c08f079ee98ab638 jdk-9+142 6ef8a1453577832626b0efb7f70a3102b721ebbf jdk-9+143 +47871e348144bafddea0ede3a44299461e254a2d jdk-9+144 From 5f91733e003457e5e98328c4eb16264e4d8b473f Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Fri, 11 Nov 2016 05:11:55 +0000 Subject: [PATCH 100/402] Added tag jdk-9+144 for changeset d55f24e8953e --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index edcfefd25c1..fc07f2de0a9 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -377,3 +377,4 @@ e3b11296395b39bfeb3364f26c2ef77fa652e300 jdk-9+139 a46b7d3867957a868a6cc8ee66c05079b883733a jdk-9+141 d3f5d7311a1aec3152b17d75046d5d298245a0b4 jdk-9+142 b4e57ead3fae4939b70dd345d1f6744a1dedfa21 jdk-9+143 +a7f21ee6ed30695a6de14e74035d2857a754f62b jdk-9+144 From d666bc1ccfb40a1b5197b6e45a29903cf0d281f2 Mon Sep 17 00:00:00 2001 From: Ajit Ghaisas Date: Fri, 11 Nov 2016 12:40:59 +0530 Subject: [PATCH 101/402] 8169043: The task bar icon color is not blue Reviewed-by: serb, arapte --- .../MultiResolutionIcon/MultiResIconTest.java | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java b/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java index f2486a13b27..1f1cd31666f 100644 --- a/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java @@ -24,9 +24,10 @@ /** * @test * @key headful - * @bug 8149371 + * @bug 8149371 8169043 * @summary multi-res. image: -Dsun.java2d.uiScale does not work for Window * icons (some ambiguity for Window.setIconImages()?) + * @requires (os.family == "windows") * @run main/othervm/manual -Dsun.java2d.uiScale=2 MultiResIconTest */ import java.awt.Color; @@ -58,6 +59,7 @@ public class MultiResIconTest { private static JDialog f; private static CountDownLatch latch; private static TestFrame frame; + private static boolean testPassed; private static BufferedImage generateImage(int x, Color c) { @@ -70,12 +72,13 @@ public class MultiResIconTest { return img; } - public MultiResIconTest() { - try { - latch = new CountDownLatch(1); - createUI(); - latch.await(); - } catch (Exception ex) { + public MultiResIconTest() throws Exception { + latch = new CountDownLatch(1); + createUI(); + latch.await(); + + if (!testPassed) { + throw new RuntimeException("User Pressed Failed Button"); } } @@ -89,7 +92,10 @@ public class MultiResIconTest { resultButtonPanel = new JPanel(layout); GridBagConstraints gbc = new GridBagConstraints(); String instructions - = " INSTRUCTIONS:

    " + = " INSTRUCTIONS:
    " + + "This test is for Windows OS only.
    " + + "Make sure that 'Use Small Icons' setting is not set
    " + + "on Windows Taskbar Properties
    " + "1) Test frame title icon and frame color should be green." + "
    " + "2) Test frame task bar icon should be blue
    " @@ -106,6 +112,7 @@ public class MultiResIconTest { passButton = new JButton("Pass"); passButton.setActionCommand("Pass"); passButton.addActionListener((ActionEvent e) -> { + testPassed = true; latch.countDown(); f.dispose(); frame.dispose(); @@ -115,6 +122,7 @@ public class MultiResIconTest { failButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { + testPassed = false; latch.countDown(); f.dispose(); frame.dispose(); @@ -140,6 +148,7 @@ public class MultiResIconTest { f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { + testPassed = false; latch.countDown(); f.dispose(); frame.dispose(); @@ -191,7 +200,7 @@ public class MultiResIconTest { } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { new MultiResIconTest(); } } From a41bc73423b6b11d265028bc7e9bc7ab0790cf59 Mon Sep 17 00:00:00 2001 From: Manajit Halder Date: Fri, 11 Nov 2016 13:58:42 +0530 Subject: [PATCH 102/402] 8165680: [macosx] Enhance handling of UTF-8 characters in CDataTransfer.java Reviewed-by: serb, aniyogi --- .../macosx/classes/sun/lwawt/macosx/CDataTransferer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java index 150c6e92ad1..795e4296c70 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java @@ -38,6 +38,7 @@ import java.text.Normalizer.Form; import java.util.*; import java.util.regex.*; import java.awt.datatransfer.*; +import java.nio.charset.StandardCharsets; import sun.awt.datatransfer.*; public class CDataTransferer extends DataTransferer { @@ -132,7 +133,7 @@ public class CDataTransferer extends DataTransferer { String charset = Charset.defaultCharset().name(); if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { try { - charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), "UTF-8"); + charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), StandardCharsets.UTF_8); } catch (UnsupportedFlavorException cannotHappen) { } } From e285ff61a856031628095f50ff82f3a367274aa6 Mon Sep 17 00:00:00 2001 From: Prahalad Kumar Narayanan Date: Fri, 11 Nov 2016 15:30:22 +0530 Subject: [PATCH 103/402] 8166003: [PIT][TEST_BUG] missing helper for javax/swing/text/GlyphPainter2/6427244/bug6427244.java Reviewed-by: prr, psadhukhan --- .../GlyphPainter2/6427244/bug6427244.java | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java b/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java index cc32aeb7690..f6f571aa05e 100644 --- a/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java +++ b/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java @@ -23,11 +23,11 @@ */ /* @test - @bug 6427244 8144240 + @bug 6427244 8144240 8166003 @summary Test that pressing HOME correctly moves caret in I18N document. @author Sergey Groznyh @library ../../../regtesthelpers - @build JRobot Util TestCase + @build JRobot @run main bug6427244 */ @@ -36,12 +36,13 @@ import java.awt.Dimension; import java.awt.Point; import java.awt.Shape; import java.awt.event.KeyEvent; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.text.Position; -public class bug6427244 extends TestCase { +public class bug6427244 { private static final JRobot ROBOT = JRobot.getRobot(); final static int TP_SIZE = 200; @@ -105,13 +106,25 @@ public class bug6427244 extends TestCase { dim = c.getSize(); } }); - Util.blockTillDisplayed(tp); + blockTillDisplayed(tp); ROBOT.waitForIdle(); } catch (Exception ex) { throw new RuntimeException(ex); } } + void blockTillDisplayed(JComponent comp) { + if(comp != null) { + while (!comp.isVisible()) { + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + /* No-op */ + } + } + } + } + public void testCaretPosition() { Point p = tp.getLocationOnScreen(); // the right-top corner position @@ -122,7 +135,9 @@ public class bug6427244 extends TestCase { ROBOT.hitKey(KeyEvent.VK_HOME); ROBOT.waitForIdle(); // this will fail if caret moves out of the 1st line. - assertEquals(0, getCaretOrdinate()); + if (getCaretOrdinate() != 0) { + throw new RuntimeException("Test Failed."); + } } int getCaretOrdinate() { From 8b4ddda72debc11347439ec310e1d9d1a58f8c74 Mon Sep 17 00:00:00 2001 From: Prahalad Kumar Narayanan Date: Fri, 11 Nov 2016 15:33:57 +0530 Subject: [PATCH 104/402] 8165212: VolatileImage should not be compatible with GraphicsConfiguration which transform is changed Reviewed-by: prr, serb --- .../sun/awt/image/VolatileSurfaceManager.java | 41 ++- .../VolatileImageConfigurationTest.java | 267 ++++++++++++++++++ 2 files changed, 304 insertions(+), 4 deletions(-) create mode 100644 jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java diff --git a/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java b/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java index ef2abf1caf7..9f187c629c5 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,6 +54,15 @@ public abstract class VolatileSurfaceManager */ protected SunVolatileImage vImg; + /** + * A reference to the AffineTransform corresponding to the graphics + * configuration of the volatile image. Affine Transformation is usually + * derived from the screen device. During the displayChanged() callback, + * the existing transform is compared with the updated screen transform to + * determine whether the software backed surface needs to be re-created + */ + protected AffineTransform atCurrent; + /** * The accelerated SurfaceData object. */ @@ -93,6 +102,7 @@ public abstract class VolatileSurfaceManager protected VolatileSurfaceManager(SunVolatileImage vImg, Object context) { this.vImg = vImg; this.context = context; + this.atCurrent = vImg.getGraphicsConfig().getDefaultTransform(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); @@ -210,6 +220,10 @@ public abstract class VolatileSurfaceManager sdCurrent = getBackupSurface(); sdAccel = null; returnCode = VolatileImage.IMAGE_RESTORED; + } else if (lostSurfaceTmp) { + // A software surface has been restored. This could be due to + // display mode change on a non-accelerated volatile image. + returnCode = VolatileImage.IMAGE_RESTORED; } if ((returnCode != VolatileImage.IMAGE_INCOMPATIBLE) && @@ -326,9 +340,6 @@ public abstract class VolatileSurfaceManager * method in the rendering process to recreate the surface. */ public void displayChanged() { - if (!isAccelerationEnabled()) { - return; - } lostSurface = true; if (sdAccel != null) { // First, nullify the software surface. This guards against @@ -345,6 +356,28 @@ public abstract class VolatileSurfaceManager // Update graphicsConfig for the vImg in case it changed due to // this display change event vImg.updateGraphicsConfig(); + + // Compare the Graphics configuration transforms to determine + // whether the software backed surface needs to be invalidated. + AffineTransform atUpdated = vImg.getGraphicsConfig() + .getDefaultTransform(); + if (!isAccelerationEnabled()) { + if (!atUpdated.equals(atCurrent)) { + // Ideally there is no need to re-create a software surface. + // But some OSs allow changes to display state at runtime. Such + // a provision would cause mismatch in graphics configuration of + // the display and the surface. Hence we re-create the software + // surface as well. + sdBackup = null; + sdCurrent = getBackupSurface(); + } else { + // Software backed surface was not invalidated. + lostSurface = false; + } + } + + // Update the AffineTransformation backing the volatile image + atCurrent = atUpdated; } /** diff --git a/jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java b/jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java new file mode 100644 index 00000000000..5fc165acc84 --- /dev/null +++ b/jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8165212 + * @summary This manual test case displays scale values of Graphics and the + * underlying device configuration. Any change to host display's DPI + * value should reflect corresponding changes in the scale values + * of both Frame and Backbuffer (VolatileImage). + * @run main/othervm/manual -Dsun.java2d.d3d=false -Dsun.java2d.opengl=false VolatileImageConfigurationTest + */ +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.geom.AffineTransform; +import java.awt.image.VolatileImage; +import java.awt.HeadlessException; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JButton; +import javax.swing.SwingUtilities; + +public class VolatileImageConfigurationTest + extends JFrame + implements ActionListener { + /* Test frame and completion status */ + private static JFrame testFrame; + private static volatile boolean testComplete = false; + private static volatile boolean testResult = false; + + /* Main frame's dimensions */ + private static final int TEST_WIDTH = 600; + private static final int TEST_HEIGHT = 600; + private static final int TEST_MIN_DURATION = 3000; + private static final int TEST_TOTAL_DURATION = 45000; + + /* + * Frame will display information text explaining how to run the manual + * test, and two buttons- Pass and Fail to determine the end-result. + */ + private JTextArea infoTextArea; + private JPanel buttonPanel; + private JPanel testPanel; + private JButton passButton; + private JButton failButton; + + public VolatileImageConfigurationTest() { + /* Default constructor. Initialize the UI components */ + super("Volatile Image Configuration Update Test"); + initComponents(); + } + + private void initComponents() { + /* Create the text area with steps to execute the test */ + String description + = "\n Volatile Image Configuration Update Test.\n" + + " 1. The test displays scale values of component and the" + + " underlying graphics device configuration.\n" + + " 2. Kindly change the display's DPI settings from OS" + + " control panel and observe the application.\n" + + " 3. Select Pass if the scale values for both component & " + + "underlying device configuration are updated as per the " + + "\ndisplay's DPI value.\n"; + infoTextArea = new JTextArea(description); + + /* Create the test panel where user will observe the drawing */ + testPanel = new DisplayPanel(); + + /* Create the buttons with event listeners */ + passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.setEnabled(true); + passButton.addActionListener(this); + + failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.setEnabled(true); + failButton.addActionListener(this); + + /* Add the buttons to a separate panel with flowlayout */ + buttonPanel = new JPanel(new FlowLayout()); + buttonPanel.add(passButton); + buttonPanel.add(failButton); + + /* Add all the created components to the master frame */ + setLayout(new BorderLayout(10, 10)); + add(infoTextArea, BorderLayout.NORTH); + add(buttonPanel, BorderLayout.SOUTH); + add(testPanel, BorderLayout.CENTER); + + /* Set the dimensions */ + setSize(TEST_WIDTH, TEST_HEIGHT); + } + + @Override + public void actionPerformed(ActionEvent e) { + /* Button event listener */ + String command = e.getActionCommand(); + + if (command.equals("Pass")) { + /* Test has passed. Dispose the frame with success message */ + testComplete = true; + testResult = true; + System.out.println("Test Passed."); + } else if (command.equals("Fail")) { + /* Test has failed. Dispose the frame and throw exception */ + testComplete = true; + testResult = false; + } + } + + private static void constructTestUI() { + /* Construct the test's user interface */ + testFrame = new VolatileImageConfigurationTest(); + testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + testFrame.setLocationRelativeTo(null); + testFrame.setVisible(true); + } + + private static void destructTestUI() { + /* Destroy the test's user interface */ + testFrame.dispose(); + } + + static class DisplayPanel extends JPanel { + /* Display panel settings */ + private static final int PANEL_WIDTH = 600; + private static final int PANEL_HEIGHT = 500; + private static final int PANEL_X = 20; + private static final int PANEL_Y = 80; + private static final String MSG = "%s scale: [%2.2f, %2.2f]"; + private VolatileImage vImg; + + public DisplayPanel() throws HeadlessException { + setSize(PANEL_WIDTH, PANEL_HEIGHT); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + + g.setColor(Color.WHITE); + g.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT); + /* Display graphics configuration values of the component */ + drawInfo(g, PANEL_X, PANEL_Y, "Frame", Color.BLUE); + int attempts = 0; + do { + /* Display graphics configuration values of volatile image */ + drawBackingStoreImage(g); + } while (vImg.contentsLost() && ++attempts < 3); + } + + private void drawInfo(Graphics g, int x, int y, + String msg, Color color) { + g.setColor(color); + g.setFont(g.getFont().deriveFont(24f)); + Graphics2D g2d = (Graphics2D) g; + AffineTransform tx = g2d.getTransform(); + + g.drawString(msg, x, y); + String text = String.format(MSG, + "Graphics", + tx.getScaleX(), + tx.getScaleY()); + int dy = 20; + g.drawString(text, x, y + dy); + + tx = g2d.getDeviceConfiguration().getDefaultTransform(); + text = String.format(MSG, + "Device Config", + tx.getScaleX(), + tx.getScaleY()); + g.drawString(text, x, y + 2 * dy); + } + + private void drawBackingStoreImage(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + GraphicsConfiguration gc = g2d.getDeviceConfiguration(); + if (vImg == null || + vImg.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) { + /* Create a new volatile image */ + vImg = createVolatileImage(PANEL_WIDTH, PANEL_HEIGHT / 3); + } + + Graphics vImgGraphics = vImg.createGraphics(); + vImgGraphics.setColor(Color.WHITE); + vImgGraphics.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT / 3); + drawInfo(vImgGraphics, + PANEL_X, + PANEL_Y, + "Backbuffer", + Color.MAGENTA); + g.drawImage(vImg, 0, PANEL_Y * 2, this); + } + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + /* Construct the test interface */ + constructTestUI(); + } catch (Exception ex) { + /* Throw an exception indicating error while creating UI */ + throw new RuntimeException("Test Failed. Error while " + + "creating the test interface."); + } + } + }); + + try { + /* Provide sufficient time for user to act upon the manual test */ + long totalWaitDuration = 0; + do { + Thread.sleep(TEST_MIN_DURATION); + totalWaitDuration += TEST_MIN_DURATION; + } while (!testComplete && totalWaitDuration < TEST_TOTAL_DURATION); + } catch(InterruptedException ite) { + /* No-op. The thread continues execution further */ + } + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + /* Destroy the test interface */ + destructTestUI(); + } catch (Exception ex) { + /* No-op */ + } + } + }); + + /* Check for the test result and throw exception if required */ + if (testResult == false) { + throw new RuntimeException("Test Failed. Incorrect scale values " + + "were seen during the test execution."); + } + } +} \ No newline at end of file From d969a1a3fa9ea2242694c3e238c23a1454e2d1f4 Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Fri, 11 Nov 2016 12:54:47 +0100 Subject: [PATCH 105/402] 8145838: JShell: restrict RemoteAgent connection socket to localhost Also reviewed by Chris Ries Reviewed-by: rfield --- .../execution/JdiDefaultExecutionControl.java | 43 ++++++++++++++++++- .../execution/RemoteExecutionControl.java | 21 +++++++++ 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java index 45114ac03a6..8e22d330e82 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java @@ -24,18 +24,23 @@ */ package jdk.jshell.execution; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; +import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; +import java.security.SecureRandom; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; + import com.sun.jdi.BooleanValue; import com.sun.jdi.ClassNotLoadedException; import com.sun.jdi.Field; @@ -111,7 +116,7 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { */ private static ExecutionControl create(ExecutionEnv env, boolean isLaunch, String host) throws IOException { - try (final ServerSocket listener = new ServerSocket(0)) { + try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { // timeout after 60 seconds listener.setSoTimeout(60000); int port = listener.getLocalPort(); @@ -122,6 +127,14 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { VirtualMachine vm = jdii.vm(); Process process = jdii.process(); + OutputStream processOut = process.getOutputStream(); + SecureRandom rng = new SecureRandom(); + byte[] randomBytes = new byte[VERIFY_HASH_LEN]; + + rng.nextBytes(randomBytes); + processOut.write(randomBytes); + processOut.flush(); + List> deathListeners = new ArrayList<>(); deathListeners.add(s -> env.closeDown()); Util.detectJdiExitEvent(vm, s -> { @@ -130,6 +143,8 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { } }); + ByteArrayOutputStream receivedRandomBytes = new ByteArrayOutputStream(); + // Set-up the commands/reslts on the socket. Piggy-back snippet // output. Socket socket = listener.accept(); @@ -138,11 +153,35 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { Map outputs = new HashMap<>(); outputs.put("out", env.userOut()); outputs.put("err", env.userErr()); + outputs.put("echo", new OutputStream() { + @Override public void write(int b) throws IOException { + synchronized (receivedRandomBytes) { + receivedRandomBytes.write(b); + receivedRandomBytes.notify(); + } + } + }); Map input = new HashMap<>(); input.put("in", env.userIn()); - return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new JdiDefaultExecutionControl(objOut, objIn, vm, process, deathListeners)); + return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> { + synchronized (receivedRandomBytes) { + while (receivedRandomBytes.size() < randomBytes.length) { + try { + receivedRandomBytes.wait(); + } catch (InterruptedException ex) { + //ignore + } + } + if (!Arrays.equals(receivedRandomBytes.toByteArray(), randomBytes)) { + throw new IllegalStateException("Invalid connection!"); + } + } + return new JdiDefaultExecutionControl(objOut, objIn, vm, process, deathListeners); + }); } } + //where: + private static final int VERIFY_HASH_LEN = 20; /** * Create an instance. diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java index 81eac159b60..32330239d1f 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java @@ -24,6 +24,7 @@ */ package jdk.jshell.execution; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; @@ -57,6 +58,7 @@ public class RemoteExecutionControl extends DirectExecutionControl implements Ex * @throws Exception any unexpected exception */ public static void main(String[] args) throws Exception { + InputStream fd0 = System.in; String loopBack = null; Socket socket = new Socket(loopBack, Integer.parseInt(args[0])); InputStream inStream = socket.getInputStream(); @@ -64,6 +66,25 @@ public class RemoteExecutionControl extends DirectExecutionControl implements Ex Map> outputs = new HashMap<>(); outputs.put("out", st -> System.setOut(new PrintStream(st, true))); outputs.put("err", st -> System.setErr(new PrintStream(st, true))); + outputs.put("echo", st -> { + new Thread(() -> { + try { + int read; + + while ((read = fd0.read()) != (-1)) { + st.write(read); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + try { + st.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + }).start(); + }); Map> input = new HashMap<>(); input.put("in", st -> System.setIn(st)); forwardExecutionControlAndIO(new RemoteExecutionControl(), inStream, outStream, outputs, input); From cc33916b474563d3d4a77cdf305a1a3921d02e1d Mon Sep 17 00:00:00 2001 From: Sergey Bylokhov Date: Fri, 11 Nov 2016 17:07:33 +0300 Subject: [PATCH 106/402] 8169332: The fix JDK-8083664 in AudioFileWriter can be reverted Reviewed-by: prr, amenkov --- .../classes/javax/sound/sampled/spi/AudioFileWriter.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java b/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java index 7ce970b2508..0f137363b8c 100644 --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -129,7 +129,7 @@ public abstract class AudioFileWriter { * system * @throws NullPointerException if {@code stream} or {@code fileType} or * {@code out} are {@code null} - * @see #isFileTypeSupported(AudioFileFormat.Type, AudioInputStream) + * @see #isFileTypeSupported(Type, AudioInputStream) * @see #getAudioFileTypes */ public abstract int write(AudioInputStream stream, Type fileType, @@ -149,7 +149,7 @@ public abstract class AudioFileWriter { * the system * @throws NullPointerException if {@code stream} or {@code fileType} or * {@code out} are {@code null} - * @see #isFileTypeSupported + * @see #isFileTypeSupported(Type, AudioInputStream) * @see #getAudioFileTypes */ public abstract int write(AudioInputStream stream, Type fileType, File out) From 1406cd4347fe1359338945dd5d87141b86efbfd1 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Fri, 11 Nov 2016 15:50:51 +0100 Subject: [PATCH 107/402] 8168373: don't emit conversions for symbols outside their lexical scope Reviewed-by: hannesw, sundar --- .../codegen/LocalVariableTypesCalculator.java | 79 +++++++++++++------ .../internal/ir/debug/PrintVisitor.java | 2 +- nashorn/test/script/basic/es6/JDK-8168373.js | 44 +++++++++++ 3 files changed, 98 insertions(+), 27 deletions(-) create mode 100644 nashorn/test/script/basic/es6/JDK-8168373.js diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java index cf92047730c..8b34bfc9ef8 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java @@ -33,6 +33,7 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; +import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; @@ -122,9 +123,9 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { private final List origins = new LinkedList<>(); private Map types = Collections.emptyMap(); - void addOrigin(final JoinPredecessor originNode, final Map originTypes) { + void addOrigin(final JoinPredecessor originNode, final Map originTypes, final LocalVariableTypesCalculator calc) { origins.add(new JumpOrigin(originNode, originTypes)); - this.types = getUnionTypes(this.types, originTypes); + this.types = calc.getUnionTypes(this.types, originTypes); } } private enum LvarType { @@ -185,12 +186,15 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { } @SuppressWarnings("unchecked") - private static IdentityHashMap cloneMap(final Map map) { - return (IdentityHashMap)((IdentityHashMap)map).clone(); + private static HashMap cloneMap(final Map map) { + return (HashMap)((HashMap)map).clone(); } private LocalVariableConversion createConversion(final Symbol symbol, final LvarType branchLvarType, final Map joinLvarTypes, final LocalVariableConversion next) { + if (invalidatedSymbols.contains(symbol)) { + return next; + } final LvarType targetType = joinLvarTypes.get(symbol); assert targetType != null; if(targetType == branchLvarType) { @@ -208,7 +212,7 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { return new LocalVariableConversion(symbol, branchLvarType.type, targetType.type, next); } - private static Map getUnionTypes(final Map types1, final Map types2) { + private Map getUnionTypes(final Map types1, final Map types2) { if(types1 == types2 || types1.isEmpty()) { return types2; } else if(types2.isEmpty()) { @@ -261,6 +265,11 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { final LvarType type2 = types2.get(symbol); union.put(symbol, widestLvarType(type1, type2)); } + // If the two sets of symbols differ, there's a good chance that some of + // symbols only appearing in one of the sets are lexically invalidated, + // so we remove them from further consideration. + // This is not strictly necessary, just a working set size optimization. + union.keySet().removeAll(invalidatedSymbols); return union; } @@ -359,8 +368,6 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { if(t1.ordinal() < LvarType.INT.ordinal() || t2.ordinal() < LvarType.INT.ordinal()) { return LvarType.OBJECT; } - // NOTE: we allow "widening" of long to double even though it can lose precision. ECMAScript doesn't have an - // Int64 type anyway, so this loss of precision is actually more conformant to the specification... return LvarType.values()[Math.max(t1.ordinal(), t2.ordinal())]; } private final Compiler compiler; @@ -368,7 +375,10 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { // Local variable type mapping at the currently evaluated point. No map instance is ever modified; setLvarType() always // allocates a new map. Immutability of maps allows for cheap snapshots by just keeping the reference to the current // value. - private Map localVariableTypes = new IdentityHashMap<>(); + private Map localVariableTypes = Collections.emptyMap(); + // Set of symbols whose lexical scope has already ended. + private final Set invalidatedSymbols = new HashSet<>(); + // Stack for evaluated expression types. private final Deque typeStack = new ArrayDeque<>(); @@ -464,9 +474,19 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { @Override public boolean enterBlock(final Block block) { + boolean cloned = false; for(final Symbol symbol: block.getSymbols()) { - if(symbol.isBytecodeLocal() && getLocalVariableTypeOrNull(symbol) == null) { - setType(symbol, LvarType.UNDEFINED); + if(symbol.isBytecodeLocal()) { + if (getLocalVariableTypeOrNull(symbol) == null) { + if (!cloned) { + cloneOrNewLocalVariableTypes(); + cloned = true; + } + localVariableTypes.put(symbol, LvarType.UNDEFINED); + } + // In case we're repeating analysis of a lexical scope (e.g. it's in a loop), + // make sure all symbols lexically scoped by the block become valid again. + invalidatedSymbols.remove(symbol); } } return true; @@ -1046,15 +1066,11 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { // throw an exception. reachable = true; catchBody.accept(this); - final Symbol exceptionSymbol = exception.getSymbol(); if(reachable) { - localVariableTypes = cloneMap(localVariableTypes); - localVariableTypes.remove(exceptionSymbol); jumpToLabel(catchBody, endLabel); canExit = true; } - localVariableTypes = cloneMap(afterConditionTypes); - localVariableTypes.remove(exceptionSymbol); + localVariableTypes = afterConditionTypes; } // NOTE: if we had one or more conditional catch blocks with no unconditional catch block following them, then // there will be an unconditional rethrow, so the join point can never be reached from the last @@ -1204,7 +1220,7 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { } private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label, final Map types) { - getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types); + getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types, this); } @Override @@ -1226,16 +1242,18 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { boolean cloned = false; for(final Symbol symbol: block.getSymbols()) { - // Undefine the symbol outside the block - if(localVariableTypes.containsKey(symbol)) { - if(!cloned) { - localVariableTypes = cloneMap(localVariableTypes); - cloned = true; - } - localVariableTypes.remove(symbol); - } - if(symbol.hasSlot()) { + // Invalidate the symbol when its defining block ends + if (symbol.isBytecodeLocal()) { + if(localVariableTypes.containsKey(symbol)) { + if(!cloned) { + localVariableTypes = cloneMap(localVariableTypes); + cloned = true; + } + } + invalidateSymbol(symbol); + } + final SymbolConversions conversions = symbolConversions.get(symbol); if(conversions != null) { // Potentially make some currently dead types live if they're needed as a source of a type @@ -1605,10 +1623,19 @@ final class LocalVariableTypesCalculator extends SimpleNodeVisitor { } assert symbol.hasSlot(); assert !symbol.isGlobal(); - localVariableTypes = localVariableTypes.isEmpty() ? new IdentityHashMap() : cloneMap(localVariableTypes); + cloneOrNewLocalVariableTypes(); localVariableTypes.put(symbol, type); } + private void cloneOrNewLocalVariableTypes() { + localVariableTypes = localVariableTypes.isEmpty() ? new HashMap() : cloneMap(localVariableTypes); + } + + private void invalidateSymbol(final Symbol symbol) { + localVariableTypes.remove(symbol); + invalidatedSymbols.add(symbol); + } + /** * Set a flag in the symbol marking it as needing to be able to store a value of a particular type. Every symbol for * a local variable will be assigned between 1 and 6 local variable slots for storing all types it is known to need diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/PrintVisitor.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/PrintVisitor.java index bb8d61a5907..fccad1532aa 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/PrintVisitor.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/PrintVisitor.java @@ -397,7 +397,7 @@ public final class PrintVisitor extends SimpleNodeVisitor { @Override public boolean enterVarNode(final VarNode varNode) { - sb.append("var "); + sb.append(varNode.isConst() ? "const " : varNode.isLet() ? "let " : "var "); varNode.getName().toString(sb, printTypes); printLocalVariableConversion(varNode.getName()); final Node init = varNode.getInit(); diff --git a/nashorn/test/script/basic/es6/JDK-8168373.js b/nashorn/test/script/basic/es6/JDK-8168373.js new file mode 100644 index 00000000000..af26e73533e --- /dev/null +++ b/nashorn/test/script/basic/es6/JDK-8168373.js @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * JDK-8168373: don't emit conversions for symbols outside their lexical scope + * + * @test + * @run + * @option --language=es6 + */ + +function p() { return false } // "predicate" +function r(x) { return x } // "read" + +(function() { + try { // Try creates control flow edges from assignments into catch blocks. + // Lexically scoped, never read int variable (undefined at catch block) but still with a cf edge into catch block. + // Since it's never read, it's not written either (Nashorn optimizes some dead writes). + let x = 0; + if (p()) { throw {}; } // We need `p()` so this block doesn't get optimized away, for possibility of a `throw` + x = 0.0; // change the type of x to double + r(x); // read x otherwise it's optimized away + } catch (e) {} // under the bug, "throw" will try to widen unwritten int x to double for here and cause a verifier error +})() From 5e2e968e204ad22df8edd68e6b5f94092b38019b Mon Sep 17 00:00:00 2001 From: Jesper Wilhelmsson Date: Fri, 11 Nov 2016 16:52:44 +0100 Subject: [PATCH 108/402] 8169597: Quarantine TestCpoolForInvokeDynamic.java until JDK-8169232 is solved Reviewed-by: egahlin, gtriantafill --- hotspot/test/serviceability/sa/TestCpoolForInvokeDynamic.java | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/test/serviceability/sa/TestCpoolForInvokeDynamic.java b/hotspot/test/serviceability/sa/TestCpoolForInvokeDynamic.java index 80160d5cf84..e8f1fd86703 100644 --- a/hotspot/test/serviceability/sa/TestCpoolForInvokeDynamic.java +++ b/hotspot/test/serviceability/sa/TestCpoolForInvokeDynamic.java @@ -51,6 +51,7 @@ import jdk.test.lib.Asserts; * jdk.hotspot.agent/sun.jvm.hotspot.oops * jdk.hotspot.agent/sun.jvm.hotspot.debugger * jdk.hotspot.agent/sun.jvm.hotspot.ui.classbrowser + * @ignore 8169232 * @run main/othervm TestCpoolForInvokeDynamic */ From 4ca0a287feb5709ffce10118d255cc9cc1e84b2d Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Fri, 11 Nov 2016 17:45:29 +0100 Subject: [PATCH 109/402] 8169599: Several JShell tests are failing on Solaris after JDK-8145838 Partially reverting e43f670394ca Reviewed-by: rfield --- .../execution/JdiDefaultExecutionControl.java | 40 +------------------ .../execution/RemoteExecutionControl.java | 21 ---------- 2 files changed, 1 insertion(+), 60 deletions(-) diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java index 8e22d330e82..ee266a30c17 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java @@ -24,7 +24,6 @@ */ package jdk.jshell.execution; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; @@ -33,14 +32,11 @@ import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; -import java.security.SecureRandom; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; - import com.sun.jdi.BooleanValue; import com.sun.jdi.ClassNotLoadedException; import com.sun.jdi.Field; @@ -127,14 +123,6 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { VirtualMachine vm = jdii.vm(); Process process = jdii.process(); - OutputStream processOut = process.getOutputStream(); - SecureRandom rng = new SecureRandom(); - byte[] randomBytes = new byte[VERIFY_HASH_LEN]; - - rng.nextBytes(randomBytes); - processOut.write(randomBytes); - processOut.flush(); - List> deathListeners = new ArrayList<>(); deathListeners.add(s -> env.closeDown()); Util.detectJdiExitEvent(vm, s -> { @@ -143,8 +131,6 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { } }); - ByteArrayOutputStream receivedRandomBytes = new ByteArrayOutputStream(); - // Set-up the commands/reslts on the socket. Piggy-back snippet // output. Socket socket = listener.accept(); @@ -153,35 +139,11 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { Map outputs = new HashMap<>(); outputs.put("out", env.userOut()); outputs.put("err", env.userErr()); - outputs.put("echo", new OutputStream() { - @Override public void write(int b) throws IOException { - synchronized (receivedRandomBytes) { - receivedRandomBytes.write(b); - receivedRandomBytes.notify(); - } - } - }); Map input = new HashMap<>(); input.put("in", env.userIn()); - return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> { - synchronized (receivedRandomBytes) { - while (receivedRandomBytes.size() < randomBytes.length) { - try { - receivedRandomBytes.wait(); - } catch (InterruptedException ex) { - //ignore - } - } - if (!Arrays.equals(receivedRandomBytes.toByteArray(), randomBytes)) { - throw new IllegalStateException("Invalid connection!"); - } - } - return new JdiDefaultExecutionControl(objOut, objIn, vm, process, deathListeners); - }); + return remoteInputOutput(socket.getInputStream(), out, outputs, input, (objIn, objOut) -> new JdiDefaultExecutionControl(objOut, objIn, vm, process, deathListeners)); } } - //where: - private static final int VERIFY_HASH_LEN = 20; /** * Create an instance. diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java index 32330239d1f..81eac159b60 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java @@ -24,7 +24,6 @@ */ package jdk.jshell.execution; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; @@ -58,7 +57,6 @@ public class RemoteExecutionControl extends DirectExecutionControl implements Ex * @throws Exception any unexpected exception */ public static void main(String[] args) throws Exception { - InputStream fd0 = System.in; String loopBack = null; Socket socket = new Socket(loopBack, Integer.parseInt(args[0])); InputStream inStream = socket.getInputStream(); @@ -66,25 +64,6 @@ public class RemoteExecutionControl extends DirectExecutionControl implements Ex Map> outputs = new HashMap<>(); outputs.put("out", st -> System.setOut(new PrintStream(st, true))); outputs.put("err", st -> System.setErr(new PrintStream(st, true))); - outputs.put("echo", st -> { - new Thread(() -> { - try { - int read; - - while ((read = fd0.read()) != (-1)) { - st.write(read); - } - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - try { - st.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - }).start(); - }); Map> input = new HashMap<>(); input.put("in", st -> System.setIn(st)); forwardExecutionControlAndIO(new RemoteExecutionControl(), inStream, outStream, outputs, input); From 8a2f4e80e4e6a1c2f58e5c99b01c2f9d81285ddc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= Date: Fri, 11 Nov 2016 18:56:37 +0100 Subject: [PATCH 110/402] 8168049: Fix Performance of Lexer.isJSWhitespace Reviewed-by: sundar, attila --- .../jdk/nashorn/internal/parser/Lexer.java | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java index 3b43249cdc7..24518223439 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java @@ -102,19 +102,9 @@ public class Lexer extends Scanner { private int templateExpressionOpenBraces; - private static final String SPACETAB = " \t"; // ASCII space and tab - private static final String LFCR = "\n\r"; // line feed and carriage return (ctrl-m) - - private static final String JAVASCRIPT_WHITESPACE_EOL = - LFCR + + private static final String JAVASCRIPT_OTHER_WHITESPACE = "\u2028" + // line separator - "\u2029" // paragraph separator - ; - private static final String JAVASCRIPT_WHITESPACE = - SPACETAB + - JAVASCRIPT_WHITESPACE_EOL + - "\u000b" + // tabulation line - "\u000c" + // ff (ctrl-l) + "\u2029" + // paragraph separator "\u00a0" + // Latin-1 space "\u1680" + // Ogham space mark "\u180e" + // separator, Mongolian vowel @@ -384,7 +374,13 @@ public class Lexer extends Scanner { * @return true if valid JavaScript whitespace */ public static boolean isJSWhitespace(final char ch) { - return JAVASCRIPT_WHITESPACE.indexOf(ch) != -1; + return ch == ' ' // space + || ch >= '\t' && ch <= '\r' // 0x09..0x0d: tab, line feed, tabulation line, ff, carriage return + || ch >= 160 && isOtherJSWhitespace(ch); + } + + private static boolean isOtherJSWhitespace(final char ch) { + return JAVASCRIPT_OTHER_WHITESPACE.indexOf(ch) != -1; } /** @@ -393,7 +389,10 @@ public class Lexer extends Scanner { * @return true if valid JavaScript end of line */ public static boolean isJSEOL(final char ch) { - return JAVASCRIPT_WHITESPACE_EOL.indexOf(ch) != -1; + return ch == '\n' // line feed + || ch == '\r' // carriage return (ctrl-m) + || ch == '\u2028' // line separator + || ch == '\u2029'; // paragraph separator } /** From 8899d192109302727541b1e0c54b22fb1409790c Mon Sep 17 00:00:00 2001 From: Robert Field Date: Fri, 11 Nov 2016 11:50:11 -0800 Subject: [PATCH 111/402] 8166333: jshell tool: shortcut var does not import its type Reviewed-by: jlahoda --- .../jshell/tool/ConsoleIOContext.java | 45 +++++++++++++++---- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java index 16e9f65bd0c..a99a1fc5579 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java @@ -57,7 +57,6 @@ import jdk.internal.jline.TerminalFactory; import jdk.internal.jline.TerminalSupport; import jdk.internal.jline.WindowsTerminal; import jdk.internal.jline.console.ConsoleReader; -import jdk.internal.jline.console.CursorBuffer; import jdk.internal.jline.console.KeyMap; import jdk.internal.jline.console.UserInterruptException; import jdk.internal.jline.console.completer.Completer; @@ -581,26 +580,55 @@ class ConsoleIOContext extends IOContext { private static final FixComputer[] FIX_COMPUTERS = new FixComputer[] { new FixComputer('v', false) { //compute "Introduce variable" Fix: + private void performToVar(ConsoleReader in, String type) throws IOException { + in.redrawLine(); + in.setCursorPosition(0); + in.putString(type + " = "); + in.setCursorPosition(in.getCursorBuffer().cursor - 3); + in.flush(); + } + @Override public FixResult compute(JShellTool repl, String code, int cursor) { String type = repl.analysis.analyzeType(code, cursor); if (type == null) { return new FixResult(Collections.emptyList(), null); } - return new FixResult(Collections.singletonList(new Fix() { + List fixes = new ArrayList<>(); + fixes.add(new Fix() { @Override public String displayName() { return repl.messageFormat("jshell.console.create.variable"); } + @Override public void perform(ConsoleReader in) throws IOException { - in.redrawLine(); - in.setCursorPosition(0); - in.putString(type + " = "); - in.setCursorPosition(in.getCursorBuffer().cursor - 3); - in.flush(); + performToVar(in, type); } - }), null); + }); + int idx = type.lastIndexOf("."); + if (idx > 0) { + String stype = type.substring(idx + 1); + QualifiedNames res = repl.analysis.listQualifiedNames(stype, stype.length()); + if (res.isUpToDate() && res.getNames().contains(type) + && !res.isResolvable()) { + fixes.add(new Fix() { + @Override + public String displayName() { + return "import: " + type + ". " + + repl.messageFormat("jshell.console.create.variable"); + } + + @Override + public void perform(ConsoleReader in) throws IOException { + repl.state.eval("import " + type + ";"); + in.println("Imported: " + type); + performToVar(in, stype); + } + }); + } + } + return new FixResult(fixes, null); } }, new FixComputer('i', true) { //compute "Add import" Fixes: @@ -614,6 +642,7 @@ class ConsoleIOContext extends IOContext { public String displayName() { return "import: " + fqn; } + @Override public void perform(ConsoleReader in) throws IOException { repl.state.eval("import " + fqn + ";"); From 40e24f2e56a9d55da80366044531a4e1f68b1ae0 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Fri, 11 Nov 2016 17:32:21 -0800 Subject: [PATCH 112/402] 8168386: Fix jdeps verbose options Reviewed-by: dfuchs, lancea --- .../com/sun/tools/jdeps/JdepsTask.java | 715 ++++++++++++------ .../com/sun/tools/jdeps/ModuleAnalyzer.java | 8 - .../tools/jdeps/resources/jdeps.properties | 10 +- langtools/test/tools/jdeps/DotFileTest.java | 4 - langtools/test/tools/jdeps/Options.java | 92 +++ .../test/tools/jdeps/lib/JdepsRunner.java | 2 +- 6 files changed, 587 insertions(+), 244 deletions(-) create mode 100644 langtools/test/tools/jdeps/Options.java diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java index dca3f476d3c..af5bfb50041 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java @@ -25,8 +25,10 @@ package com.sun.tools.jdeps; +import com.sun.tools.jdeps.Analyzer.Type; import static com.sun.tools.jdeps.Analyzer.Type.*; import static com.sun.tools.jdeps.JdepsWriter.*; +import static java.util.stream.Collectors.*; import java.io.IOException; import java.io.PrintWriter; @@ -111,6 +113,10 @@ class JdepsTask { this.aliases = aliases; } + Option(boolean hasArg, CommandOption cmd) { + this(hasArg, cmd.names()); + } + boolean isHidden() { return false; } @@ -144,25 +150,46 @@ class JdepsTask { } } + enum CommandOption { + ANALYZE_DEPS(""), + GENERATE_DOT_FILE("-dotoutput", "--dot-output"), + GENERATE_MODULE_INFO("--generate-module-info"), + LIST_DEPS("--list-deps"), + LIST_REDUCED_DEPS("--list-reduced-deps"), + CHECK_MODULES("--check"); + + private final String[] names; + CommandOption(String... names) { + this.names = names; + } + + String[] names() { + return names; + } + + @Override + public String toString() { + return names[0]; + } + } + static Option[] recognizedOptions = { new Option(false, "-h", "-?", "-help", "--help") { void process(JdepsTask task, String opt, String arg) { task.options.help = true; } }, - new Option(true, "-dotoutput", "--dot-output") { + new Option(true, CommandOption.GENERATE_DOT_FILE) { void process(JdepsTask task, String opt, String arg) throws BadArgs { - Path p = Paths.get(arg); - if (Files.exists(p) && (!Files.isDirectory(p) || !Files.isWritable(p))) { - throw new BadArgs("err.invalid.path", arg); + if (task.command != null) { + throw new BadArgs("err.command.set", task.command, opt); } - task.options.dotOutputDir = Paths.get(arg);; + task.command = task.genDotFile(Paths.get(arg)); } }, new Option(false, "-s", "-summary") { void process(JdepsTask task, String opt, String arg) { task.options.showSummary = true; - task.options.verbose = SUMMARY; } }, new Option(false, "-v", "-verbose", @@ -196,35 +223,48 @@ class JdepsTask { task.options.apiOnly = true; } }, - new Option(true, "--check") { - void process(JdepsTask task, String opt, String arg) throws BadArgs { - Set mods = Set.of(arg.split(",")); - task.options.checkModuleDeps = mods; - task.options.addmods.addAll(mods); - } - }, - new Option(true, "--generate-module-info") { - void process(JdepsTask task, String opt, String arg) throws BadArgs { - Path p = Paths.get(arg); - if (Files.exists(p) && (!Files.isDirectory(p) || !Files.isWritable(p))) { - throw new BadArgs("err.invalid.path", arg); - } - task.options.genModuleInfo = Paths.get(arg); - } - }, + new Option(false, "-jdkinternals", "--jdk-internals") { void process(JdepsTask task, String opt, String arg) { task.options.findJDKInternals = true; - task.options.verbose = CLASS; if (task.options.includePattern == null) { task.options.includePattern = Pattern.compile(".*"); } } }, - new Option(false, "--list-deps", "--list-reduced-deps") { - void process(JdepsTask task, String opt, String arg) { - task.options.showModulesAddExports = true; - task.options.reduced = opt.equals("--list-reduced-deps"); + + new Option(true, CommandOption.CHECK_MODULES) { + void process(JdepsTask task, String opt, String arg) throws BadArgs { + if (task.command != null) { + throw new BadArgs("err.command.set", task.command, opt); + } + Set mods = Set.of(arg.split(",")); + task.options.addmods.addAll(mods); + task.command = task.checkModuleDeps(mods); + } + }, + new Option(true, CommandOption.GENERATE_MODULE_INFO) { + void process(JdepsTask task, String opt, String arg) throws BadArgs { + if (task.command != null) { + throw new BadArgs("err.command.set", task.command, opt); + } + task.command = task.genModuleInfo(Paths.get(arg)); + } + }, + new Option(false, CommandOption.LIST_DEPS) { + void process(JdepsTask task, String opt, String arg) throws BadArgs { + if (task.command != null) { + throw new BadArgs("err.command.set", task.command, opt); + } + task.command = task.listModuleDeps(false); + } + }, + new Option(false, CommandOption.LIST_REDUCED_DEPS) { + void process(JdepsTask task, String opt, String arg) throws BadArgs { + if (task.command != null) { + throw new BadArgs("err.command.set", task.command, opt); + } + task.command = task.listModuleDeps(true); } }, @@ -419,6 +459,7 @@ class JdepsTask { private final Options options = new Options(); private final List inputArgs = new ArrayList<>(); + private Command command; private PrintWriter log; void setLog(PrintWriter out) { log = out; @@ -445,55 +486,30 @@ class JdepsTask { if (options.version || options.fullVersion) { showVersion(options.fullVersion); } + if (options.help || options.version || options.fullVersion) { + return EXIT_OK; + } + if (!inputArgs.isEmpty() && options.rootModule != null) { reportError("err.invalid.arg.for.option", "-m"); } - if (inputArgs.isEmpty() && options.addmods.isEmpty() && options.includePattern == null - && options.includeSystemModulePattern == null && options.checkModuleDeps == null) { - if (options.help || options.version || options.fullVersion) { - return EXIT_OK; - } else { - showHelp(); - return EXIT_CMDERR; - } - } - if (options.genModuleInfo != null) { - if (options.dotOutputDir != null || options.classpath != null || options.hasFilter()) { - showHelp(); - return EXIT_CMDERR; - } - } if (options.numFilters() > 1) { reportError("err.invalid.filters"); return EXIT_CMDERR; } - if (options.inverse && options.depth != 1) { - reportError("err.invalid.inverse.option", "-R"); - return EXIT_CMDERR; + // default command to analyze dependences + if (command == null) { + command = analyzeDeps(); } - - if (options.inverse && options.numFilters() == 0) { - reportError("err.invalid.filters"); - return EXIT_CMDERR; - } - - if ((options.findJDKInternals) && (options.hasFilter() || options.showSummary)) { - showHelp(); - return EXIT_CMDERR; - } - if (options.showSummary && options.verbose != SUMMARY) { - showHelp(); - return EXIT_CMDERR; - } - if (options.checkModuleDeps != null && !inputArgs.isEmpty()) { - reportError("err.invalid.module.option", inputArgs, "--check"); + if (!command.checkOptions()) { return EXIT_CMDERR; } boolean ok = run(); return ok ? EXIT_OK : EXIT_ERROR; + } catch (BadArgs|UncheckedBadArgs e) { reportError(e.getKey(), e.getArgs()); if (e.showUsage()) { @@ -515,13 +531,14 @@ class JdepsTask { } boolean run() throws IOException { - try (JdepsConfiguration config = buildConfig()) { + try (JdepsConfiguration config = buildConfig(command.allModules())) { // detect split packages - config.splitPackages().entrySet().stream() + config.splitPackages().entrySet() + .stream() .sorted(Map.Entry.comparingByKey()) .forEach(e -> System.out.format("split package: %s %s%n", e.getKey(), - e.getValue().toString())); + e.getValue().toString())); // check if any module specified in --require is missing Stream.concat(options.addmods.stream(), options.requires.stream()) @@ -529,38 +546,11 @@ class JdepsTask { .forEach(mn -> config.findModule(mn).orElseThrow(() -> new UncheckedBadArgs(new BadArgs("err.module.not.found", mn)))); - // --generate-module-info - if (options.genModuleInfo != null) { - return genModuleInfo(config); - } - - // --check - if (options.checkModuleDeps != null) { - return new ModuleAnalyzer(config, log, options.checkModuleDeps).run(); - } - - if (options.showModulesAddExports) { - return new ModuleExportsAnalyzer(config, - dependencyFilter(config), - options.reduced, - log).run(); - } - - if (options.dotOutputDir != null && - (options.verbose == SUMMARY || options.verbose == MODULE) && - !options.addmods.isEmpty() && inputArgs.isEmpty()) { - return new ModuleAnalyzer(config, log).genDotFiles(options.dotOutputDir); - } - - if (options.inverse) { - return analyzeInverseDeps(config); - } else { - return analyzeDeps(config); - } + return command.run(config); } } - private JdepsConfiguration buildConfig() throws IOException { + private JdepsConfiguration buildConfig(boolean allModules) throws IOException { JdepsConfiguration.Builder builder = new JdepsConfiguration.Builder(options.systemModulePath); @@ -568,7 +558,7 @@ class JdepsTask { .appModulePath(options.modulePath) .addmods(options.addmods); - if (options.checkModuleDeps != null || options.showModulesAddExports) { + if (allModules) { // check all system modules in the image builder.allModules(); } @@ -592,148 +582,420 @@ class JdepsTask { return builder.build(); } - private boolean analyzeDeps(JdepsConfiguration config) throws IOException { - // output result - final JdepsWriter writer; - if (options.dotOutputDir != null) { - writer = new DotFileWriter(options.dotOutputDir, - options.verbose, - options.showProfile, - options.showModule, - options.showLabel); - } else { - writer = new SimpleWriter(log, - options.verbose, - options.showProfile, - options.showModule); - } + // ---- factory methods to create a Command - // analyze the dependencies - DepsAnalyzer analyzer = new DepsAnalyzer(config, - dependencyFilter(config), - writer, - options.verbose, - options.apiOnly); - - boolean ok = analyzer.run(options.compileTimeView, options.depth); - - // print skipped entries, if any - if (!options.nowarning) { - analyzer.archives() - .forEach(archive -> archive.reader() - .skippedEntries().stream() - .forEach(name -> warning("warn.skipped.entry", name))); - } - - if (options.findJDKInternals && !options.nowarning) { - Map jdkInternals = new TreeMap<>(); - Set deps = analyzer.dependences(); - // find the ones with replacement - deps.forEach(cn -> replacementFor(cn).ifPresent( - repl -> jdkInternals.put(cn, repl)) - ); - - if (!deps.isEmpty()) { - log.println(); - warning("warn.replace.useJDKInternals", getMessage("jdeps.wiki.url")); - } - - if (!jdkInternals.isEmpty()) { - log.println(); - log.format("%-40s %s%n", "JDK Internal API", "Suggested Replacement"); - log.format("%-40s %s%n", "----------------", "---------------------"); - jdkInternals.entrySet().stream() - .forEach(e -> { - String key = e.getKey(); - String[] lines = e.getValue().split("\\n"); - for (String s : lines) { - log.format("%-40s %s%n", key, s); - key = ""; - } - }); - } - } - return ok; + private AnalyzeDeps analyzeDeps() throws BadArgs { + return options.inverse ? new InverseAnalyzeDeps() + : new AnalyzeDeps(); } - private boolean analyzeInverseDeps(JdepsConfiguration config) throws IOException { - JdepsWriter writer = new SimpleWriter(log, - options.verbose, - options.showProfile, - options.showModule); - - InverseDepsAnalyzer analyzer = new InverseDepsAnalyzer(config, - dependencyFilter(config), - writer, - options.verbose, - options.apiOnly); - boolean ok = analyzer.run(); - - log.println(); - if (!options.requires.isEmpty()) - log.format("Inverse transitive dependences on %s%n", options.requires); - else - log.format("Inverse transitive dependences matching %s%n", - options.regex != null - ? options.regex.toString() - : "packages " + options.packageNames); - - analyzer.inverseDependences().stream() - .sorted(Comparator.comparing(this::sortPath)) - .forEach(path -> log.println(path.stream() - .map(Archive::getName) - .collect(Collectors.joining(" <- ")))); - return ok; + private GenDotFile genDotFile(Path dir) throws BadArgs { + if (Files.exists(dir) && (!Files.isDirectory(dir) || !Files.isWritable(dir))) { + throw new BadArgs("err.invalid.path", dir.toString()); + } + return new GenDotFile(dir); } - private String sortPath(Deque path) { - return path.peekFirst().getName(); + private GenModuleInfo genModuleInfo(Path dir) throws BadArgs { + if (Files.exists(dir) && (!Files.isDirectory(dir) || !Files.isWritable(dir))) { + throw new BadArgs("err.invalid.path", dir.toString()); + } + return new GenModuleInfo(dir); } - private boolean genModuleInfo(JdepsConfiguration config) throws IOException { - // check if any JAR file contains unnamed package - for (String arg : inputArgs) { - try (ClassFileReader reader = ClassFileReader.newInstance(Paths.get(arg))) { - Optional classInUnnamedPackage = - reader.entries().stream() - .filter(n -> n.endsWith(".class")) - .filter(cn -> toPackageName(cn).isEmpty()) - .findFirst(); + private ListModuleDeps listModuleDeps(boolean reduced) throws BadArgs { + return reduced ? new ListReducedDeps() + : new ListModuleDeps(); + } - if (classInUnnamedPackage.isPresent()) { - if (classInUnnamedPackage.get().equals("module-info.class")) { - reportError("err.genmoduleinfo.not.jarfile", arg); - } else { - reportError("err.genmoduleinfo.unnamed.package", arg); - } + private CheckModuleDeps checkModuleDeps(Set mods) throws BadArgs { + return new CheckModuleDeps(mods); + } + + abstract class Command { + final CommandOption option; + protected Command(CommandOption option) { + this.option = option; + } + /** + * Returns true if the command-line options are all valid; + * otherwise, returns false. + */ + abstract boolean checkOptions(); + + /** + * Do analysis + */ + abstract boolean run(JdepsConfiguration config) throws IOException; + + /** + * Includes all modules on system module path and application module path + */ + boolean allModules() { + return false; + } + + @Override + public String toString() { + return option.toString(); + } + } + + + /** + * Analyze dependences + */ + class AnalyzeDeps extends Command { + JdepsWriter writer; + AnalyzeDeps() { + this(CommandOption.ANALYZE_DEPS); + } + + AnalyzeDeps(CommandOption option) { + super(option); + } + + @Override + boolean checkOptions() { + if (options.findJDKInternals) { + // cannot set any filter, -verbose and -summary option + if (options.showSummary || options.verbose != null) { + reportError("err.invalid.options", "-summary or -verbose", + "-jdkinternals"); + return false; + } + if (options.hasFilter()) { + reportError("err.invalid.options", "--package, --regex, --require", + "-jdkinternals"); return false; } } + if (options.showSummary) { + // -summary cannot use with -verbose option + if (options.verbose != null) { + reportError("err.invalid.options", "-v, -verbose", "-s, -summary"); + return false; + } + } + if (inputArgs.isEmpty() && !options.hasSourcePath()) { + showHelp(); + return false; + } + return true; } - ModuleInfoBuilder builder - = new ModuleInfoBuilder(config, inputArgs, options.genModuleInfo); - boolean ok = builder.run(); + /* + * Default is to show package-level dependencies + */ + Type getAnalyzerType() { + if (options.showSummary) + return Type.SUMMARY; - if (!ok && !options.nowarning) { - log.println("ERROR: missing dependencies"); - builder.visitMissingDeps( - new Analyzer.Visitor() { - @Override - public void visitDependence(String origin, Archive originArchive, - String target, Archive targetArchive) { - if (builder.notFound(targetArchive)) - log.format(" %-50s -> %-50s %s%n", - origin, target, targetArchive.getName()); - } - }); + if (options.findJDKInternals) + return Type.CLASS; + + // default to package-level verbose + return options.verbose != null ? options.verbose : PACKAGE; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + Type type = getAnalyzerType(); + // default to package-level verbose + JdepsWriter writer = new SimpleWriter(log, + type, + options.showProfile, + options.showModule); + + return run(config, writer, type); + } + + boolean run(JdepsConfiguration config, JdepsWriter writer, Type type) throws IOException { + + + // analyze the dependencies + DepsAnalyzer analyzer = new DepsAnalyzer(config, + dependencyFilter(config), + writer, + type, + options.apiOnly); + + boolean ok = analyzer.run(options.compileTimeView, options.depth); + + // print skipped entries, if any + if (!options.nowarning) { + analyzer.archives() + .forEach(archive -> archive.reader() + .skippedEntries().stream() + .forEach(name -> warning("warn.skipped.entry", name))); + } + + if (options.findJDKInternals && !options.nowarning) { + Map jdkInternals = new TreeMap<>(); + Set deps = analyzer.dependences(); + // find the ones with replacement + deps.forEach(cn -> replacementFor(cn).ifPresent( + repl -> jdkInternals.put(cn, repl)) + ); + + if (!deps.isEmpty()) { + log.println(); + warning("warn.replace.useJDKInternals", getMessage("jdeps.wiki.url")); + } + + if (!jdkInternals.isEmpty()) { + log.println(); + log.format("%-40s %s%n", "JDK Internal API", "Suggested Replacement"); + log.format("%-40s %s%n", "----------------", "---------------------"); + jdkInternals.entrySet().stream() + .forEach(e -> { + String key = e.getKey(); + String[] lines = e.getValue().split("\\n"); + for (String s : lines) { + log.format("%-40s %s%n", key, s); + key = ""; + } + }); + } + } + return ok; } - return ok; } - private String toPackageName(String name) { - int i = name.lastIndexOf('/'); - return i > 0 ? name.replace('/', '.').substring(0, i) : ""; + + class InverseAnalyzeDeps extends AnalyzeDeps { + InverseAnalyzeDeps() { + } + + @Override + boolean checkOptions() { + if (options.depth != 1) { + reportError("err.invalid.options", "-R", "--inverse"); + return false; + } + + if (options.numFilters() == 0) { + reportError("err.filter.not.specified"); + return false; + } + + if (!super.checkOptions()) { + return false; + } + + return true; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + Type type = getAnalyzerType(); + + InverseDepsAnalyzer analyzer = + new InverseDepsAnalyzer(config, + dependencyFilter(config), + writer, + type, + options.apiOnly); + boolean ok = analyzer.run(); + + log.println(); + if (!options.requires.isEmpty()) + log.format("Inverse transitive dependences on %s%n", options.requires); + else + log.format("Inverse transitive dependences matching %s%n", + options.regex != null + ? options.regex.toString() + : "packages " + options.packageNames); + + analyzer.inverseDependences().stream() + .sorted(Comparator.comparing(this::sortPath)) + .forEach(path -> log.println(path.stream() + .map(Archive::getName) + .collect(joining(" <- ")))); + return ok; + } + + private String sortPath(Deque path) { + return path.peekFirst().getName(); + } + } + + + class GenModuleInfo extends Command { + final Path dir; + GenModuleInfo(Path dir) { + super(CommandOption.GENERATE_MODULE_INFO); + this.dir = dir; + } + + @Override + boolean checkOptions() { + if (options.classpath != null) { + reportError("err.invalid.options", "-classpath", + option); + return false; + } + if (options.hasFilter()) { + reportError("err.invalid.options", "--package, --regex, --require", + option); + return false; + } + return true; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + // check if any JAR file contains unnamed package + for (String arg : inputArgs) { + try (ClassFileReader reader = ClassFileReader.newInstance(Paths.get(arg))) { + Optional classInUnnamedPackage = + reader.entries().stream() + .filter(n -> n.endsWith(".class")) + .filter(cn -> toPackageName(cn).isEmpty()) + .findFirst(); + + if (classInUnnamedPackage.isPresent()) { + if (classInUnnamedPackage.get().equals("module-info.class")) { + reportError("err.genmoduleinfo.not.jarfile", arg); + } else { + reportError("err.genmoduleinfo.unnamed.package", arg); + } + return false; + } + } + } + + ModuleInfoBuilder builder + = new ModuleInfoBuilder(config, inputArgs, dir); + boolean ok = builder.run(); + + if (!ok && !options.nowarning) { + log.println("ERROR: missing dependencies"); + builder.visitMissingDeps( + new Analyzer.Visitor() { + @Override + public void visitDependence(String origin, Archive originArchive, + String target, Archive targetArchive) { + if (builder.notFound(targetArchive)) + log.format(" %-50s -> %-50s %s%n", + origin, target, targetArchive.getName()); + } + }); + } + return ok; + } + + private String toPackageName(String name) { + int i = name.lastIndexOf('/'); + return i > 0 ? name.replace('/', '.').substring(0, i) : ""; + } + } + + class CheckModuleDeps extends Command { + final Set modules; + CheckModuleDeps(Set mods) { + super(CommandOption.CHECK_MODULES); + this.modules = mods; + } + + @Override + boolean checkOptions() { + if (!inputArgs.isEmpty()) { + reportError("err.invalid.options", inputArgs, "--check"); + return false; + } + return true; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + if (!config.initialArchives().isEmpty()) { + String list = config.initialArchives().stream() + .map(Archive::getPathName).collect(joining(" ")); + throw new UncheckedBadArgs(new BadArgs("err.invalid.options", + list, "--check")); + } + return new ModuleAnalyzer(config, log, modules).run(); + } + + public boolean allModules() { + return true; + } + } + + class ListReducedDeps extends ListModuleDeps { + ListReducedDeps() { + super(CommandOption.LIST_REDUCED_DEPS, true); + } + } + + class ListModuleDeps extends Command { + final boolean reduced; + ListModuleDeps() { + this(CommandOption.LIST_DEPS, false); + } + ListModuleDeps(CommandOption option, boolean reduced) { + super(option); + this.reduced = reduced; + } + + @Override + boolean checkOptions() { + if (options.showSummary || options.verbose != null) { + reportError("err.invalid.options", "-summary or -verbose", + option); + return false; + } + if (options.findJDKInternals) { + reportError("err.invalid.options", "-jdkinternals", + option); + return false; + } + if (inputArgs.isEmpty() && !options.hasSourcePath()) { + showHelp(); + return false; + } + return true; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + return new ModuleExportsAnalyzer(config, + dependencyFilter(config), + reduced, + log).run(); + } + + public boolean allModules() { + return true; + } + } + + + class GenDotFile extends AnalyzeDeps { + final Path dotOutputDir; + GenDotFile(Path dotOutputDir) { + super(CommandOption.GENERATE_DOT_FILE); + + this.dotOutputDir = dotOutputDir; + } + + @Override + boolean run(JdepsConfiguration config) throws IOException { + if ((options.showSummary || options.verbose == MODULE) && + !options.addmods.isEmpty() && inputArgs.isEmpty()) { + // print module descriptor + return new ModuleAnalyzer(config, log).genDotFiles(dotOutputDir); + } + + Type type = getAnalyzerType(); + JdepsWriter writer = new DotFileWriter(dotOutputDir, + type, + options.showProfile, + options.showModule, + options.showLabel); + return run(config, writer, type); + } } /** @@ -875,14 +1137,11 @@ class JdepsTask { boolean showLabel; boolean findJDKInternals; boolean nowarning = false; - // default is to show package-level dependencies - // and filter references from same package - Analyzer.Type verbose = PACKAGE; + Analyzer.Type verbose; + // default filter references from same package boolean filterSamePackage = true; boolean filterSameArchive = false; Pattern filterRegex; - Path dotOutputDir; - Path genModuleInfo; String classpath; int depth = 1; Set requires = new HashSet<>(); @@ -892,15 +1151,17 @@ class JdepsTask { Pattern includeSystemModulePattern; boolean inverse = false; boolean compileTimeView = false; - Set checkModuleDeps; String systemModulePath = System.getProperty("java.home"); String upgradeModulePath; String modulePath; String rootModule; Set addmods = new HashSet<>(); Runtime.Version multiRelease; - boolean showModulesAddExports; - boolean reduced; + + boolean hasSourcePath() { + return !addmods.isEmpty() || includePattern != null || + includeSystemModulePattern != null; + } boolean hasFilter() { return numFilters() > 0; diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java index c5a5a971158..9c0d65cfc1a 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java @@ -70,14 +70,6 @@ public class ModuleAnalyzer { public ModuleAnalyzer(JdepsConfiguration config, PrintWriter log, Set names) { - - if (!config.initialArchives().isEmpty()) { - String list = config.initialArchives().stream() - .map(Archive::getPathName).collect(joining(" ")); - throw new JdepsTask.UncheckedBadArgs(new BadArgs("err.invalid.module.option", - list, "--check")); - } - this.configuration = config; this.log = log; diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdeps.properties b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdeps.properties index 8bff48b92dc..4189ae86745 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdeps.properties +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/resources/jdeps.properties @@ -151,7 +151,9 @@ main.opt.jdkinternals=\ main.opt.list-deps=\ \ --list-deps Lists the dependences and use of JDK internal\n\ -\ APIs.\n\ +\ APIs. + +main.opt.list-reduced-deps=\ \ --list-reduced-deps Same as --list-deps with not listing\n\ \ the implied reads edges from the module graph\n\ \ If module M1 depends on M2 and M3,\n\ @@ -171,6 +173,7 @@ main.opt.multi-release=\ \ multi-release jar files. should\n\ \ be integer >= 9 or base. +err.command.set={0} and {1} options are specified. err.unknown.option=unknown option: {0} err.missing.arg=no value given for {0} err.invalid.arg.for.option=invalid argument for option: {0} @@ -180,11 +183,10 @@ err.genmoduleinfo.unnamed.package={0} contains an unnamed package that is not al err.profiles.msg=No profile information err.exception.message={0} err.invalid.path=invalid path: {0} -err.invalid.module.option=Cannot set {0} with {1} option. -err.invalid.filters=Only one of --package (-p), --regex (-e), --require option can be set +err.invalid.options={0} cannot be used with {1} option err.module.not.found=module not found: {0} err.root.module.not.set=root module set empty -err.invalid.inverse.option={0} cannot be used with --inverse option +err.filter.not.specified=--package (-p), --regex (-e), --require option must be specified err.multirelease.option.exists={0} is not a multi-release jar file, but the --multi-release option is set err.multirelease.option.notfound={0} is a multi-release jar file, but the --multi-release option is not set err.multirelease.version.associated=class {0} already associated with version {1}, trying to add version {2} diff --git a/langtools/test/tools/jdeps/DotFileTest.java b/langtools/test/tools/jdeps/DotFileTest.java index 0dd4296776c..944d3a3694d 100644 --- a/langtools/test/tools/jdeps/DotFileTest.java +++ b/langtools/test/tools/jdeps/DotFileTest.java @@ -136,8 +136,6 @@ public class DotFileTest { // with -P option List argsWithDashP = new ArrayList<>(); - argsWithDashP.add("-dotoutput"); - argsWithDashP.add(dotoutput.toString()); argsWithDashP.add("-P"); argsWithDashP.addAll(args); @@ -162,8 +160,6 @@ public class DotFileTest { // with -P option List argsWithDashP = new ArrayList<>(); - argsWithDashP.add("-dotoutput"); - argsWithDashP.add(dotoutput.toString()); argsWithDashP.add("-P"); argsWithDashP.addAll(args); diff --git a/langtools/test/tools/jdeps/Options.java b/langtools/test/tools/jdeps/Options.java new file mode 100644 index 00000000000..40da51047c8 --- /dev/null +++ b/langtools/test/tools/jdeps/Options.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8168386 + * @summary Test option validation + * @modules jdk.jdeps + * @library lib + * @build JdepsRunner + * @run testng Options + */ + + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertTrue; + +public class Options { + private static final String TEST_CLASSES = System.getProperty("test.classes"); + + @DataProvider(name = "errors") + public Object[][] errors() { + return new Object[][]{ + { + new String[] { "-summary", "-v", TEST_CLASSES }, + "-v, -verbose cannot be used with -s, -summary option" + }, + { + new String[] { "-jdkinternal", "-summary", TEST_CLASSES }, + "-summary or -verbose cannot be used with -jdkinternals option" + }, + { + new String[] { "-jdkinternal", "-p", "java.lang", TEST_CLASSES }, + "--package, --regex, --require cannot be used with -jdkinternals option" + }, + { + new String[] { "--inverse", TEST_CLASSES }, + "--package (-p), --regex (-e), --require option must be specified" + }, + { + new String[] { "--inverse", "-R", TEST_CLASSES }, + "-R cannot be used with --inverse option" + }, + { + new String[] { "--generate-module-info", "dots", "-cp", TEST_CLASSES }, + "-classpath cannot be used with --generate-module-info option" + }, + { + new String[] { "--list-deps", "-summary", TEST_CLASSES }, + "--list-deps and --list-reduced-deps options are specified" + }, + { + new String[] { "--list-deps", "--list-reduced-deps", TEST_CLASSES }, + "--list-deps and --list-reduced-deps options are specified" + }, + }; + } + + @Test(dataProvider = "errors") + public void test(String[] options, String expected) { + jdepsError(options).outputContains(expected); + } + + + public static JdepsRunner jdepsError(String... args) { + JdepsRunner jdeps = new JdepsRunner(args); + assertTrue(jdeps.run(true) != 0); + return jdeps; + } +} diff --git a/langtools/test/tools/jdeps/lib/JdepsRunner.java b/langtools/test/tools/jdeps/lib/JdepsRunner.java index 5d93f2fbd5a..1161558beaa 100644 --- a/langtools/test/tools/jdeps/lib/JdepsRunner.java +++ b/langtools/test/tools/jdeps/lib/JdepsRunner.java @@ -75,7 +75,7 @@ public class JdepsRunner { } public boolean outputContains(String s) { - return stdout.toString().contains(s); + return stdout.toString().contains(s) || stderr.toString().contains(s); } public void printStdout(PrintStream stream) { From 4e5211401e6c07777c0d20a656968bfae21c41fb Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Sat, 12 Nov 2016 09:26:08 -0800 Subject: [PATCH 113/402] 8169606: jdeps --list-reduced-deps should not show java.base as all modules require it Reviewed-by: dfuchs --- .../sun/tools/jdeps/JdepsConfiguration.java | 11 ++++-- .../com/sun/tools/jdeps/JdepsTask.java | 3 +- .../classes/com/sun/tools/jdeps/Module.java | 2 +- .../tools/jdeps/ModuleExportsAnalyzer.java | 35 +++++++++++++------ .../tools/jdeps/listdeps/ListModuleDeps.java | 17 +++++++-- .../test/tools/jdeps/listdeps/src/hi/Hi.java | 27 ++++++++++++++ 6 files changed, 79 insertions(+), 16 deletions(-) create mode 100644 langtools/test/tools/jdeps/listdeps/src/hi/Hi.java diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java index 02d6bc6ea9b..44159653d95 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java @@ -89,6 +89,7 @@ public class JdepsConfiguration implements AutoCloseable { List classpaths, List initialArchives, boolean allDefaultModules, + boolean allSystemModules, Runtime.Version version) throws IOException { @@ -107,6 +108,11 @@ public class JdepsConfiguration implements AutoCloseable { roots.isEmpty() || allDefaultModules) { mods.addAll(systemModulePath.defaultSystemRoots()); } + if (allSystemModules) { + systemModulePath.findAll().stream() + .map(mref -> mref.descriptor().name()) + .forEach(mods::add); + } this.configuration = Configuration.empty() .resolveRequires(finder, ModuleFinder.of(), mods); @@ -488,6 +494,7 @@ public class JdepsConfiguration implements AutoCloseable { ModuleFinder appModulePath; boolean addAllApplicationModules; boolean addAllDefaultModules; + boolean addAllSystemModules; Runtime.Version version; public Builder() { @@ -533,8 +540,7 @@ public class JdepsConfiguration implements AutoCloseable { * Include all system modules and modules found on modulepath */ public Builder allModules() { - systemModulePath.moduleNames() - .forEach(this.rootModules::add); + this.addAllSystemModules = true; this.addAllApplicationModules = true; return this; } @@ -588,6 +594,7 @@ public class JdepsConfiguration implements AutoCloseable { classPaths, initialArchives, addAllDefaultModules, + addAllSystemModules, version); } diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java index af5bfb50041..3ed77929c9c 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java @@ -966,7 +966,8 @@ class JdepsTask { log).run(); } - public boolean allModules() { + @Override + boolean allModules() { return true; } } diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java index 810498b6718..f00394a05a3 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java @@ -81,7 +81,7 @@ class Module extends Archive { * Returns module name */ public String name() { - return descriptor.name(); + return descriptor != null ? descriptor.name() : getName(); } public boolean isNamed() { diff --git a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java index 79847e6d6ec..8d7b82094a1 100644 --- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java +++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java @@ -33,6 +33,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import static com.sun.tools.jdeps.Analyzer.NOT_FOUND; @@ -140,20 +141,34 @@ public class ModuleExportsAnalyzer extends DepsAnalyzer { Set modules = builder.build().adjacentNodes(root); // if reduced is set, apply transition reduction - Set reducedSet = reduced ? builder.reduced().adjacentNodes(root) - : modules; + Set reducedSet; + if (reduced) { + Set nodes = builder.reduced().adjacentNodes(root); + if (nodes.size() == 1) { + // java.base only + reducedSet = nodes; + } else { + // java.base is mandated and can be excluded from the reduced graph + reducedSet = nodes.stream() + .filter(m -> !"java.base".equals(m.name()) || + jdkinternals.containsKey("java.base")) + .collect(Collectors.toSet()); + } + } else { + reducedSet = modules; + } modules.stream() .sorted(Comparator.comparing(Module::name)) .forEach(m -> { - if (jdkinternals.containsKey(m)) { - jdkinternals.get(m).stream() - .sorted() - .forEach(pn -> writer.format(" %s/%s%n", m, pn)); - } else if (reducedSet.contains(m)){ - // if the transition reduction is applied, show the reduced graph - writer.format(" %s%n", m); - } + if (jdkinternals.containsKey(m)) { + jdkinternals.get(m).stream() + .sorted() + .forEach(pn -> writer.format(" %s/%s%n", m, pn)); + } else if (reducedSet.contains(m)){ + // if the transition reduction is applied, show the reduced graph + writer.format(" %s%n", m); + } }); } diff --git a/langtools/test/tools/jdeps/listdeps/ListModuleDeps.java b/langtools/test/tools/jdeps/listdeps/ListModuleDeps.java index 1456fed1e19..9327565881a 100644 --- a/langtools/test/tools/jdeps/listdeps/ListModuleDeps.java +++ b/langtools/test/tools/jdeps/listdeps/ListModuleDeps.java @@ -24,7 +24,7 @@ /* * @test * @bug 8167057 - * @summary Tests split packages + * @summary Tests --list-deps and --list-reduced-deps options * @modules java.logging * java.xml * jdk.compiler @@ -53,6 +53,8 @@ public class ListModuleDeps { private static final Path CLASSES_DIR = Paths.get("classes"); private static final Path LIB_DIR = Paths.get("lib"); + private static final Path HI_CLASS = + CLASSES_DIR.resolve("hi").resolve("Hi.class"); private static final Path FOO_CLASS = CLASSES_DIR.resolve("z").resolve("Foo.class"); private static final Path BAR_CLASS = @@ -68,6 +70,9 @@ public class ListModuleDeps { // compile library assertTrue(CompilerUtils.compile(Paths.get(TEST_SRC, "src", "lib"), LIB_DIR)); + // simple program depends only on java.base + assertTrue(CompilerUtils.compile(Paths.get(TEST_SRC, "src", "hi"), CLASSES_DIR)); + // compile classes in unnamed module assertTrue(CompilerUtils.compile(Paths.get(TEST_SRC, "src", "z"), CLASSES_DIR, @@ -117,6 +122,11 @@ public class ListModuleDeps { } }, + { HI_CLASS, new String[] { + "java.base" + } + }, + { FOO_CLASS, new String[] { "java.base", "java.logging", @@ -155,9 +165,12 @@ public class ListModuleDeps { } }, + { HI_CLASS, new String[] { + "java.base" + } + }, { FOO_CLASS, new String[] { - "java.base", "java.sql", "unnamed module: lib" } diff --git a/langtools/test/tools/jdeps/listdeps/src/hi/Hi.java b/langtools/test/tools/jdeps/listdeps/src/hi/Hi.java new file mode 100644 index 00000000000..248ae724365 --- /dev/null +++ b/langtools/test/tools/jdeps/listdeps/src/hi/Hi.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package hi; + +public class Hi { +} From 863735b560cf237cb59d2866f2bde8ab1a45473e Mon Sep 17 00:00:00 2001 From: Volker Simonis Date: Mon, 14 Nov 2016 11:48:43 +0100 Subject: [PATCH 114/402] 8169630: Fix wrong cpu build flag for Linux/ppc64le build Reviewed-by: erikj --- common/autoconf/flags.m4 | 2 +- common/autoconf/generated-configure.sh | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index eb912119e70..6a0eb9f8e3e 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -942,7 +942,7 @@ AC_DEFUN([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK_HELPER], # Little endian machine uses ELFv2 ABI. $2JVM_CFLAGS="[$]$2JVM_CFLAGS -DABI_ELFv2" # Use Power8, this is the first CPU to support PPC64 LE with ELFv2 ABI. - $2JVM_CFLAGS="[$]$2JVM_CFLAGS -mcpu=power7 -mtune=power8" + $2JVM_CFLAGS="[$]$2JVM_CFLAGS -mcpu=power8 -mtune=power8" fi elif test "x$OPENJDK_$1_CPU" = xs390x; then if test "x$OPENJDK_$1_OS" = xlinux; then diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 131556f50ad..238387046d6 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -5093,7 +5093,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1478524503 +DATE_WHEN_GENERATED=1479120453 ############################################################################### # @@ -50124,7 +50124,7 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA # Little endian machine uses ELFv2 ABI. JVM_CFLAGS="$JVM_CFLAGS -DABI_ELFv2" # Use Power8, this is the first CPU to support PPC64 LE with ELFv2 ABI. - JVM_CFLAGS="$JVM_CFLAGS -mcpu=power7 -mtune=power8" + JVM_CFLAGS="$JVM_CFLAGS -mcpu=power8 -mtune=power8" fi elif test "x$OPENJDK_TARGET_CPU" = xs390x; then if test "x$OPENJDK_TARGET_OS" = xlinux; then @@ -50948,7 +50948,7 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA # Little endian machine uses ELFv2 ABI. OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -DABI_ELFv2" # Use Power8, this is the first CPU to support PPC64 LE with ELFv2 ABI. - OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -mcpu=power7 -mtune=power8" + OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -mcpu=power8 -mtune=power8" fi elif test "x$OPENJDK_BUILD_CPU" = xs390x; then if test "x$OPENJDK_BUILD_OS" = xlinux; then From 95d99302d82d78f185dc1b44e05aa57304f3bb95 Mon Sep 17 00:00:00 2001 From: Srikanth Adayapalam Date: Mon, 14 Nov 2016 19:45:41 +0530 Subject: [PATCH 115/402] 8168312: javac throws NPE if annotation processor is specified and module is declared in a file named arbitrarily Reviewed-by: jlahoda --- .../com/sun/tools/javac/code/Symtab.java | 14 ++- .../com/sun/tools/javac/comp/Modules.java | 8 +- ...nProcessingWithModuleInfoInWrongPlace.java | 99 +++++++++++++++++++ 3 files changed, 116 insertions(+), 5 deletions(-) create mode 100644 langtools/test/tools/javac/modules/AnnotationProcessingWithModuleInfoInWrongPlace.java diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java index 40c9211b61d..202ca4e5dfe 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symtab.java @@ -383,7 +383,19 @@ public class Symtab { addRootPackageFor(unnamedModule); unnamedModule.enclosedPackages = unnamedModule.enclosedPackages.prepend(unnamedModule.unnamedPackage); - errModule = new ModuleSymbol(names.empty, null) { }; + errModule = new ModuleSymbol(names.empty, null) { + { + directives = List.nil(); + exports = List.nil(); + provides = List.nil(); + uses = List.nil(); + ModuleSymbol java_base = enterModule(names.java_base); + com.sun.tools.javac.code.Directive.RequiresDirective d = + new com.sun.tools.javac.code.Directive.RequiresDirective(java_base, + EnumSet.of(com.sun.tools.javac.code.Directive.RequiresFlag.MANDATED)); + requires = List.of(d); + } + }; addRootPackageFor(errModule); noModule = new ModuleSymbol(names.empty, null) { diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java index 2850e2506f4..b52af6545d6 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java @@ -293,8 +293,11 @@ public class Modules extends JCTree.Visitor { private void enterModule(JCCompilationUnit toplevel, ClassSymbol c, Set modules) { boolean isModuleInfo = toplevel.sourcefile.isNameCompatible("module-info", Kind.SOURCE); boolean isModuleDecl = toplevel.defs.nonEmpty() && toplevel.defs.head.hasTag(MODULEDEF); - if (isModuleInfo && isModuleDecl) { + if (isModuleDecl) { JCModuleDecl decl = (JCModuleDecl) toplevel.defs.head; + if (!isModuleInfo) { + log.error(decl.pos(), Errors.ModuleDeclSbInModuleInfoJava); + } Name name = TreeInfo.fullName(decl.qualId); ModuleSymbol sym; if (c != null) { @@ -330,9 +333,6 @@ public class Modules extends JCTree.Visitor { JCTree tree = toplevel.defs.isEmpty() ? toplevel : toplevel.defs.head; log.error(tree.pos(), Errors.ExpectedModule); } - } else if (isModuleDecl) { - JCTree tree = toplevel.defs.head; - log.error(tree.pos(), Errors.ModuleDeclSbInModuleInfoJava); } } diff --git a/langtools/test/tools/javac/modules/AnnotationProcessingWithModuleInfoInWrongPlace.java b/langtools/test/tools/javac/modules/AnnotationProcessingWithModuleInfoInWrongPlace.java new file mode 100644 index 00000000000..1a5e17842fd --- /dev/null +++ b/langtools/test/tools/javac/modules/AnnotationProcessingWithModuleInfoInWrongPlace.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8168312 + * @summary javac throws NPE if annotation processor is specified and module is declared in a file named arbitrarily + * @library /tools/lib + * @modules + * jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase + * @run main AnnotationProcessingWithModuleInfoInWrongPlace + */ + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; + +import toolbox.JavacTask; +import toolbox.Task; + +public class AnnotationProcessingWithModuleInfoInWrongPlace extends ModuleTestBase { + + public static void main(String... args) throws Exception { + new AnnotationProcessingWithModuleInfoInWrongPlace().runTests(); + } + + @Test + public void testModuleInfoInWrongPlace(Path base) throws Exception { + Path moduleSrc = base.resolve("module-src"); + Path m = moduleSrc.resolve("m"); + + Path classes = base.resolve("classes"); + + Files.createDirectories(classes); + + tb.writeJavaFiles(m, "module m {}"); + + Path mi = m.resolve("module-info.java"); + Path f = m.resolve("F.java"); + + tb.moveFile(mi, f); + + String log = new JavacTask(tb) + .options("-XDrawDiagnostics", + "--module-source-path", moduleSrc.toString(), + "-processor", AP.class.getName()) + .outdir(classes) + .files(findJavaFiles(moduleSrc)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutput(Task.OutputKind.DIRECT); + + + if (!log.contains("F.java:1:1: compiler.err.module.decl.sb.in.module-info.java")) + throw new AssertionError("Unexpected output: " + log); + } + + @SupportedAnnotationTypes("*") + public static final class AP extends AbstractProcessor { + + @Override + public boolean process(Set annot, RoundEnvironment env) { + return false; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latest(); + } + } +} From cbde1f4c5fb6d85a727345d0eab2f9d1481c06b1 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Mon, 14 Nov 2016 09:59:36 -0800 Subject: [PATCH 116/402] 8169518: Suppress Deprecation warnings for deprecated Swing APIs Reviewed-by: alexsch, ssadetsky --- .../classes/com/apple/laf/AquaTextFieldFormattedUI.java | 1 + .../macosx/classes/sun/lwawt/macosx/CAccessibleText.java | 1 + .../classes/sun/lwawt/macosx/CDragSourceContextPeer.java | 1 + .../classes/com/sun/java/swing/plaf/motif/MotifTextUI.java | 1 + .../com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java | 1 + .../com/sun/java/swing/plaf/windows/WindowsTextUI.java | 1 + .../java.desktop/share/classes/javax/swing/JEditorPane.java | 1 + .../share/classes/javax/swing/plaf/basic/BasicTextUI.java | 2 ++ .../share/classes/javax/swing/plaf/multi/MultiTextUI.java | 1 + .../share/classes/javax/swing/text/DefaultCaret.java | 6 ++++++ .../share/classes/javax/swing/text/DefaultEditorKit.java | 4 ++++ .../share/classes/javax/swing/text/DefaultHighlighter.java | 1 + .../share/classes/javax/swing/text/FieldView.java | 1 + .../share/classes/javax/swing/text/JTextComponent.java | 2 ++ .../share/classes/javax/swing/text/ParagraphView.java | 2 ++ .../share/classes/javax/swing/text/PasswordView.java | 2 ++ .../share/classes/javax/swing/text/PlainView.java | 2 ++ .../share/classes/javax/swing/text/Utilities.java | 4 ++++ .../java.desktop/share/classes/javax/swing/text/View.java | 1 + .../share/classes/javax/swing/text/WrappedPlainView.java | 3 +++ .../share/classes/javax/swing/text/html/AccessibleHTML.java | 1 + .../share/classes/javax/swing/text/html/HTMLEditorKit.java | 4 ++++ .../share/classes/sun/swing/JLightweightFrame.java | 1 + .../classes/sun/swing/text/TextComponentPrintable.java | 1 + 24 files changed, 45 insertions(+) diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java index bf258df6e4d..4fb08c8b37e 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java @@ -55,6 +55,7 @@ public class AquaTextFieldFormattedUI extends AquaTextFieldUI implements MouseLi super.uninstallListeners(); } + @SuppressWarnings("deprecation") public void mouseClicked(final MouseEvent e) { if (e.getClickCount() != 1) return; diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java index 6abf06ecd08..1f1dbea1885 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java @@ -293,6 +293,7 @@ class CAccessibleText { }, c); } + @SuppressWarnings("deprecation") static int[] getVisibleCharacterRange(final Accessible a) { final Accessible sa = CAccessible.getSwingAccessible(a); if (!(sa instanceof JTextComponent)) return null; diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java index 0c8d4afc08f..6a0f49a92b1 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java @@ -214,6 +214,7 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer { this.setDefaultDragImage(); } + @SuppressWarnings("deprecation") private void setDefaultDragImage(JTextComponent component) { DragGestureEvent trigger = getTrigger(); int selectionStart = component.getSelectionStart(); diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java index d198a942825..208a96840f6 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java @@ -124,6 +124,7 @@ public class MotifTextUI { * @param g the graphics context * @see #damage */ + @SuppressWarnings("deprecation") public void paint(Graphics g) { if(isVisible()) { try { diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java index 917f7a4ec27..4e5b3d6c1ae 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java @@ -132,6 +132,7 @@ public class WindowsTextFieldUI extends BasicTextFieldUI this.r = r; } + @SuppressWarnings("deprecation") public void run() { JTextField field = (JTextField) getComponent(); if (field != null) { diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java index 04c773c4e6c..58e9dfe5dbf 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java @@ -93,6 +93,7 @@ public abstract class WindowsTextUI extends BasicTextUI { * @param bounds the bounding box for the highlight * @param c the editor */ + @SuppressWarnings("deprecation") public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java index aed7fd3b992..5f1056ef4d5 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java @@ -825,6 +825,7 @@ public class JEditorPane extends JTextComponent { * * @param reference the named location to scroll to */ + @SuppressWarnings("deprecation") public void scrollToReference(String reference) { Document d = getDocument(); if (d instanceof HTMLDocument) { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java index 70020a002db..8acc5d7298e 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java @@ -1309,6 +1309,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory { * @see javax.swing.text.View#getToolTipText * @since 1.4 */ + @SuppressWarnings("deprecation") public String getToolTipText(JTextComponent t, Point pt) { if (!painted) { return null; @@ -2264,6 +2265,7 @@ public abstract class BasicTextUI extends TextUI implements ViewFactory { *

  • the press event is located over a selection * */ + @SuppressWarnings("deprecation") protected boolean isDragPossible(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.isEnabled()) { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java b/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java index df57f0bbecc..3102e4cd63d 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java @@ -85,6 +85,7 @@ public class MultiTextUI extends TextUI { * the UI obtained from the default LookAndFeel * @since 1.4 */ + @SuppressWarnings("deprecation") public String getToolTipText(JTextComponent a, Point b) { String returnValue = ((TextUI) (uis.elementAt(0))).getToolTipText(a,b); diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java index 134d94cb1fa..50457771068 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java @@ -304,6 +304,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * * @param e the mouse event */ + @SuppressWarnings("deprecation") protected void positionCaret(MouseEvent e) { Point pt = new Point(e.getX(), e.getY()); Position.Bias[] biasRet = new Position.Bias[1]; @@ -323,6 +324,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * * @param e the mouse event */ + @SuppressWarnings("deprecation") protected void moveCaret(MouseEvent e) { Point pt = new Point(e.getX(), e.getY()); Position.Bias[] biasRet = new Position.Bias[1]; @@ -615,6 +617,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * @param g the graphics context * @see #damage */ + @SuppressWarnings("deprecation") public void paint(Graphics g) { if(isVisible()) { try { @@ -959,6 +962,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * @see #isActive * @see Caret#setVisible */ + @SuppressWarnings("deprecation") public void setVisible(boolean e) { // focus lost notification can come in later after the // caret has been deinstalled, in which case the component @@ -1301,6 +1305,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * event thread so that calling modelToView * is safe. */ + @SuppressWarnings("deprecation") void repaintNewCaret() { if (component != null) { TextUI mapper = component.getUI(); @@ -1664,6 +1669,7 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou * * @param e the action event */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { if (width == 0 || height == 0) { // setVisible(true) will cause a scroll, only do this if the diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java index ca434585761..dc48035a5b4 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java @@ -1429,6 +1429,7 @@ public class DefaultEditorKit extends EditorKit { } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { @@ -1542,6 +1543,7 @@ public class DefaultEditorKit extends EditorKit { * Returns adjustsed {@code y} position that indicates the location to scroll to * after selecting index. */ + @SuppressWarnings("deprecation") private int getAdjustedY(JTextComponent text, Rectangle visible, int index) { int result = visible.y; @@ -1589,6 +1591,7 @@ public class DefaultEditorKit extends EditorKit { } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { @@ -1672,6 +1675,7 @@ public class DefaultEditorKit extends EditorKit { } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java index cc423788a0a..6ce84a0a849 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java @@ -405,6 +405,7 @@ public class DefaultHighlighter extends LayeredHighlighter { * @param bounds the bounding box for the highlight * @param c the editor */ + @SuppressWarnings("deprecation") public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java index 37b6f86a21f..936a78700be 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java @@ -205,6 +205,7 @@ public class FieldView extends PlainView { * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ + @SuppressWarnings("deprecation") public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java b/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java index 4e06e866dcf..241070327b2 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java @@ -785,6 +785,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * @param p the point to calculate a drop location for * @return the drop location, or null */ + @SuppressWarnings("deprecation") DropLocation dropLocationForPoint(Point p) { Position.Bias[] bias = new Position.Bias[1]; int index = getUI().viewToModel(this, p, bias); @@ -1959,6 +1960,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * @see javax.swing.plaf.TextUI#getToolTipText * @see javax.swing.ToolTipManager#registerComponent */ + @SuppressWarnings("deprecation") public String getToolTipText(MouseEvent event) { String retValue = super.getToolTipText(event); diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java index 5af2ebd3a3f..a40409c5b09 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java @@ -178,6 +178,7 @@ public class ParagraphView extends FlowView implements TabExpander { * @return the location in the model that represents the * next location visual position */ + @SuppressWarnings("deprecation") protected int getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) @@ -252,6 +253,7 @@ public class ParagraphView extends FlowView implements TabExpander { // NOTE: This will not properly work if ParagraphView contains // other ParagraphViews. It won't raise, but this does not message // the children views with getNextVisualPositionFrom. + @SuppressWarnings("deprecation") protected int getClosestPositionTo(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet, int rowIndex, int x) diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java index dc65285e75c..7da3fa313b2 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java @@ -84,6 +84,7 @@ public class PasswordView extends FieldView { return drawUnselectedTextImpl(g, x, y, p0, p1, true); } + @SuppressWarnings("deprecation") private float drawUnselectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) @@ -152,6 +153,7 @@ public class PasswordView extends FieldView { return drawSelectedTextImpl(g, x, y, p0, p1, true); } + @SuppressWarnings("deprecation") private float drawSelectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java index 8675436f610..e04c95aecd6 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java @@ -471,6 +471,7 @@ public class PlainView extends View implements TabExpander { * represent a valid location in the associated document * @see View#modelToView */ + @SuppressWarnings("deprecation") public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { // line coordinates Document doc = getDocument(); @@ -798,6 +799,7 @@ public class PlainView extends View implements TabExpander { * the given element. It is assumed that the font * and font metrics are up-to-date. */ + @SuppressWarnings("deprecation") private int getLineWidth(Element line) { if (line == null) { return 0; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java b/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java index 7fc2cd11cd0..b7516201f17 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java @@ -672,6 +672,7 @@ public class Utilities { * a value of -1 will be returned. * @exception BadLocationException if the offset is out of range */ + @SuppressWarnings("deprecation") public static final int getRowStart(JTextComponent c, int offs) throws BadLocationException { Rectangle r = c.modelToView(offs); if (r == null) { @@ -702,6 +703,7 @@ public class Utilities { * a value of -1 will be returned. * @exception BadLocationException if the offset is out of range */ + @SuppressWarnings("deprecation") public static final int getRowEnd(JTextComponent c, int offs) throws BadLocationException { Rectangle2D r = c.modelToView2D(offs); if (r == null) { @@ -744,6 +746,7 @@ public class Utilities { return getPositionAbove(c, offs, x, false); } + @SuppressWarnings("deprecation") static final int getPositionAbove(JTextComponent c, int offs, float x, boolean useFPAPI) throws BadLocationException { @@ -818,6 +821,7 @@ public class Utilities { return getPositionBelow(c, offs, x, false); } + @SuppressWarnings("deprecation") static final int getPositionBelow(JTextComponent c, int offs, float x, boolean useFPAPI) throws BadLocationException { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/View.java b/jdk/src/java.desktop/share/classes/javax/swing/text/View.java index 7b95bae0fd0..a1429e50e03 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/View.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/View.java @@ -501,6 +501,7 @@ public abstract class View implements SwingConstants { * @exception IllegalArgumentException if direction * doesn't have one of the legal values above */ + @SuppressWarnings("deprecation") public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java index 5549317d95c..6bb02264dd3 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java @@ -352,6 +352,7 @@ public class WrappedPlainView extends BoxView implements TabExpander { * @param p1 the ending document location to use * @return the break position */ + @SuppressWarnings("deprecation") protected int calculateBreakPosition(int p0, int p1) { int p; Segment segment = SegmentCache.getSharedSegment(); @@ -749,6 +750,7 @@ public class WrappedPlainView extends BoxView implements TabExpander { * valid location in the associated document * @see View#modelToView */ + @SuppressWarnings("deprecation") public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { Rectangle alloc = a.getBounds(); @@ -793,6 +795,7 @@ public class WrappedPlainView extends BoxView implements TabExpander { * given point in the view * @see View#viewToModel */ + @SuppressWarnings("deprecation") public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) { // PENDING(prinz) implement bias properly bias[0] = Position.Bias.Forward; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java b/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java index 660322ade36..e5dddf82eb5 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java @@ -936,6 +936,7 @@ class AccessibleHTML implements Accessible { * @return the screen coordinates of the character's the bounding box, * if index is invalid returns an empty rectangle. */ + @SuppressWarnings("deprecation") public Rectangle getCharacterBounds(int i) { try { return editor.getUI().modelToView(editor, i); diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java b/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java index 57beae1ddb9..d5d995e9fba 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java @@ -683,6 +683,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { * @param e the mouse event * @see MouseListener#mouseClicked */ + @SuppressWarnings("deprecation") public void mouseClicked(MouseEvent e) { JEditorPane editor = (JEditorPane) e.getSource(); @@ -701,6 +702,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { } // track the moving of the mouse. + @SuppressWarnings("deprecation") public void mouseMoved(MouseEvent e) { JEditorPane editor = (JEditorPane) e.getSource(); if (!editor.isEnabled()) { @@ -773,6 +775,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { * Returns a string anchor if the passed in element has a * USEMAP that contains the passed in location. */ + @SuppressWarnings("deprecation") private String getMapHREF(JEditorPane html, HTMLDocument hdoc, Element elem, AttributeSet attr, int offset, int x, int y) { @@ -813,6 +816,7 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { * the location x, y. offset * gives the offset into the Document to check for. */ + @SuppressWarnings("deprecation") private boolean doesElementContainLocation(JEditorPane editor, Element e, int offset, int x, int y) { diff --git a/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java b/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java index 450a62c57fe..9671ec9101a 100644 --- a/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java +++ b/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java @@ -249,6 +249,7 @@ public final class JLightweightFrame extends LightweightFrame implements RootPan } @Override + @SuppressWarnings("deprecation") public void notifyDisplayChanged(final int scaleFactor) { notifyDisplayChanged(scaleFactor, scaleFactor); } diff --git a/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java b/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java index eace48bcc26..6e60cd803b3 100644 --- a/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java +++ b/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java @@ -753,6 +753,7 @@ public class TextComponentPrintable implements CountingPrintable { * First step is to find yStart and yEnd for the every document position. * Second step is to merge all intersected segments ( [yStart, yEnd] ). */ + @SuppressWarnings("deprecation") private void calculateRowsMetrics() { final int documentLength = printShell.getDocument().getLength(); List documentMetrics = new ArrayList(LIST_SIZE); From 9ccb699c49c2ce392cfad1582dffec58cdbe72a9 Mon Sep 17 00:00:00 2001 From: Phil Race Date: Mon, 14 Nov 2016 10:00:15 -0800 Subject: [PATCH 117/402] 8169518: Suppress Deprecation warnings for deprecated Swing APIs Reviewed-by: alexsch, ssadetsky --- make/CompileJavaModules.gmk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/CompileJavaModules.gmk b/make/CompileJavaModules.gmk index 473d7f98d1b..c222a400c85 100644 --- a/make/CompileJavaModules.gmk +++ b/make/CompileJavaModules.gmk @@ -95,7 +95,7 @@ java.datatransfer_COPY := flavormap.properties ################################################################################ java.desktop_ADD_JAVAC_FLAGS := -Xdoclint:all/protected,-reference \ - '-Xdoclint/package:java.*,javax.*' -Xlint:-deprecation,exports + '-Xdoclint/package:java.*,javax.*' -Xlint:exports java.desktop_COPY := .gif .png .wav .txt .xml .css .pf java.desktop_CLEAN := iio-plugin.properties cursors.properties From a556619f93569d870a2119ed24f0df2b62c7f89e Mon Sep 17 00:00:00 2001 From: Anthony Scarpino Date: Mon, 14 Nov 2016 10:13:38 -0800 Subject: [PATCH 118/402] 8168861: AnchorCertificates uses hardcoded password for cacerts keystore Reviewed-by: vinnie, mullan --- .../share/classes/sun/security/util/AnchorCertificates.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/sun/security/util/AnchorCertificates.java b/jdk/src/java.base/share/classes/sun/security/util/AnchorCertificates.java index 60edcc85d60..e260dd44ac0 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/AnchorCertificates.java +++ b/jdk/src/java.base/share/classes/sun/security/util/AnchorCertificates.java @@ -58,7 +58,7 @@ public class AnchorCertificates { try { cacerts = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(f)) { - cacerts.load(fis, "changeit".toCharArray()); + cacerts.load(fis, null); certs = new HashSet<>(); Enumeration list = cacerts.aliases(); String alias; From 39b3b9cb3bac1c0878ad12622f4b0a1116d96bad Mon Sep 17 00:00:00 2001 From: Anthony Scarpino Date: Mon, 14 Nov 2016 13:32:15 -0800 Subject: [PATCH 119/402] 8168931: Few OCSP related test failed with "Response is unreliable: its validity interval is out-of-date" Reviewed-by: mullan --- .../sun/security/provider/certpath/RevocationChecker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java index 85e596cb6c3..5fba1666119 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java @@ -740,7 +740,7 @@ class RevocationChecker extends PKIXRevocationChecker { } response = OCSP.check(Collections.singletonList(certId), - responderURI, issuerInfo, responderCert, params.date(), + responderURI, issuerInfo, responderCert, null, ocspExtensions); } } catch (IOException e) { From 9b43eda24c57fb8c64db04b9b6dd4186c5cd00e6 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Mon, 14 Nov 2016 16:33:48 -0800 Subject: [PATCH 120/402] 8167967: javadoc should identify the ordinal value of enum constants Reviewed-by: jjg --- .../formats/html/AbstractMemberWriter.java | 2 +- .../formats/html/ConfigurationImpl.java | 2 - .../formats/html/ConstructorWriterImpl.java | 2 +- .../builders/AbstractMemberBuilder.java | 17 + .../builders/AnnotationTypeFieldBuilder.java | 39 +- .../AnnotationTypeRequiredMemberBuilder.java | 42 +- .../builders/ConstantsSummaryBuilder.java | 18 +- .../toolkit/builders/ConstructorBuilder.java | 40 +- .../toolkit/builders/EnumConstantBuilder.java | 38 +- .../toolkit/builders/FieldBuilder.java | 29 +- .../builders/MemberSummaryBuilder.java | 8 +- .../toolkit/builders/MethodBuilder.java | 38 +- .../toolkit/builders/PropertyBuilder.java | 35 +- .../internal/doclets/toolkit/util/Utils.java | 18 +- .../toolkit/util/VisibleMemberMap.java | 76 +- .../javadoc/doclet/testJavaFX/TestJavaFX.java | 29 +- .../doclet/testOrdering/TestOrdering.java | 1031 ++++++++++------- .../AnnoFieldTest.java} | 35 +- .../testOrdering/pkg5/AnnoOptionalTest.java | 31 + .../testOrdering/pkg5/AnnoRequiredTest.java | 31 + .../doclet/testOrdering/pkg5/CtorTest.java | 31 + .../doclet/testOrdering/pkg5/EnumTest.java | 31 + .../doclet/testOrdering/pkg5/FieldTest.java | 31 + .../doclet/testOrdering/pkg5/IntfTest.java | 31 + .../doclet/testOrdering/pkg5/MethodTest.java | 31 + .../testOrdering/pkg5/PropertyTest.java | 31 + 26 files changed, 990 insertions(+), 757 deletions(-) rename langtools/test/jdk/javadoc/doclet/testOrdering/{order/MethodOrder.java => pkg5/AnnoFieldTest.java} (63%) create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoOptionalTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoRequiredTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/CtorTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/EnumTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/FieldTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/IntfTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/MethodTest.java create mode 100644 langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/PropertyTest.java diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java index e7c5385d937..b671ed16c3b 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractMemberWriter.java @@ -535,7 +535,7 @@ public abstract class AbstractMemberWriter { TypeElement superClass = utils.getSuperClass(typeElement); while (superClass != null) { - if (visibleMemberMap.hasMembersFor(superClass)) { + if (visibleMemberMap.hasMembers(superClass)) { liNav.addContent(getNavSummaryLink(superClass, true)); return; } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java index d2607ba41b8..3485be66d24 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java @@ -135,8 +135,6 @@ public class ConfigurationImpl extends Configuration { */ public String docrootparent = ""; - public boolean sortedMethodDetails = false; - /** * True if command line option "-nohelp" is used. Default value is false. */ diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConstructorWriterImpl.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConstructorWriterImpl.java index be59ef815c9..612c2e0db06 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConstructorWriterImpl.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConstructorWriterImpl.java @@ -72,7 +72,7 @@ public class ConstructorWriterImpl extends AbstractExecutableMemberWriter VisibleMemberMap visibleMemberMap = new VisibleMemberMap( typeElement, VisibleMemberMap.Kind.CONSTRUCTORS, configuration); - SortedSet constructors = visibleMemberMap.getMembersFor(typeElement); + List constructors = visibleMemberMap.getMembers(typeElement); for (Element constructor : constructors) { if (utils.isProtected(constructor) || utils.isPrivate(constructor)) { setFoundNonPubConstructor(true); diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AbstractMemberBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AbstractMemberBuilder.java index ee0dba08fee..3bc2b1a1939 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AbstractMemberBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AbstractMemberBuilder.java @@ -25,6 +25,15 @@ package jdk.javadoc.internal.doclets.toolkit.builders; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.lang.model.element.Element; + +import jdk.javadoc.internal.doclets.formats.html.ConfigurationImpl; import jdk.javadoc.internal.doclets.toolkit.Content; import jdk.javadoc.internal.doclets.toolkit.DocletException; @@ -42,6 +51,7 @@ import jdk.javadoc.internal.doclets.toolkit.DocletException; */ public abstract class AbstractMemberBuilder extends AbstractBuilder { + public final Comparator comparator; /** * Construct a SubBuilder. * @param context a context object, providing information used in this run @@ -49,6 +59,7 @@ public abstract class AbstractMemberBuilder extends AbstractBuilder { */ public AbstractMemberBuilder(Context context) { super(context); + comparator = utils.makeGeneralPurposeComparator(); } /** @@ -83,4 +94,10 @@ public abstract class AbstractMemberBuilder extends AbstractBuilder { * @return true if this subbuilder has anything to document */ public abstract boolean hasMembersToDocument(); + + public SortedSet asSortedSet(Collection members) { + SortedSet out = new TreeSet<>(comparator); + out.addAll(members); + return out; + } } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java index f8d020ab904..9026429b7c9 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeFieldBuilder.java @@ -67,7 +67,7 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { /** * The list of members being documented. */ - protected SortedSet members; + protected List members; /** * The index of the current member that is being documented at this point @@ -91,7 +91,7 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { this.typeElement = typeElement; this.writer = writer; this.visibleMemberMap = new VisibleMemberMap(typeElement, memberType, configuration); - this.members = this.visibleMemberMap.getMembersFor(typeElement); + this.members = this.visibleMemberMap.getMembers(typeElement); } @@ -118,26 +118,6 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { return "AnnotationTypeFieldDetails"; } - /** - * Returns a list of members that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the TypeElement we want to check. - * @return a list of members that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the members of this class. - * - * @return the visible member map for the members of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } /** * Returns whether or not there are members to document. @@ -145,7 +125,7 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { */ @Override public boolean hasMembersToDocument() { - return members.size() > 0; + return !members.isEmpty(); } /** @@ -172,16 +152,19 @@ public class AnnotationTypeFieldBuilder extends AbstractMemberBuilder { if (writer == null) { return; } - if (!members.isEmpty()) { + if (hasMembersToDocument()) { writer.addAnnotationFieldDetailsMarker(memberDetailsTree); - for (Element element : members) { - currentMember = element; + + Element lastElement = members.get(members.size() - 1); + for (Element member : members) { + currentMember = member; Content detailsTree = writer.getMemberTreeHeader(); writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree); - Content annotationDocTree = writer.getAnnotationDocTreeHeader(element, detailsTree); + Content annotationDocTree = writer.getAnnotationDocTreeHeader(currentMember, + detailsTree); buildChildren(node, annotationDocTree); detailsTree.addContent(writer.getAnnotationDoc( - annotationDocTree, currentMember == members.last())); + annotationDocTree, currentMember == lastElement)); memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree)); } } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java index 8f4a678c585..412f723ef16 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/AnnotationTypeRequiredMemberBuilder.java @@ -68,7 +68,7 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { /** * The list of members being documented. */ - protected SortedSet members; + protected List members; /** * The index of the current member that is being documented at this point @@ -82,6 +82,7 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { * @param context the build context. * @param typeElement the class whose members are being documented. * @param writer the doclet specific writer. + * @param memberType the kind of member this builder processes. */ protected AnnotationTypeRequiredMemberBuilder(Context context, TypeElement typeElement, @@ -91,7 +92,7 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { this.typeElement = typeElement; this.writer = writer; this.visibleMemberMap = new VisibleMemberMap(typeElement, memberType, configuration); - this.members = this.visibleMemberMap.getMembersFor(typeElement); + this.members = this.visibleMemberMap.getMembers(typeElement); } @@ -101,6 +102,7 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { * @param context the build context. * @param typeElement the class whose members are being documented. * @param writer the doclet specific writer. + * @return an instance of this object */ public static AnnotationTypeRequiredMemberBuilder getInstance( Context context, TypeElement typeElement, @@ -118,34 +120,13 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { return "AnnotationTypeRequiredMemberDetails"; } - /** - * Returns a list of members that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the {@link TypeElement} we want to check. - * @return a list of members that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the members of this class. - * - * @return the visible member map for the members of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } - /** * Returns whether or not there are members to document. * @return whether or not there are members to document */ @Override public boolean hasMembersToDocument() { - return members.size() > 0; + return !members.isEmpty(); } /** @@ -165,24 +146,25 @@ public class AnnotationTypeRequiredMemberBuilder extends AbstractMemberBuilder { * * @param node the XML element that specifies which components to document * @param memberDetailsTree the content tree to which the documentation will be added + * @throws DocletException if an error occurs */ public void buildAnnotationTypeMember(XMLNode node, Content memberDetailsTree) throws DocletException { if (writer == null) { return; } - int size = members.size(); - if (size > 0) { + if (hasMembersToDocument()) { writer.addAnnotationDetailsMarker(memberDetailsTree); - for (Element element : members) { - currentMember = element; + Element lastMember = members.get((members.size() - 1)); + for (Element member : members) { + currentMember = member; Content detailsTree = writer.getMemberTreeHeader(); writer.addAnnotationDetailsTreeHeader(typeElement, detailsTree); Content annotationDocTree = writer.getAnnotationDocTreeHeader( - element, detailsTree); + currentMember, detailsTree); buildChildren(node, annotationDocTree); detailsTree.addContent(writer.getAnnotationDoc( - annotationDocTree, currentMember == members.last())); + annotationDocTree, currentMember == lastMember)); memberDetailsTree.addContent(writer.getAnnotationDetails(detailsTree)); } } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstantsSummaryBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstantsSummaryBuilder.java index 45eea2bc5b9..75a01fa5c73 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstantsSummaryBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstantsSummaryBuilder.java @@ -275,7 +275,7 @@ public class ConstantsSummaryBuilder extends AbstractBuilder { private boolean hasConstantField (TypeElement typeElement) { VisibleMemberMap visibleMemberMapFields = new VisibleMemberMap(typeElement, VisibleMemberMap.Kind.FIELDS, configuration); - SortedSet fields = visibleMemberMapFields.getLeafClassMembers(); + List fields = visibleMemberMapFields.getLeafMembers(); for (Element f : fields) { VariableElement field = (VariableElement)f; if (field.getConstantValue() != null) { @@ -350,21 +350,21 @@ public class ConstantsSummaryBuilder extends AbstractBuilder { } /** - * Return the list of visible constant fields for the given TypeElement. - * @return the list of visible constant fields for the given TypeElement. + * Returns a set of visible constant fields for the given type. + * @return the set of visible constant fields for the given type. */ protected SortedSet members() { - SortedSet list = visibleMemberMapFields.getLeafClassMembers(); - list.addAll(visibleMemberMapEnumConst.getLeafClassMembers()); - SortedSet inclList = + List members = visibleMemberMapFields.getLeafMembers(); + members.addAll(visibleMemberMapEnumConst.getLeafMembers()); + SortedSet includes = new TreeSet<>(utils.makeGeneralPurposeComparator()); - for (Element element : list) { + for (Element element : members) { VariableElement member = (VariableElement)element; if (member.getConstantValue() != null) { - inclList.add(member); + includes.add(member); } } - return inclList; + return includes; } } } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java index 787ba257eb7..ee8076bb72f 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/ConstructorBuilder.java @@ -59,7 +59,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { /** * The current constructor that is being documented at this point in time. */ - private ExecutableElement constructor; + private ExecutableElement currentConstructor; /** * The class whose constructors are being documented. @@ -79,7 +79,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { /** * The constructors being documented. */ - private final SortedSet constructors; + private final List constructors; /** * Construct a new ConstructorBuilder. @@ -99,7 +99,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { typeElement, VisibleMemberMap.Kind.CONSTRUCTORS, configuration); - constructors = visibleMemberMap.getMembersFor(typeElement); + constructors = visibleMemberMap.getMembers(typeElement); for (Element ctor : constructors) { if (utils.isProtected(ctor) || utils.isPrivate(ctor)) { writer.setFoundNonPubConstructor(true); @@ -136,18 +136,6 @@ public class ConstructorBuilder extends AbstractMemberBuilder { return !constructors.isEmpty(); } - /** - * Returns a list of constructors that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the class - * @return a list of constructors that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - /** * Return the constructor writer for this builder. * @@ -168,17 +156,17 @@ public class ConstructorBuilder extends AbstractMemberBuilder { if (writer == null) { return; } - int size = constructors.size(); - if (size > 0) { + if (hasMembersToDocument()) { Content constructorDetailsTree = writer.getConstructorDetailsTreeHeader(typeElement, memberDetailsTree); - for (Element ctor : constructors) { - constructor = (ExecutableElement)ctor; - Content constructorDocTree = writer.getConstructorDocTreeHeader( - constructor, constructorDetailsTree); + + Element lastElement = constructors.get(constructors.size() - 1); + for (Element contructor : constructors) { + currentConstructor = (ExecutableElement)contructor; + Content constructorDocTree = writer.getConstructorDocTreeHeader(currentConstructor, constructorDetailsTree); buildChildren(node, constructorDocTree); constructorDetailsTree.addContent(writer.getConstructorDoc(constructorDocTree, - constructors.last().equals(constructor))); + currentConstructor == lastElement)); } memberDetailsTree.addContent( writer.getConstructorDetails(constructorDetailsTree)); @@ -192,7 +180,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { * @param constructorDocTree the content tree to which the documentation will be added */ public void buildSignature(XMLNode node, Content constructorDocTree) { - constructorDocTree.addContent(writer.getSignature(constructor)); + constructorDocTree.addContent(writer.getSignature(currentConstructor)); } /** @@ -202,7 +190,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { * @param constructorDocTree the content tree to which the documentation will be added */ public void buildDeprecationInfo(XMLNode node, Content constructorDocTree) { - writer.addDeprecated(constructor, constructorDocTree); + writer.addDeprecated(currentConstructor, constructorDocTree); } /** @@ -214,7 +202,7 @@ public class ConstructorBuilder extends AbstractMemberBuilder { */ public void buildConstructorComments(XMLNode node, Content constructorDocTree) { if (!configuration.nocomment) { - writer.addComments(constructor, constructorDocTree); + writer.addComments(currentConstructor, constructorDocTree); } } @@ -225,6 +213,6 @@ public class ConstructorBuilder extends AbstractMemberBuilder { * @param constructorDocTree the content tree to which the documentation will be added */ public void buildTagInfo(XMLNode node, Content constructorDocTree) { - writer.addTags(constructor, constructorDocTree); + writer.addTags(currentConstructor, constructorDocTree); } } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java index 47ac296c5e9..ddb6619225e 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/EnumConstantBuilder.java @@ -67,9 +67,9 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { private final EnumConstantWriter writer; /** - * The list of enum constants being documented. + * The set of enum constants being documented. */ - private final SortedSet enumConstants; + private final List enumConstants; /** * The current enum constant that is being documented at this point @@ -94,7 +94,7 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { typeElement, VisibleMemberMap.Kind.ENUM_CONSTANTS, configuration); - enumConstants = visibleMemberMap.getMembersFor(typeElement); + enumConstants = visibleMemberMap.getMembers(typeElement); } /** @@ -118,27 +118,6 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { return "EnumConstantDetails"; } - /** - * Returns a list of enum constants that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the {@link TypeElement} we want to check. - * @return a list of enum constants that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the enum constants of this class. - * - * @return the visible member map for the enum constants of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } - /** * Returns whether or not there are members to document. * @@ -146,7 +125,7 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { */ @Override public boolean hasMembersToDocument() { - return enumConstants.size() > 0; + return !enumConstants.isEmpty(); } /** @@ -160,16 +139,17 @@ public class EnumConstantBuilder extends AbstractMemberBuilder { if (writer == null) { return; } - if (!enumConstants.isEmpty()) { + if (hasMembersToDocument()) { Content enumConstantsDetailsTree = writer.getEnumConstantsDetailsTreeHeader(typeElement, memberDetailsTree); - for (Element element : enumConstants) { - currentElement = (VariableElement)element; + Element lastElement = enumConstants.get(enumConstants.size() - 1); + for (Element enumConstant : enumConstants) { + currentElement = (VariableElement)enumConstant; Content enumConstantsTree = writer.getEnumConstantsTreeHeader(currentElement, enumConstantsDetailsTree); buildChildren(node, enumConstantsTree); enumConstantsDetailsTree.addContent(writer.getEnumConstants( - enumConstantsTree, currentElement.equals(enumConstants.last()))); + enumConstantsTree, currentElement == lastElement)); } memberDetailsTree.addContent( writer.getEnumConstantsDetails(enumConstantsDetailsTree)); diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java index 09f6965f07f..ccb5671b9ab 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/FieldBuilder.java @@ -69,7 +69,7 @@ public class FieldBuilder extends AbstractMemberBuilder { /** * The list of fields being documented. */ - private final SortedSet fields; + private final List fields; /** * The index of the current field that is being documented at this point @@ -95,7 +95,7 @@ public class FieldBuilder extends AbstractMemberBuilder { typeElement, VisibleMemberMap.Kind.FIELDS, configuration); - fields = visibleMemberMap.getLeafClassMembers(); + fields = visibleMemberMap.getLeafMembers(); } /** @@ -120,27 +120,6 @@ public class FieldBuilder extends AbstractMemberBuilder { return "FieldDetails"; } - /** - * Returns a list of fields that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the {@link TypeElement} we want to check. - * @return a list of fields that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the fields of this class. - * - * @return the visible member map for the fields of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } - /** * Returns whether or not there are members to document. * @@ -164,12 +143,14 @@ public class FieldBuilder extends AbstractMemberBuilder { } if (!fields.isEmpty()) { Content fieldDetailsTree = writer.getFieldDetailsTreeHeader(typeElement, memberDetailsTree); + + Element lastElement = fields.get(fields.size() - 1); for (Element element : fields) { currentElement = (VariableElement)element; Content fieldDocTree = writer.getFieldDocTreeHeader(currentElement, fieldDetailsTree); buildChildren(node, fieldDocTree); fieldDetailsTree.addContent(writer.getFieldDoc( - fieldDocTree, currentElement.equals(fields.last()))); + fieldDocTree, currentElement == lastElement)); } memberDetailsTree.addContent( writer.getFieldDetails(fieldDetailsTree)); diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java index 713fc028e7c..5534abd0bd3 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MemberSummaryBuilder.java @@ -182,7 +182,9 @@ public class MemberSummaryBuilder extends AbstractMemberBuilder { * @see VisibleMemberMap */ public SortedSet members(VisibleMemberMap.Kind type) { - return visibleMemberMaps.get(type).getLeafClassMembers(); + TreeSet out = new TreeSet<>(comparator); + out.addAll(visibleMemberMaps.get(type).getLeafMembers()); + return out; } /** @@ -336,7 +338,7 @@ public class MemberSummaryBuilder extends AbstractMemberBuilder { */ private void buildSummary(MemberSummaryWriter writer, VisibleMemberMap visibleMemberMap, LinkedList summaryTreeList) { - SortedSet members = visibleMemberMap.getLeafClassMembers(); + SortedSet members = asSortedSet(visibleMemberMap.getLeafMembers()); if (!members.isEmpty()) { List tableContents = new LinkedList<>(); int counter = 0; @@ -492,7 +494,7 @@ public class MemberSummaryBuilder extends AbstractMemberBuilder { if (inhclass == typeElement) { continue; } - SortedSet inhmembers = visibleMemberMap.getMembersFor(inhclass); + SortedSet inhmembers = asSortedSet(visibleMemberMap.getMembers(inhclass)); if (!inhmembers.isEmpty()) { Content inheritedTree = writer.getInheritedSummaryHeader(inhclass); Content linksTree = writer.getInheritedSummaryLinksTree(); diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java index 7511bdad07d..ba0e88a287b 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/MethodBuilder.java @@ -78,7 +78,7 @@ public class MethodBuilder extends AbstractMemberBuilder { /** * The methods being documented. */ - private final SortedSet methods; + private final List methods; /** @@ -98,7 +98,7 @@ public class MethodBuilder extends AbstractMemberBuilder { typeElement, VisibleMemberMap.Kind.METHODS, configuration); - methods = visibleMemberMap.getLeafClassMembers(); + methods = visibleMemberMap.getLeafMembers(); } /** @@ -123,27 +123,6 @@ public class MethodBuilder extends AbstractMemberBuilder { return "MethodDetails"; } - /** - * Returns a list of methods that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the {@link TypeElement} we want to check. - * @return a list of methods that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the methods of this class. - * - * @return the visible member map for the methods of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } - /** * {@inheritDoc} */ @@ -163,18 +142,17 @@ public class MethodBuilder extends AbstractMemberBuilder { if (writer == null) { return; } - if (!methods.isEmpty()) { + if (hasMembersToDocument()) { Content methodDetailsTree = writer.getMethodDetailsTreeHeader(typeElement, memberDetailsTree); - Set methodDetailSet = ((ConfigurationImpl)configuration).sortedMethodDetails - ? methods - : visibleMemberMap.getLeafClassMembersSourceOrder(); - for (Element e : methodDetailSet) { - currentMethod = (ExecutableElement) e; + + Element lastElement = methods.get(methods.size() - 1); + for (Element method : methods) { + currentMethod = (ExecutableElement)method; Content methodDocTree = writer.getMethodDocTreeHeader(currentMethod, methodDetailsTree); buildChildren(node, methodDocTree); methodDetailsTree.addContent(writer.getMethodDoc( - methodDocTree, currentMethod == methods.last())); + methodDocTree, currentMethod == lastElement)); } memberDetailsTree.addContent(writer.getMethodDetails(methodDetailsTree)); } diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java index 68af2e3447b..986924f61fb 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PropertyBuilder.java @@ -69,7 +69,7 @@ public class PropertyBuilder extends AbstractMemberBuilder { /** * The list of properties being documented. */ - private final SortedSet properties; + private final List properties; /** * The index of the current property that is being documented at this point @@ -95,7 +95,7 @@ public class PropertyBuilder extends AbstractMemberBuilder { typeElement, VisibleMemberMap.Kind.PROPERTIES, configuration); - properties = visibleMemberMap.getMembersFor(typeElement); + properties = visibleMemberMap.getMembers(typeElement); } /** @@ -120,27 +120,6 @@ public class PropertyBuilder extends AbstractMemberBuilder { return "PropertyDetails"; } - /** - * Returns a list of properties that will be documented for the given class. - * This information can be used for doclet specific documentation - * generation. - * - * @param typeElement the {@link TypeElement} we want to check. - * @return a list of properties that will be documented. - */ - public SortedSet members(TypeElement typeElement) { - return visibleMemberMap.getMembersFor(typeElement); - } - - /** - * Returns the visible member map for the properties of this class. - * - * @return the visible member map for the properties of this class. - */ - public VisibleMemberMap getVisibleMemberMap() { - return visibleMemberMap; - } - /** * Returns whether or not there are members to document. * @@ -162,17 +141,17 @@ public class PropertyBuilder extends AbstractMemberBuilder { if (writer == null) { return; } - int size = properties.size(); - if (size > 0) { + if (hasMembersToDocument()) { Content propertyDetailsTree = writer.getPropertyDetailsTreeHeader(typeElement, memberDetailsTree); - for (Element e : properties) { - currentProperty = (ExecutableElement) e; + Element lastElement = properties.get(properties.size() - 1); + for (Element property : properties) { + currentProperty = (ExecutableElement)property; Content propertyDocTree = writer.getPropertyDocTreeHeader(currentProperty, propertyDetailsTree); buildChildren(node, propertyDocTree); propertyDetailsTree.addContent(writer.getPropertyDoc( - propertyDocTree, currentProperty == properties.last())); + propertyDocTree, currentProperty == lastElement)); } memberDetailsTree.addContent( writer.getPropertyDetails(propertyDetailsTree)); diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java index e23cf65983a..7ba231bac15 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java @@ -25,7 +25,6 @@ package jdk.javadoc.internal.doclets.toolkit.util; -import java.io.IOException; import java.lang.annotation.Documented; import java.lang.ref.SoftReference; import java.text.CollationKey; @@ -77,9 +76,7 @@ import com.sun.source.util.DocTrees; import com.sun.source.util.TreePath; import jdk.javadoc.internal.doclets.toolkit.CommentUtils.DocCommentDuo; import jdk.javadoc.internal.doclets.toolkit.Configuration; -import jdk.javadoc.internal.doclets.toolkit.DocletException; import jdk.javadoc.internal.doclets.toolkit.Messages; -import jdk.javadoc.internal.doclets.toolkit.Resources; import jdk.javadoc.internal.doclets.toolkit.WorkArounds; import static javax.lang.model.element.ElementKind.*; @@ -258,14 +255,6 @@ public class Utils { return getEnclosingTypeElement(e) == null || isStatic(e); } - public boolean matches(Element e1, Element e2) { - if (isExecutableElement(e1) && isExecutableElement(e1)) { - return executableMembersEqual((ExecutableElement)e1, (ExecutableElement)e2); - } else { - return e1.getSimpleName().equals(e2.getSimpleName()); - } - } - /** * Copy doc-files directory and its contents from the source * package directory to the generated documentation directory. @@ -2161,6 +2150,13 @@ public class Utils { return convertToExecutableElement(getItems(e, false, METHOD)); } + public int getOrdinalValue(VariableElement member) { + if (member == null || member.getKind() != ENUM_CONSTANT) { + throw new IllegalArgumentException("must be an enum constant: " + member); + } + return member.getEnclosingElement().getEnclosedElements().indexOf(member); + } + public long getLineNumber(Element e) { TreePath path = getTreePath(e); if (path == null) { // maybe null if synthesized diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/VisibleMemberMap.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/VisibleMemberMap.java index 6fbae159bf1..08e07514964 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/VisibleMemberMap.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/VisibleMemberMap.java @@ -220,48 +220,36 @@ public class VisibleMemberMap { } /** - * Return the visible members of the class being mapped. Also append at the - * end of the list members that are inherited by inaccessible parents. We - * document these members in the child because the parent is not documented. + * Returns a list of visible enclosed members of the type being mapped. + * This list may also contain appended members, inherited by inaccessible + * super types. These members are documented in the subtype when the + * super type is not documented. * - * @param configuration the current configuration of the doclet. + * @return a list of visible enclosed members */ - public SortedSet getLeafClassMembers() { - SortedSet result = getMembersFor(typeElement); - result.addAll(getInheritedPackagePrivateMethods()); - return result; - } - public Set getLeafClassMembersSourceOrder() { - Set result = new LinkedHashSet<>(classMap.get(typeElement).members); + public List getLeafMembers() { + List result = new ArrayList<>(); + result.addAll(classMap.get(typeElement).members); result.addAll(getInheritedPackagePrivateMethods()); return result; } /** - * Retrn the list of members for the given class. + * Returns a list of enclosed members for the given type. * - * @param typeElement the class to retrieve the list of visible members for. + * @param typeElement the given type * - * @return the list of members for the given class. + * @return a list of enclosed members */ - public SortedSet getMembersFor(TypeElement typeElement) { - return asSortedSet(classMap.get(typeElement).members); + public List getMembers(TypeElement typeElement) { + return classMap.get(typeElement).members; } - public boolean hasMembersFor(TypeElement typeElement) { + public boolean hasMembers(TypeElement typeElement) { return !classMap.get(typeElement).members.isEmpty(); } - private SortedSet asSortedSet(Collection in) { - if (in == null) { - return Collections.emptySortedSet(); - } - TreeSet out = new TreeSet<>(comparator); - out.addAll(in); - return out; - } - private void fillMemberLevelMap(List list, String level) { for (Element element : list) { Object key = getMemberKey(element); @@ -318,9 +306,9 @@ public class VisibleMemberMap { private final TypeElement typeElement; /** - * List of inherited members from the mapping class. + * List of members from the mapping class. */ - private Set members = new LinkedHashSet<>(); + private List members = null; /** * Level/Depth of inheritance. @@ -379,23 +367,23 @@ public class VisibleMemberMap { * Adjust member-level-map, class-map. */ private void addMembers(TypeElement fromClass) { - List classMembers = getClassMembers(fromClass, true); - List incllist = new ArrayList<>(); - for (Element element : classMembers) { - if (!found(members, element)) { - if (memberIsVisible(element)) { - if (!isOverridden(element, level)) { - if (!utils.isHidden(element)) { - incllist.add(element); - } + List result = new ArrayList<>(); + for (Element element : getClassMembers(fromClass, true)) { + if (memberIsVisible(element)) { + if (!isOverridden(element, level)) { + if (!utils.isHidden(element)) { + result.add(element); } } } } - if (!incllist.isEmpty()) { + if (members != null) { + throw new AssertionError("members should not be null"); + } + members = Collections.unmodifiableList(result); + if (!members.isEmpty()) { noVisibleMembers = false; } - members.addAll(incllist); fillMemberLevelMap(getClassMembers(fromClass, false), level); } @@ -513,16 +501,6 @@ public class VisibleMemberMap { return targetMembers; } - private boolean found(Iterable list, Element elem) { - for (Element pgmelem : list) { - if (utils.matches(pgmelem, elem)) { - return true; - } - } - return false; - } - - /** * Is member overridden? The member is overridden if it is found in the * same level hierarchy e.g. member at level "11" overrides member at diff --git a/langtools/test/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java b/langtools/test/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java index cc8af164a63..bb9c951876b 100644 --- a/langtools/test/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java +++ b/langtools/test/jdk/javadoc/doclet/testJavaFX/TestJavaFX.java @@ -23,7 +23,7 @@ /* * @test - * @bug 7112427 8012295 8025633 8026567 8061305 8081854 8150130 8162363 + * @bug 7112427 8012295 8025633 8026567 8061305 8081854 8150130 8162363 8167967 * @summary Test of the JavaFX doclet features. * @author jvalenta * @library ../lib @@ -163,10 +163,7 @@ public class TestJavaFX extends JavadocTester { "pkg2"); checkExit(Exit.OK); checkOutput("pkg2/Test.html", true, - "
  • \n" - + "\n" - + "\n" - + "

    Property Detail

    \n" + "

    Property Detail

    \n" + "\n" + "\n" + "\n" @@ -176,27 +173,27 @@ public class TestJavaFX extends JavadocTester { + "
    public java.lang.Object betaProperty
    \n" + "
  • \n" + "\n" - + "\n" + + "\n" + "\n" + "\n" + "
      \n" + "
    • \n" + + "

      gamma

      \n" + + "
      public final java.util.List<java.lang.String> gammaProperty
      \n" + + "
    • \n" + + "
    \n" + + "\n" + + "\n" + + "\n" + + "
      \n" + + "
    • \n" + "

      delta

      \n" + "
      public final java.util.List<"
                       + "java.util.Set<? super java.lang.Object>> deltaProperty
      \n" + "
    • \n" + "
    \n" - + "\n" - + "\n" - + "\n" - + "
      \n" - + "
    • \n" - + "

      gamma

      \n" - + "
      public final java.util.List<"
      -                + "java.lang.String> gammaProperty
      \n" + "
    • \n" - + "
    \n" - + ""); + + ""); } /* diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/TestOrdering.java b/langtools/test/jdk/javadoc/doclet/testOrdering/TestOrdering.java index 9ffac254c93..19626d84d10 100644 --- a/langtools/test/jdk/javadoc/doclet/testOrdering/TestOrdering.java +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/TestOrdering.java @@ -23,9 +23,8 @@ /* * @test - * @bug 8039410 8042601 8042829 8049393 8050031 8155061 8155995 + * @bug 8039410 8042601 8042829 8049393 8050031 8155061 8155995 8167967 * @summary test to determine if members are ordered correctly - * @author ksrini * @library ../lib/ * @modules jdk.javadoc/jdk.javadoc.internal.tool * @build JavadocTester @@ -51,492 +50,640 @@ public class TestOrdering extends JavadocTester { @Test void testUnnamedPackagesForClassUse() { - javadoc("-d", "out", - "-sourcepath", testSrc, - "-use", - testSrc("C.java"), testSrc("UsedInC.java")); - checkExit(Exit.OK); - checkExecutableMemberOrdering("class-use/UsedInC.html"); + new UnnamedPackageForClassUseTest(this).run(); } @Test void testNamedPackagesForClassUse() { - javadoc("-d", "out-1", - "-sourcepath", testSrc, - "-use", - "pkg1"); - checkExit(Exit.OK); - checkClassUseOrdering("pkg1/class-use/UsedClass.html"); - checkOrder("pkg1/class-use/UsedClass.html", expectedClassUseMethodOrdering); - checkOrder("pkg1/class-use/UsedClass.html", expectedClassUseWithTypeParams); - checkOrder("pkg1/class-use/UsedClass.html", expectedInnerClassContructors); - checkOrder("pkg1/ImplementsOrdering.html", expectedImplementsOrdering); - checkOrder("pkg1/OverrideOrdering.html", expectedOverrideOrdering); - checkOrder("allclasses-noframe.html", expectedAllClasses); - checkOrder("allclasses-frame.html", expectedAllClasses); + new NamedPackagesForClassUseTest(this).run(); } - enum ListOrder { NONE, REVERSE, SHUFFLE }; - /* - * By default we do not shuffle the input list, in order to keep the list deterministic, - * and the test predictable. However, we can turn on the stress mode, by setting the following - * property if required. - */ - static final ListOrder STRESS_MODE = Boolean.getBoolean("TestOrder.STRESS") - ? ListOrder.SHUFFLE - : ListOrder.REVERSE; - - /* - * Controls the number of sibling packages, pkg0, pkg1, pkg2, ..... - */ - static final int MAX_PACKAGES = 4; - - /* - * Controls the number of children packages, pkg0, pkg0.pkg, pkg0.pkg.pkg, ..... - * Note: having too long a depth (> 256 chars on Windows), will likely lead to - * cause problems with automated build and test systems. - */ - static final int MAX_SUBPACKAGES_DEPTH = 4; @Test void testIndexOrdering() throws IOException { - final String clsname = "Add"; - List cmdArgs = new ArrayList(); - cmdArgs.add("-d"); - cmdArgs.add("out-2"); - cmdArgs.add("-sourcepath"); - cmdArgs.add("src"); - cmdArgs.add("-package"); - System.out.println("STRESS_MODE: " + STRESS_MODE); - emitFile(null, clsname, STRESS_MODE); - for (int width = 0 ; width < MAX_PACKAGES ; width++) { - String wpkgname = "add" + width; - String dpkgname = wpkgname; - emitFile(wpkgname, clsname, ListOrder.NONE); // list as-is - cmdArgs.add(wpkgname); - for (int depth = 1 ; depth < MAX_SUBPACKAGES_DEPTH ; depth++) { - dpkgname = dpkgname + ".add"; - emitFile(dpkgname, clsname, STRESS_MODE); - cmdArgs.add(dpkgname); - } - } - File srcDir = new File(new File("."), "src"); - cmdArgs.add(new File(srcDir, clsname + ".java").getPath()); - javadoc(cmdArgs.toArray(new String[cmdArgs.size()])); - checkExit(Exit.OK); - checkOrder("index-all.html", composeTestVectors()); - checkOrder("add0/add/package-tree.html", expectedPackageTreeOrdering); - checkOrder("overview-tree.html", expectedOverviewOrdering); - checkOrder("overview-frame.html", expectedOverviewFrameOrdering); + new IndexOrderingTest(this).run(); } @Test void testIndexTypeClustering() { - javadoc("-d", "out-3", - "-sourcepath", testSrc("src-2"), - "-use", - "a", - "b", - "e", - "something"); - checkOrder("index-all.html", typeTestVectors); - checkExit(Exit.OK); + new IndexTypeClusteringTest(this).run(); } @Test - void testMethodDetailOrdering() { - javadoc("-d", "out-4", - "-sourcepath", testSrc(new File(".").getPath()), - "order" - ); - checkOrder("order/MethodOrder.html", methodSourceOrderVectors); - checkExit(Exit.OK); + void testTypeElementMemberOrdering() { + new TypeElementMemberOrderingTest(this).run(); } - String[] methodSourceOrderVectors = { - "
    public void d()
    \n" + - "
    Method d.\n" + - " Second line.
    ", - "
    public void b()
    \n" + - "
    Method b.\n" + - " Second line.
    ", - "
    public void c()
    \n" + - "
    Method c.\n" + - " Second line.
    ", - "
    public void a()
    \n" + - "
    Method a.\n" + - " Second line.
    " - }; + static class UnnamedPackageForClassUseTest { + final JavadocTester tester; - String[] typeTestVectors = { - "something - package something", - "something - Class in", - "something - Enum in", - "something - Interface in", - "something - Annotation Type in", - "something - Variable in class", - "something() - Constructor", - "something() - Method in class a. - Method in class a. - Method in class something. testList = new ArrayList<>(); - - testList.addAll(Arrays.asList(expectedPackageOrdering)); - for (String x : expectedEnumOrdering) { - testList.add(x.replace("REPLACE_ME", "<Unnamed>")); - for (int i = 0; i < MAX_PACKAGES; i++) { - String wpkg = "add" + i; - testList.add(wpkg + "/" + x.replace("REPLACE_ME", - wpkg)); - String dpkg = wpkg; - for (int j = 1; j < MAX_SUBPACKAGES_DEPTH; j++) { - dpkg = dpkg + "/" + "add"; - testList.add(dpkg + "/" + x.replace("REPLACE_ME", - pathToPackage(dpkg))); - } - } + UnnamedPackageForClassUseTest(JavadocTester tester) { + this.tester = tester; } - testList.addAll(Arrays.asList(expectedFieldOrdering)); - - for (String x : expectedMethodOrdering) { - testList.add(x); - for (int i = 0; i < MAX_PACKAGES; i++) { - String wpkg = "add" + i; - testList.add(wpkg + "/" + x); - String dpkg = wpkg; - for (int j = 1; j < MAX_SUBPACKAGES_DEPTH; j++) { - dpkg = dpkg + "/" + "add"; - testList.add(dpkg + "/" + x); - } - } + void run() { + tester.javadoc("-d", "out", + "-sourcepath", testSrc, + "-use", + tester.testSrc("C.java"), tester.testSrc("UsedInC.java")); + tester.checkExit(Exit.OK); + checkExecutableMemberOrdering("class-use/UsedInC.html"); } - return testList.toArray(new String[testList.size()]); - } - - void checkExecutableMemberOrdering(String usePage) { - String contents = readFile(usePage); - // check constructors - checking("constructors"); - int idx1 = contents.indexOf("C.html#C-UsedInC"); - int idx2 = contents.indexOf("C.html#C-UsedInC-int"); - int idx3 = contents.indexOf("C.html#C-UsedInC-java.lang.String"); - if (idx1 == -1 || idx2 == -1 || idx3 == -1) { - failed("ctor strings not found"); - } else if (idx1 > idx2 || idx2 > idx3 || idx1 > idx3) { - failed("ctor strings are out of order"); - } else - passed("ctor strings are in order"); - - // check methods - checking("methods"); - idx1 = contents.indexOf("C.html#ymethod-int"); - idx2 = contents.indexOf("C.html#ymethod-java.lang.String"); - if (idx1 == -1 || idx2 == -1) { - failed("#ymethod strings not found"); - } else if (idx1 > idx2) { - failed("#ymethod strings are out of order"); - } else - passed("Executable Member Ordering: OK"); - } - - void checkClassUseOrdering(String usePage) { - checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#zfield"); - checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#fieldInC#ITERATION#"); - checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#zmethod-pkg1.UsedClass"); - checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#methodInC#ITERATION#"); - } - - void checkClassUseOrdering(String usePage, String searchString) { - String contents = readFile(usePage); - int lastidx = 0; - System.out.println("testing for " + searchString); - for (int i = 1; i < 5; i++) { - String s = searchString.replaceAll("#ITERATION#", Integer.toString(i)); - checking(s); - int idx = contents.indexOf(s); - if (idx < lastidx) { - failed(s + ", member ordering error, last:" + lastidx + ", got:" + idx); + void checkExecutableMemberOrdering(String usePage) { + String contents = tester.readFile(usePage); + // check constructors + tester.checking("constructors"); + int idx1 = contents.indexOf("C.html#C-UsedInC"); + int idx2 = contents.indexOf("C.html#C-UsedInC-int"); + int idx3 = contents.indexOf("C.html#C-UsedInC-java.lang.String"); + if (idx1 == -1 || idx2 == -1 || idx3 == -1) { + tester.failed("ctor strings not found"); + } else if (idx1 > idx2 || idx2 > idx3 || idx1 > idx3) { + tester.failed("ctor strings are out of order"); } else { - passed("\tlast: " + lastidx + " got:" + idx); + tester.passed("ctor strings are in order"); + } + + // check methods + tester.checking("methods"); + idx1 = contents.indexOf("C.html#ymethod-int"); + idx2 = contents.indexOf("C.html#ymethod-java.lang.String"); + if (idx1 == -1 || idx2 == -1) { + tester.failed("#ymethod strings not found"); + } else if (idx1 > idx2) { + tester.failed("#ymethod strings are out of order"); + } else { + tester.passed("Executable Member Ordering: OK"); } - lastidx = idx; } } - static String[] contents = { - "public add ADDADD;", - "public add AddAdd;", - "public add addadd;", - "public enum add {add, ADD, addd, ADDD};", - "public enum ADD {ADD, add, addd, ADDD};", - "public void add(){}", - "public void add(double d){}", - "public void add(int i, float f){}", - "public void add(float f, int i){}", - "public void add(double d, byte b){}", - "public Double add(Double d) {return (double) 22/7;}", - "public double add(double d1, double d2) {return d1 + d2;}", - "public double add(double d1, Double d2) {return d1 + d2;}", - "public Float add(float f) {return (float) 22/7;}", - "public void add(int i){}", - "public int add(Integer i) {return 0;}" - }; + static class NamedPackagesForClassUseTest { + final JavadocTester tester; - void emitFile(String pkgname, String clsname, ListOrder order) throws IOException { - File srcDir = new File("src"); - File outDir = pkgname == null - ? srcDir - : new File(srcDir, pkgname.replace(".", File.separator)); - File outFile = new File(outDir, clsname + ".java"); - outDir.mkdirs(); - List scratch = new ArrayList<>(Arrays.asList(contents)); - switch (order) { - case SHUFFLE: - Collections.shuffle(scratch); - break; - case REVERSE: - Collections.reverse(scratch); - break; - default: + NamedPackagesForClassUseTest(JavadocTester tester) { + this.tester = tester; + } + + public void run() { + tester.javadoc("-d", "out-1", + "-sourcepath", tester.testSrc, + "-use", + "pkg1"); + tester.checkExit(Exit.OK); + + checkClassUseOrdering("pkg1/class-use/UsedClass.html"); + + tester.checkOrder("pkg1/class-use/UsedClass.html", + "../../pkg1/MethodOrder.html#m--", + "../../pkg1/MethodOrder.html#m-byte:A-", + "../../pkg1/MethodOrder.html#m-double-", + "../../pkg1/MethodOrder.html#m-double-double-", + "../../pkg1/MethodOrder.html#m-double-java.lang.Double-", + "../../pkg1/MethodOrder.html#m-int-", + "../../pkg1/MethodOrder.html#m-int-int-", + "../../pkg1/MethodOrder.html#m-int-java.lang.Integer-", + "../../pkg1/MethodOrder.html#m-long-", + "../../pkg1/MethodOrder.html#m-long-long-", + "../../pkg1/MethodOrder.html#m-long-java.lang.Long-", + "../../pkg1/MethodOrder.html#m-long-java.lang.Long...-", + "../../pkg1/MethodOrder.html#m-java.lang.Double-", + "../../pkg1/MethodOrder.html#m-java.lang.Double-double-", + "../../pkg1/MethodOrder.html#m-java.lang.Double-java.lang.Double-", + "../../pkg1/MethodOrder.html#m-java.lang.Integer-", + "../../pkg1/MethodOrder.html#m-java.lang.Integer-int-", + "../../pkg1/MethodOrder.html#m-java.lang.Integer-java.lang.Integer-", + "../../pkg1/MethodOrder.html#m-java.lang.Object:A-", + "../../pkg1/MethodOrder.html#m-java.util.ArrayList-", + "../../pkg1/MethodOrder.html#m-java.util.Collection-", + "../../pkg1/MethodOrder.html#m-java.util.List-"); + + tester.checkOrder("pkg1/class-use/UsedClass.html", + "../../pkg1/MethodOrder.html#tpm-pkg1.UsedClass-", + "../../pkg1/MethodOrder.html#tpm-pkg1.UsedClass-pkg1.UsedClass-", + "../../pkg1/MethodOrder.html#tpm-pkg1.UsedClass-pkg1.UsedClass:A-", + "../../pkg1/MethodOrder.html#tpm-pkg1.UsedClass-java.lang.String-"); + + tester.checkOrder("pkg1/class-use/UsedClass.html", + "../../pkg1/A.html#A-pkg1.UsedClass-", + "../../pkg1/B.A.html#A-pkg1.UsedClass-", + "../../pkg1/B.html#B-pkg1.UsedClass-", + "../../pkg1/A.C.html#C-pkg1.UsedClass-java.lang.Object:A-", + "../../pkg1/A.C.html#C-pkg1.UsedClass-java.util.Collection-", + "../../pkg1/A.C.html#C-pkg1.UsedClass-java.util.List-"); + + tester.checkOrder("pkg1/ImplementsOrdering.html", + "
    close in interface java.lang.AutoCloseable
    ", + "
    close in interface java.nio.channels.Channel
    ", + "
    close in interface java.io.Closeable
    "); + + tester.checkOrder("pkg1/OverrideOrdering.html", + "
    iterator in interface java.util.Collection<", + "
    iterator in interface java.lang.Iterable<"); + + tester.checkOrder("allclasses-noframe.html", + "pkg1/A.html\" title=\"class in pkg1", + "pkg1/A.C.html\" title=\"class in pkg1", + "pkg1/B.html\" title=\"class in pkg1", + "pkg1/B.A.html\" title=\"class in pkg1", + "pkg1/C1.html\" title=\"class in pkg1", + "pkg1/C2.html\" title=\"class in pkg1", + "pkg1/C3.html\" title=\"class in pkg1", + "pkg1/C4.html\" title=\"class in pkg1", + "pkg1/ImplementsOrdering.html\" title=\"interface in pkg1", + "pkg1/MethodOrder.html\" title=\"class in pkg1", + "pkg1/OverrideOrdering.html\" title=\"class in pkg1", + "pkg1/UsedClass.html\" title=\"class in pkg1"); + + tester.checkOrder("allclasses-frame.html", + "pkg1/A.html\" title=\"class in pkg1", + "pkg1/A.C.html\" title=\"class in pkg1", + "pkg1/B.html\" title=\"class in pkg1", + "pkg1/B.A.html\" title=\"class in pkg1", + "pkg1/C1.html\" title=\"class in pkg1", + "pkg1/C2.html\" title=\"class in pkg1", + "pkg1/C3.html\" title=\"class in pkg1", + "pkg1/C4.html\" title=\"class in pkg1", + "pkg1/ImplementsOrdering.html\" title=\"interface in pkg1", + "pkg1/MethodOrder.html\" title=\"class in pkg1", + "pkg1/OverrideOrdering.html\" title=\"class in pkg1", + "pkg1/UsedClass.html\" title=\"class in pkg1"); + } + + void checkClassUseOrdering(String usePage) { + checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#zfield"); + checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#fieldInC#ITERATION#"); + checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#zmethod-pkg1.UsedClass"); + checkClassUseOrdering(usePage, "pkg1/C#ITERATION#.html#methodInC#ITERATION#"); + } + + void checkClassUseOrdering(String usePage, String searchString) { + String contents = tester.readFile(usePage); + int lastidx = 0; + System.out.println("testing for " + searchString); + for (int i = 1; i < 5; i++) { + String s = searchString.replaceAll("#ITERATION#", Integer.toString(i)); + tester.checking(s); + int idx = contents.indexOf(s); + if (idx < lastidx) { + tester.failed(s + ", member ordering error, last:" + lastidx + ", got:" + idx); + } else { + tester.passed("\tlast: " + lastidx + " got:" + idx); + } + lastidx = idx; + } + } + } + + static class IndexOrderingTest { + private final JavadocTester tester; + + IndexOrderingTest(JavadocTester tester) { + this.tester = tester; + } + + enum ListOrder { + NONE, REVERSE, SHUFFLE + }; + + /* + * By default we do not shuffle the input list, in order to keep the list deterministic, + * and the test predictable. However, we can turn on the stress mode, by setting the following + * property if required. + */ + static final ListOrder STRESS_MODE = Boolean.getBoolean("TestOrder.STRESS") + ? ListOrder.SHUFFLE + : ListOrder.REVERSE; + + /* + * Controls the number of children packages, pkg0, pkg0.pkg, pkg0.pkg.pkg, ..... + * Note: having too long a depth (> 256 chars on Windows), will likely lead to + * cause problems with automated build and test systems. + */ + static final int MAX_SUBPACKAGES_DEPTH = 4; + + /* + * Controls the number of sibling packages, pkg0, pkg1, pkg2, ..... + */ + static final int MAX_PACKAGES = 4; + + static String[] contents = { + "public add ADDADD;", + "public add AddAdd;", + "public add addadd;", + "public enum add {add, ADD, addd, ADDD};", + "public enum ADD {ADD, add, addd, ADDD};", + "public void add(){}", + "public void add(double d){}", + "public void add(int i, float f){}", + "public void add(float f, int i){}", + "public void add(double d, byte b){}", + "public Double add(Double d) {return (double) 22/7;}", + "public double add(double d1, double d2) {return d1 + d2;}", + "public double add(double d1, Double d2) {return d1 + d2;}", + "public Float add(float f) {return (float) 22/7;}", + "public void add(int i){}", + "public int add(Integer i) {return 0;}" + }; + + static String expectedEnumOrdering[] = { + "Add.add.html\" title=\"enum in REPLACE_ME\"", + "Add.ADD.html\" title=\"enum in REPLACE_ME\"" + }; + + static String expectedFieldOrdering[] = { + "Add.html#addadd\"", + "add0/add/add/add/Add.html#addadd\"", + "add0/add/add/Add.html#addadd\"", + "add0/add/Add.html#addadd\"", + "add0/Add.html#addadd\"", + "add1/add/add/add/Add.html#addadd\"", + "add1/add/add/Add.html#addadd\"", + "add1/add/Add.html#addadd\"", + "add1/Add.html#addadd\"", + "add2/add/add/add/Add.html#addadd\"", + "add2/add/add/Add.html#addadd\"", + "add2/add/Add.html#addadd\"", + "add2/Add.html#addadd\"", + "add3/add/add/add/Add.html#addadd\"", + "add3/add/add/Add.html#addadd\"", + "add3/add/Add.html#addadd\"", + "add3/Add.html#addadd\"", + "Add.html#AddAdd\"", + "add0/add/add/add/Add.html#AddAdd\"", + "add0/add/add/Add.html#AddAdd\"", + "add0/add/Add.html#AddAdd\"", + "add0/Add.html#AddAdd\"", + "add1/add/add/add/Add.html#AddAdd\"", + "add1/add/add/Add.html#AddAdd\"", + "add1/add/Add.html#AddAdd\"", + "add1/Add.html#AddAdd\"", + "add2/add/add/add/Add.html#AddAdd\"", + "add2/add/add/Add.html#AddAdd\"", + "add2/add/Add.html#AddAdd\"", + "add2/Add.html#AddAdd\"", + "add3/add/add/add/Add.html#AddAdd\"", + "add3/add/add/Add.html#AddAdd\"", + "add3/add/Add.html#AddAdd\"", + "add3/Add.html#AddAdd\"", + "Add.html#ADDADD\"", + "add0/add/add/add/Add.html#ADDADD\"", + "add0/add/add/Add.html#ADDADD\"", + "add0/add/Add.html#ADDADD\"", + "add0/Add.html#ADDADD\"", + "add1/add/add/add/Add.html#ADDADD\"", + "add1/add/add/Add.html#ADDADD\"", + "add1/add/Add.html#ADDADD\"", + "add1/Add.html#ADDADD\"", + "add2/add/add/add/Add.html#ADDADD\"", + "add2/add/add/Add.html#ADDADD\"", + "add2/add/Add.html#ADDADD\"", + "add2/Add.html#ADDADD\"", + "add3/add/add/add/Add.html#ADDADD\"", + "add3/add/add/Add.html#ADDADD\"", + "add3/add/Add.html#ADDADD\"", + "add3/Add.html#ADDADD\"" + }; + + static String expectedMethodOrdering[] = { + "Add.html#add--", + "Add.html#add-double-", + "Add.html#add-double-byte-", + "Add.html#add-double-double-", + "Add.html#add-double-java.lang.Double-", + "Add.html#add-float-", + "Add.html#add-float-int-", + "Add.html#add-int-", + "Add.html#add-int-float-", + "Add.html#add-java.lang.Double-", + "Add.html#add-java.lang.Integer-" + }; + + static String expectedPackageOrdering[] = { + "\"add0/package-summary.html\">add0 - package add0", + "\"add0/add/package-summary.html\">add0.add - package add0.add", + "\"add0/add/add/package-summary.html\">add0.add.add - package add0.add.add", + "\"add0/add/add/add/package-summary.html\">add0.add.add.add - package add0.add.add.add", + "\"add1/package-summary.html\">add1 - package add1", + "\"add1/add/package-summary.html\">add1.add - package add1.add", + "\"add1/add/add/package-summary.html\">add1.add.add - package add1.add.add", + "\"add1/add/add/add/package-summary.html\">add1.add.add.add - package add1.add.add.add", + "\"add2/package-summary.html\">add2 - package add2", + "\"add2/add/package-summary.html\">add2.add - package add2.add", + "\"add2/add/add/package-summary.html\">add2.add.add - package add2.add.add", + "\"add2/add/add/add/package-summary.html\">add2.add.add.add - package add2.add.add.add", + "\"add3/package-summary.html\">add3 - package add3", + "\"add3/add/package-summary.html\">add3.add - package add3.add", + "\"add3/add/add/package-summary.html\">add3.add.add - package add3.add.add", + "\"add3/add/add/add/package-summary.html\">add3.add.add.add - package add3.add.add.add" + }; + + void run() throws IOException { + final String clsname = "Add"; + List cmdArgs = new ArrayList(); + cmdArgs.add("-d"); + cmdArgs.add("out-2"); + cmdArgs.add("-sourcepath"); + cmdArgs.add("src"); + cmdArgs.add("-package"); + System.out.println("STRESS_MODE: " + STRESS_MODE); + emitFile(null, clsname, STRESS_MODE); + for (int width = 0; width < MAX_PACKAGES; width++) { + String wpkgname = "add" + width; + String dpkgname = wpkgname; + emitFile(wpkgname, clsname, ListOrder.NONE); // list as-is + cmdArgs.add(wpkgname); + for (int depth = 1; depth < MAX_SUBPACKAGES_DEPTH; depth++) { + dpkgname = dpkgname + ".add"; + emitFile(dpkgname, clsname, STRESS_MODE); + cmdArgs.add(dpkgname); + } + } + File srcDir = new File(new File("."), "src"); + cmdArgs.add(new File(srcDir, clsname + ".java").getPath()); + tester.javadoc(cmdArgs.toArray(new String[cmdArgs.size()])); + tester.checkExit(Exit.OK); + tester.checkOrder("index-all.html", composeTestVectors()); + tester.checkOrder("add0/add/package-tree.html", + "", + ""); + tester.checkOrder("overview-tree.html", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ""); + + tester.checkOrder("overview-frame.html", + "<unnamed package>", + "add0", + "add0.add", + "add0.add.add", + "add0.add.add.add", + "add1", + "add1.add", + "add1.add.add", + "add1.add.add.add", + "add2", + "add2.add", + "add2.add.add", + "add2.add.add.add", + "add3", + "add3.add", + "add3.add.add", + "add3.add.add.add"); + } + + void emitFile(String pkgname, String clsname, ListOrder order) throws IOException { + File srcDir = new File("src"); + File outDir = pkgname == null + ? srcDir + : new File(srcDir, pkgname.replace(".", File.separator)); + File outFile = new File(outDir, clsname + ".java"); + outDir.mkdirs(); + List scratch = new ArrayList<>(Arrays.asList(contents)); + switch (order) { + case SHUFFLE: + Collections.shuffle(scratch); + break; + case REVERSE: + Collections.reverse(scratch); + break; + default: // leave list as-is + } + // insert the header + scratch.add(0, "public class " + clsname + " {"); + if (pkgname != null) { + scratch.add(0, "package " + pkgname + ";"); + } + // append the footer + scratch.add("}"); + Files.write(outFile.toPath(), scratch, CREATE, TRUNCATE_EXISTING); } - // insert the header - scratch.add(0, "public class " + clsname + " {"); - if (pkgname != null) { - scratch.add(0, "package " + pkgname + ";"); + + String[] composeTestVectors() { + List testList = new ArrayList<>(); + + testList.addAll(Arrays.asList(expectedPackageOrdering)); + for (String x : expectedEnumOrdering) { + testList.add(x.replace("REPLACE_ME", "<Unnamed>")); + for (int i = 0; i < MAX_PACKAGES; i++) { + String wpkg = "add" + i; + testList.add(wpkg + "/" + x.replace("REPLACE_ME", + wpkg)); + String dpkg = wpkg; + for (int j = 1; j < MAX_SUBPACKAGES_DEPTH; j++) { + dpkg = dpkg + "/" + "add"; + testList.add(dpkg + "/" + x.replace("REPLACE_ME", pathToPackage(dpkg))); + } + } + } + + testList.addAll(Arrays.asList(expectedFieldOrdering)); + + for (String x : expectedMethodOrdering) { + testList.add(x); + for (int i = 0; i < MAX_PACKAGES; i++) { + String wpkg = "add" + i; + testList.add(wpkg + "/" + x); + String dpkg = wpkg; + for (int j = 1; j < MAX_SUBPACKAGES_DEPTH; j++) { + dpkg = dpkg + "/" + "add"; + testList.add(dpkg + "/" + x); + } + } + } + + return testList.toArray(new String[testList.size()]); + } + + String pathToPackage(String in) { + return in.replace("/", "."); } - // append the footer - scratch.add("}"); - Files.write(outFile.toPath(), scratch, CREATE, TRUNCATE_EXISTING); } - String pathToPackage(String in) { - return in.replace("/", "."); + static class IndexTypeClusteringTest { + + private final JavadocTester tester; + + IndexTypeClusteringTest(JavadocTester tester) { + this.tester = tester; + } + + void run() { + tester.javadoc("-d", "out-3", + "-sourcepath", tester.testSrc("src-2"), + "-use", + "a", + "b", + "e", + "something"); + + tester.checkExit(Exit.OK); + + tester.checkOrder("index-all.html", + "something - package something", + "something - Class in", + "something - Enum in", + "something - Interface in", + "something - Annotation Type in", + "something - Variable in class", + "something() - Constructor", + "something() - Method in class a. - Method in class a. - Method in class something.add0 - package add0", - "\"add0/add/package-summary.html\">add0.add - package add0.add", - "\"add0/add/add/package-summary.html\">add0.add.add - package add0.add.add", - "\"add0/add/add/add/package-summary.html\">add0.add.add.add - package add0.add.add.add", - "\"add1/package-summary.html\">add1 - package add1", - "\"add1/add/package-summary.html\">add1.add - package add1.add", - "\"add1/add/add/package-summary.html\">add1.add.add - package add1.add.add", - "\"add1/add/add/add/package-summary.html\">add1.add.add.add - package add1.add.add.add", - "\"add2/package-summary.html\">add2 - package add2", - "\"add2/add/package-summary.html\">add2.add - package add2.add", - "\"add2/add/add/package-summary.html\">add2.add.add - package add2.add.add", - "\"add2/add/add/add/package-summary.html\">add2.add.add.add - package add2.add.add.add", - "\"add3/package-summary.html\">add3 - package add3", - "\"add3/add/package-summary.html\">add3.add - package add3.add", - "\"add3/add/add/package-summary.html\">add3.add.add - package add3.add.add", - "\"add3/add/add/add/package-summary.html\">add3.add.add.add - package add3.add.add.add" - }; + tester.checkOrder("pkg5/AnnoFieldTest.html", + "

    Field Detail

    ", + "
    static final int one
    ", + "
    static final int two
    ", + "
    static final int three
    ", + "
    static final int four
    "); - final String expectedMethodOrdering[] = { - "Add.html#add--", - "Add.html#add-double-", - "Add.html#add-double-byte-", - "Add.html#add-double-double-", - "Add.html#add-double-java.lang.Double-", - "Add.html#add-float-", - "Add.html#add-float-int-", - "Add.html#add-int-", - "Add.html#add-int-float-", - "Add.html#add-java.lang.Double-", - "Add.html#add-java.lang.Integer-" - }; + tester.checkOrder("pkg5/AnnoOptionalTest.html", + "

    Optional Element Summary

    ", + "four", + "one", + "three", + "two", + "

    Element Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

    "); - final String expectedEnumOrdering[] = { - "Add.add.html\" title=\"enum in REPLACE_ME\"", - "Add.ADD.html\" title=\"enum in REPLACE_ME\"" - }; + tester.checkOrder("pkg5/AnnoRequiredTest.html", + "

    Required Element Summary

    ", + "four", + "one", + "three", + "two", + "

    Element Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

    "); - final String expectedFieldOrdering[] = { - "Add.html#addadd\"", - "add0/add/add/add/Add.html#addadd\"", - "add0/add/add/Add.html#addadd\"", - "add0/add/Add.html#addadd\"", - "add0/Add.html#addadd\"", - "add1/add/add/add/Add.html#addadd\"", - "add1/add/add/Add.html#addadd\"", - "add1/add/Add.html#addadd\"", - "add1/Add.html#addadd\"", - "add2/add/add/add/Add.html#addadd\"", - "add2/add/add/Add.html#addadd\"", - "add2/add/Add.html#addadd\"", - "add2/Add.html#addadd\"", - "add3/add/add/add/Add.html#addadd\"", - "add3/add/add/Add.html#addadd\"", - "add3/add/Add.html#addadd\"", - "add3/Add.html#addadd\"", - "Add.html#AddAdd\"", - "add0/add/add/add/Add.html#AddAdd\"", - "add0/add/add/Add.html#AddAdd\"", - "add0/add/Add.html#AddAdd\"", - "add0/Add.html#AddAdd\"", - "add1/add/add/add/Add.html#AddAdd\"", - "add1/add/add/Add.html#AddAdd\"", - "add1/add/Add.html#AddAdd\"", - "add1/Add.html#AddAdd\"", - "add2/add/add/add/Add.html#AddAdd\"", - "add2/add/add/Add.html#AddAdd\"", - "add2/add/Add.html#AddAdd\"", - "add2/Add.html#AddAdd\"", - "add3/add/add/add/Add.html#AddAdd\"", - "add3/add/add/Add.html#AddAdd\"", - "add3/add/Add.html#AddAdd\"", - "add3/Add.html#AddAdd\"", - "Add.html#ADDADD\"", - "add0/add/add/add/Add.html#ADDADD\"", - "add0/add/add/Add.html#ADDADD\"", - "add0/add/Add.html#ADDADD\"", - "add0/Add.html#ADDADD\"", - "add1/add/add/add/Add.html#ADDADD\"", - "add1/add/add/Add.html#ADDADD\"", - "add1/add/Add.html#ADDADD\"", - "add1/Add.html#ADDADD\"", - "add2/add/add/add/Add.html#ADDADD\"", - "add2/add/add/Add.html#ADDADD\"", - "add2/add/Add.html#ADDADD\"", - "add2/Add.html#ADDADD\"", - "add3/add/add/add/Add.html#ADDADD\"", - "add3/add/add/Add.html#ADDADD\"", - "add3/add/Add.html#ADDADD\"", - "add3/Add.html#ADDADD\"" - }; + tester.checkOrder("pkg5/CtorTest.html", + "

    Constructor Summary

    ", + "Constructor Detail", + "", + "", + "", + ""); - final String expectedPackageTreeOrdering[] = { - "", - "" - }; + tester.checkOrder("pkg5/EnumTest.html", + "

    Enum Constant Summary

    ", + "
    FOUR", + "ONE", + "THREE", + "TWO", + "

    Enum Constant Detail

    ", + "

    ONE

    ", + "

    TWO

    ", + "

    THREE

    ", + "

    FOUR

    "); - final String expectedOverviewOrdering[] = { - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - }; + tester.checkOrder("pkg5/FieldTest.html", + "

    Field Summary

    ", + "
    four", + "one", + "three", + "two", + "

    Field Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

    "); - final static String expectedOverviewFrameOrdering[] = { - "<unnamed package>", - "add0", - "add0.add", - "add0.add.add", - "add0.add.add.add", - "add1", - "add1.add", - "add1.add.add", - "add1.add.add.add", - "add2", - "add2.add", - "add2.add.add", - "add2.add.add.add", - "add3", - "add3.add", - "add3.add.add", - "add3.add.add.add" - }; + tester.checkOrder("pkg5/IntfTest.html", + "

    Method Summary

    ", + "four", + "one", + "three", + "two", + "

    Method Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

    "); - final static String expectedImplementsOrdering[] = { - "
    close in interface java.lang.AutoCloseable
    ", - "
    close in interface java.nio.channels.Channel
    ", - "
    close in interface java.io.Closeable
    " - }; + tester.checkOrder("pkg5/MethodTest.html", + "

    Method Summary

    ", + "four", + "one", + "three", + "two", + "

    Method Detail

    ", + "

    one

    ", + "

    two

    ", + "

    three

    ", + "

    four

    "); - final static String expectedOverrideOrdering[] = { - "
    iterator in interface java.util.Collection<", - "
    iterator in interface java.lang.Iterable<" - }; + tester.checkOrder("pkg5/PropertyTest.html", + "

    Property Summary

    ", + "four", + "one", + "three", + "two", + "

    Property Detail

    ", + "

    oneProperty

    ", + "

    twoProperty

    ", + "

    threeProperty

    ", + "

    fourProperty

    "); + } + } } diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/order/MethodOrder.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoFieldTest.java similarity index 63% rename from langtools/test/jdk/javadoc/doclet/testOrdering/order/MethodOrder.java rename to langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoFieldTest.java index d04ceb07c4a..53c0617f3ec 100644 --- a/langtools/test/jdk/javadoc/doclet/testOrdering/order/MethodOrder.java +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoFieldTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,32 +21,11 @@ * questions. */ -package order; +package pkg5; -/** - * This class ensures the method detail section contains the methods - * in the order as it appears in the source. - * @author kumasrin - */ -public class MethodOrder { - /** - * Method d. - * Second line. - */ - public void d(){} - /** - * Method b. - * Second line. - */ - public void b() {} - /** - * Method c. - * Second line. - */ - public void c() {} - /** - * Method a. - * Second line. - */ - public void a() {} +public @interface AnnoFieldTest { + public int one = 1; + public int two = 2; + public int three = 3; + public int four = 4; } diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoOptionalTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoOptionalTest.java new file mode 100644 index 00000000000..aba053a0476 --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoOptionalTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public @interface AnnoOptionalTest { + int one() default 1; + int two() default 2; + int three() default 3; + int four() default 4; +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoRequiredTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoRequiredTest.java new file mode 100644 index 00000000000..f54a0e4af14 --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/AnnoRequiredTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public @interface AnnoRequiredTest { + int one(); + int two(); + int three(); + int four(); +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/CtorTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/CtorTest.java new file mode 100644 index 00000000000..60bd64a49e8 --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/CtorTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public class CtorTest { + public CtorTest(int one, int two, int three, int four) {} + public CtorTest(int one, int two, int three) {} + public CtorTest(int one, int two) {} + public CtorTest(int one) {} +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/EnumTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/EnumTest.java new file mode 100644 index 00000000000..ef1267f00a5 --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/EnumTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public enum EnumTest { + ONE, + TWO, + THREE, + FOUR +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/FieldTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/FieldTest.java new file mode 100644 index 00000000000..66f876e0a85 --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/FieldTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public class FieldTest { + public int one; + public int two; + public int three; + public int four; +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/IntfTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/IntfTest.java new file mode 100644 index 00000000000..959034ed16b --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/IntfTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public interface IntfTest { + void one(); + void two(); + void three(); + void four(); +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/MethodTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/MethodTest.java new file mode 100644 index 00000000000..9333b30c00d --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/MethodTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public class MethodTest { + public void one(){} + public void two(){} + public void three(){} + public void four(){} +} diff --git a/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/PropertyTest.java b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/PropertyTest.java new file mode 100644 index 00000000000..b53752a1e1a --- /dev/null +++ b/langtools/test/jdk/javadoc/doclet/testOrdering/pkg5/PropertyTest.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package pkg5; + +public class PropertyTest { + public int oneProperty() { return 1; } + public int twoProperty() { return 2; } + public int threeProperty() { return 3; } + public int fourProperty() { return 4; } +} From d867ed9a8def5e02602c2aec5e097b04e73e9663 Mon Sep 17 00:00:00 2001 From: Srinivas Dama Date: Mon, 14 Nov 2016 22:33:33 -0800 Subject: [PATCH 121/402] 8156615: Catch parameter can be a BindingPattern in ES6 mode Added parser support for catch parameter being a binding pattern Reviewed-by: sundar, hannesw, attila --- .../jdk/nashorn/api/tree/IRTranslator.java | 2 +- .../internal/codegen/AssignSymbols.java | 2 +- .../internal/codegen/CodeGenerator.java | 2 +- .../codegen/LocalVariableTypesCalculator.java | 2 +- .../jdk/nashorn/internal/codegen/Lower.java | 9 + .../jdk/nashorn/internal/ir/CatchNode.java | 54 ++- .../jdk/nashorn/internal/parser/Parser.java | 20 +- .../test/script/basic/es6/destructuring.js | 7 + .../basic/es6/destructuring.js.EXPECTED | 21 + .../nosecurity/treeapi/destructuring_catch.js | 51 +++ .../treeapi/destructuring_catch.js.EXPECTED | 399 ++++++++++++++++++ 11 files changed, 544 insertions(+), 25 deletions(-) create mode 100644 nashorn/test/script/nosecurity/treeapi/destructuring_catch.js create mode 100644 nashorn/test/script/nosecurity/treeapi/destructuring_catch.js.EXPECTED diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java index 974f56c7ccc..041ab612c34 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/tree/IRTranslator.java @@ -384,7 +384,7 @@ final class IRTranslator extends SimpleNodeVisitor { final List catchTrees = new ArrayList<>(catchNodes.size()); for (final CatchNode catchNode : catchNodes) { catchTrees.add(new CatchTreeImpl(catchNode, - translateIdent(catchNode.getException()), + translateExpr(catchNode.getException()), (BlockTree) translateBlock(catchNode.getBody()), translateExpr(catchNode.getExceptionCondition()))); } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java index fdc828b50b1..3bb44b5aa13 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java @@ -462,7 +462,7 @@ final class AssignSymbols extends SimpleNodeVisitor implements Loggable { @Override public boolean enterCatchNode(final CatchNode catchNode) { - final IdentNode exception = catchNode.getException(); + final IdentNode exception = catchNode.getExceptionIdentifier(); final Block block = lc.getCurrentBlock(); start(catchNode); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java index f04f8959339..c4053bcf1e6 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -3255,7 +3255,7 @@ final class CodeGenerator extends NodeOperatorVisitor implements Lo return checkEval(callNode.setFunction(markerFunction(callNode.getFunction()))); } + @Override + public boolean enterCatchNode(final CatchNode catchNode) { + Expression exception = catchNode.getException(); + if ((exception != null) && !(exception instanceof IdentNode)) { + throwNotImplementedYet("es6.destructuring", exception); + } + return true; + } + @Override public Node leaveCatchNode(final CatchNode catchNode) { return addStatement(catchNode); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CatchNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CatchNode.java index 80ca3a509c9..9431f3b3acb 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CatchNode.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CatchNode.java @@ -35,8 +35,8 @@ import jdk.nashorn.internal.ir.visitor.NodeVisitor; public final class CatchNode extends Statement { private static final long serialVersionUID = 1L; - /** Exception identifier. */ - private final IdentNode exception; + /** Exception binding identifier or binding pattern. */ + private final Expression exception; /** Exception condition. */ private final Expression exceptionCondition; @@ -52,21 +52,27 @@ public final class CatchNode extends Statement { * @param lineNumber lineNumber * @param token token * @param finish finish - * @param exception variable name of exception + * @param exception variable name or pattern of exception * @param exceptionCondition exception condition * @param body catch body * @param isSyntheticRethrow true if this node is a synthetically generated rethrow node. */ - public CatchNode(final int lineNumber, final long token, final int finish, final IdentNode exception, + public CatchNode(final int lineNumber, final long token, final int finish, final Expression exception, final Expression exceptionCondition, final Block body, final boolean isSyntheticRethrow) { super(lineNumber, token, finish); - this.exception = exception == null ? null : exception.setIsInitializedHere(); + if (exception instanceof IdentNode) { + this.exception = ((IdentNode) exception).setIsInitializedHere(); + } else if ((exception instanceof LiteralNode.ArrayLiteralNode) || (exception instanceof ObjectNode)) { + this.exception = exception; + } else { + throw new IllegalArgumentException("invalid catch parameter"); + } this.exceptionCondition = exceptionCondition; - this.body = body; + this.body = body; this.isSyntheticRethrow = isSyntheticRethrow; } - private CatchNode(final CatchNode catchNode, final IdentNode exception, final Expression exceptionCondition, + private CatchNode(final CatchNode catchNode, final Expression exception, final Expression exceptionCondition, final Block body, final boolean isSyntheticRethrow) { super(catchNode); this.exception = exception; @@ -83,11 +89,10 @@ public final class CatchNode extends Statement { public Node accept(final NodeVisitor visitor) { if (visitor.enterCatchNode(this)) { return visitor.leaveCatchNode( - setException((IdentNode)exception.accept(visitor)). - setExceptionCondition(exceptionCondition == null ? null : (Expression)exceptionCondition.accept(visitor)). - setBody((Block)body.accept(visitor))); + setException((Expression) exception.accept(visitor)). + setExceptionCondition(exceptionCondition == null ? null : (Expression) exceptionCondition.accept(visitor)). + setBody((Block) body.accept(visitor))); } - return this; } @@ -109,13 +114,24 @@ public final class CatchNode extends Statement { } /** - * Get the identifier representing the exception thrown - * @return the exception identifier + * Get the binding pattern representing the exception thrown + * + * @return the exception binding pattern */ - public IdentNode getException() { + public Expression getException() { return exception; } + /** + * Get the identifier representing the exception thrown + * + * @return the exception identifier + * @throws ClassCastException if exception set is not binding identifier + */ + public IdentNode getExceptionIdentifier() { + return (IdentNode) exception; + } + /** * Get the exception condition for this catch block * @return the exception condition @@ -146,13 +162,19 @@ public final class CatchNode extends Statement { /** * Resets the exception of a catch block - * @param exception new exception + * + * @param exception new exception which can be binding identifier or binding + * pattern * @return new catch node if changed, same otherwise */ - public CatchNode setException(final IdentNode exception) { + public CatchNode setException(final Expression exception) { if (this.exception == exception) { return this; } + /*check if exception is legitimate*/ + if (!((exception instanceof IdentNode) || (exception instanceof LiteralNode.ArrayLiteralNode) || (exception instanceof ObjectNode))) { + throw new IllegalArgumentException("invalid catch parameter"); + } return new CatchNode(this, exception, exceptionCondition, body, isSyntheticRethrow); } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java index c609a0d18c7..fb4fd433b42 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java @@ -2619,13 +2619,23 @@ public class Parser extends AbstractParser implements Loggable { next(); expect(LPAREN); - // FIXME: ES6 catch parameter can be a BindingIdentifier or a BindingPattern - // We need to generalize this here! + // ES6 catch parameter can be a BindingIdentifier or a BindingPattern // http://www.ecma-international.org/ecma-262/6.0/ - final IdentNode exception = getIdent(); + final String contextString = "catch argument"; + final Expression exception = bindingIdentifierOrPattern(contextString); + final boolean isDestructuring = !(exception instanceof IdentNode); + if (isDestructuring) { + verifyDestructuringBindingPattern(exception, new Consumer() { + @Override + public void accept(final IdentNode identNode) { + verifyIdent(identNode, contextString); + } + }); + } else { + // ECMA 12.4.1 strict mode restrictions + verifyStrictIdent((IdentNode) exception, "catch argument"); + } - // ECMA 12.4.1 strict mode restrictions - verifyStrictIdent(exception, "catch argument"); // Nashorn extension: catch clause can have optional // condition. So, a single try can have more than one diff --git a/nashorn/test/script/basic/es6/destructuring.js b/nashorn/test/script/basic/es6/destructuring.js index a7f7a59de04..d2b2a1bd31e 100644 --- a/nashorn/test/script/basic/es6/destructuring.js +++ b/nashorn/test/script/basic/es6/destructuring.js @@ -62,4 +62,11 @@ check("(function({ x }) { return x; })()"); check("(function([x]) { return x; })()"); check("for (var [[x, y, z] = [4, 5, 6]] = [7, 8, 9]; iterCount < 1; ) ;"); check("for ([ arrow = () => {} ] of [[]]) ;"); +check("try { throw null;} catch({}) { }"); +check("try { throw {} } catch ({}) { }"); +check("try { throw [] } catch ([,]) { }"); +check("try { throw { w: [7, undefined, ] }} catch ({ w: [x, y, z] = [4, 5, 6] }) { }"); +check("try { throw { a: 2, b: 3} } catch ({a, b}) { }"); +check("try { throw [null] } catch ([[x]]) { }"); +check("try { throw { w: undefined } } catch ({ w: { x, y, z } = { x: 4, y: 5, z: 6 } }) { }"); diff --git a/nashorn/test/script/basic/es6/destructuring.js.EXPECTED b/nashorn/test/script/basic/es6/destructuring.js.EXPECTED index 65e2eda1dc9..54ecd96a3fa 100644 --- a/nashorn/test/script/basic/es6/destructuring.js.EXPECTED +++ b/nashorn/test/script/basic/es6/destructuring.js.EXPECTED @@ -70,3 +70,24 @@ for (var [[x, y, z] = [4, 5, 6]] = [7, 8, 9]; iterCount < 1; ) ; java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:0 ES6 destructuring is not yet implemented for ([ arrow = () => {} ] of [[]]) ; ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:25 ES6 destructuring is not yet implemented +try { throw null;} catch({}) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:24 ES6 destructuring is not yet implemented +try { throw {} } catch ({}) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:24 ES6 destructuring is not yet implemented +try { throw [] } catch ([,]) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:44 ES6 destructuring is not yet implemented +try { throw { w: [7, undefined, ] }} catch ({ w: [x, y, z] = [4, 5, 6] }) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:35 ES6 destructuring is not yet implemented +try { throw { a: 2, b: 3} } catch ({a, b}) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:28 ES6 destructuring is not yet implemented +try { throw [null] } catch ([[x]]) { } + ^ +java.lang.RuntimeException: test/script/basic/es6/destructuring.js#35:6:1:38 ES6 destructuring is not yet implemented +try { throw { w: undefined } } catch ({ w: { x, y, z } = { x: 4, y: 5, z: 6 } }) { } + ^ diff --git a/nashorn/test/script/nosecurity/treeapi/destructuring_catch.js b/nashorn/test/script/nosecurity/treeapi/destructuring_catch.js new file mode 100644 index 00000000000..ff399fee444 --- /dev/null +++ b/nashorn/test/script/nosecurity/treeapi/destructuring_catch.js @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Tests to check representation of ES6 catch parameter as binding pattern. + * + * @test + * @option -scripting + * @run + */ + +load(__DIR__ + "utils.js") + +var code = < Date: Tue, 15 Nov 2016 12:52:24 +0530 Subject: [PATCH 122/402] 6334602: Animated GIFs created from opaque PNG image frames appear transparent when loaded with Toolkit APIs Reviewed-by: serb, prr --- .../sun/awt/image/GifImageDecoder.java | 10 +- .../java/awt/image/OpaquePNGToGIFTest.java | 422 ++++++++++++++++++ jdk/test/java/awt/image/opaque_input.png | Bin 0 -> 775 bytes 3 files changed, 423 insertions(+), 9 deletions(-) create mode 100644 jdk/test/java/awt/image/OpaquePNGToGIFTest.java create mode 100644 jdk/test/java/awt/image/opaque_input.png diff --git a/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java b/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java index 12f6cfa64b5..fa4612f1848 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,6 @@ */ package sun.awt.image; -import java.util.Vector; import java.util.Hashtable; import java.io.InputStream; import java.io.IOException; @@ -620,7 +619,6 @@ public class GifImageDecoder extends ImageDecoder { class GifFrame { private static final boolean verbose = false; - private static IndexColorModel trans_model; static final int DISPOSAL_NONE = 0x00; static final int DISPOSAL_SAVE = 0x01; @@ -718,12 +716,6 @@ class GifFrame { case DISPOSAL_BGCOLOR: byte tpix; if (model.getTransparentPixel() < 0) { - model = trans_model; - if (model == null) { - model = new IndexColorModel(8, 1, - new byte[4], 0, true); - trans_model = model; - } tpix = 0; } else { tpix = (byte) model.getTransparentPixel(); diff --git a/jdk/test/java/awt/image/OpaquePNGToGIFTest.java b/jdk/test/java/awt/image/OpaquePNGToGIFTest.java new file mode 100644 index 00000000000..ce22df97e36 --- /dev/null +++ b/jdk/test/java/awt/image/OpaquePNGToGIFTest.java @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + /* + * @test + * @bug 6334602 + * @summary Test verifies that when we create GIF image from Opaque PNG images + * it should not be transparent. + * @modules java.desktop/com.sun.imageio.plugins.gif + * @run main/manual OpaquePNGToGIFTest + */ + +import java.awt.image.BufferedImage; +import com.sun.imageio.plugins.gif.GIFImageMetadata; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public final class OpaquePNGToGIFTest extends Frame { + + Image img = null; + private Dimension prefImgSize = new Dimension(100, 100); + private Color canvasColor = new Color(0, 255, 0); + File outputFile = null; + ImageCanvas imageCanvas = new ImageCanvas(); + FileOutputStream fos; + private static GridBagLayout layout; + private static JPanel mainControlPanel; + private static JPanel resultButtonPanel; + private static JPanel canvasPanel; + private static JLabel instructionText; + private static JButton startTestButton; + private static JButton passButton; + private static JButton failButton; + private static JDialog dialog; + private static Frame instructionFrame; + private static Frame imageFrame; + Toolkit tk; + ImageWriter writer = null; + boolean testPassed, testGeneratedInterrupt, startButtonClicked; + private static Thread mainThread; + + public OpaquePNGToGIFTest() throws Exception { + SwingUtilities.invokeAndWait(() -> { + try { + startTest(); + } catch (Exception ex) { + Logger.getLogger(OpaquePNGToGIFTest.class.getName()). + log(Level.SEVERE, null, ex); + } + }); + mainThread = Thread.currentThread(); + try { + Thread.sleep(60000); + } catch (InterruptedException e) { + if (!testPassed && testGeneratedInterrupt) { + throw new RuntimeException("Test failed or didnt run" + + " properly"); + } + } + if (!testGeneratedInterrupt) { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (startButtonClicked) { + imageFrame.dispose(); + } + fos.close(); + Files.delete(outputFile.toPath()); + throw new RuntimeException("user has not executed the test"); + } + } + + public void startTest() throws Exception { + instructionFrame = new Frame(); + dialog = new JDialog(instructionFrame); + dialog.setTitle("Instruction Dialog"); + layout = new GridBagLayout(); + mainControlPanel = new JPanel(layout); + resultButtonPanel = new JPanel(layout); + canvasPanel = new JPanel(); + GridBagConstraints gbc = new GridBagConstraints(); + String instructions + = " INSTRUCTIONS:

    " + + "After clicking on Start Test button you will see Red
    " + + " circle drawn with light blue background, if the circle
    " + + " color changes from Red to Green then press button Fail,
    " + + " if it stays Red then press button Pass.

    "; + instructionText = new JLabel(); + instructionText.setText(instructions); + + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(instructionText, gbc); + startTestButton = new JButton("Start Test"); + startTestButton.setActionCommand("Start Test"); + startTestButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + startButtonClicked = true; + imageFrame = new Frame(); + + Iterator it = ImageIO.getImageWritersByFormatName("GIF"); + while (it.hasNext()) { + writer = (ImageWriter) it.next(); + break; + } + // read input opaque PNG image. + String fileName = "opaque_input.png"; + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + System.out.println(dir + " " + sep); + String filePath = dir + sep + fileName; + File inputFile = new File(filePath); + ImageInputStream iis = ImageIO. + createImageInputStream(inputFile); + ImageReader reader = null; + Iterator readerIter = ImageIO.getImageReaders(iis); + while (readerIter.hasNext()) { + reader = (ImageReader) readerIter.next(); + break; + } + + reader.setInput(iis); + IIOMetadata imgData = reader.getImageMetadata(0); + BufferedImage bi = reader.read(0); + + //create temporary GIF imageas output + File directory = new File(dir + sep); + outputFile = File.createTempFile("output", + ".gif", directory); + createAnimatedImage(bi, imgData, + writer, outputFile); + writer.dispose(); + iis.close(); + if (outputFile == null) { + throw new RuntimeException("Unable to create output GIF" + + " file"); + } + // extract GIF image using Toolkit and show it on a Panel. + tk = Toolkit.getDefaultToolkit(); + img = tk.getImage(dir + sep + outputFile.getName()); + directory.delete(); + imageCanvas.setBackground(canvasColor); + imageCanvas.setImage(img); + imageCanvas.setPreferredSize(prefImgSize); + canvasPanel.doLayout(); + + canvasPanel.add(imageCanvas); + imageFrame.add("Center", canvasPanel); + imageFrame.setSize(200, 200); + imageFrame.setVisible(true); + imageFrame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + try { + img.flush(); + instructionFrame.dispose(); + imageFrame.dispose(); + fail(); + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, + ex); + } + } + } + }); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class.getName()). + log(Level.SEVERE, null, ex); + } + } + }); + passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + pass(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + fail(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + gbc.gridx = 1; + gbc.gridy = 0; + resultButtonPanel.add(startTestButton, gbc); + gbc.gridx = 2; + gbc.gridy = 0; + resultButtonPanel.add(passButton, gbc); + gbc.gridx = 3; + gbc.gridy = 0; + resultButtonPanel.add(failButton, gbc); + + gbc.gridx = 0; + gbc.gridy = 1; + mainControlPanel.add(resultButtonPanel, gbc); + + dialog.add(mainControlPanel); + dialog.setSize(400, 200); + dialog.setLocationRelativeTo(null); + dialog.setVisible(true); + + dialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + fail(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + } + + public synchronized void pass() { + testPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public synchronized void fail() { + testPassed = false; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public void createAnimatedImage(BufferedImage bi, IIOMetadata metadata, + ImageWriter writer, File outputFile) { + try { + + fos = new FileOutputStream(outputFile); + ImageOutputStream ios = ImageIO.createImageOutputStream(fos); + System.out.println(ios); + writer.setOutput(ios); + + ImageWriteParam param = writer.getDefaultWriteParam(); + IIOMetadata streamData = writer.getDefaultStreamMetadata(param); + + writer.prepareWriteSequence(streamData); + ImageTypeSpecifier specify = new ImageTypeSpecifier(bi); + IIOMetadata imgData = writer.convertImageMetadata( + (IIOMetadata) metadata, specify, param); + GIFImageMetadata gifData = setAnimationProperties(imgData); + IIOImage iim = new IIOImage(bi, null, gifData); + param.setProgressiveMode(param.MODE_DISABLED); + writer.writeToSequence(iim, param); + writer.endWriteSequence(); + ios.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public GIFImageMetadata setAnimationProperties(IIOMetadata data) { + ArrayList appIDs = new ArrayList(); + appIDs.add(new String("NETSCAPE").getBytes()); + ArrayList authCodes = new ArrayList(); + authCodes.add(new String("2.0").getBytes()); + ArrayList appData = new ArrayList(); + byte[] authData = {1, 0, 0}; + appData.add(authData); + + GIFImageMetadata gifData = (GIFImageMetadata) data; + gifData.delayTime = 200; + // If we set disposalMethod to 2 then only the issue is reproduced. + gifData.disposalMethod = 2; + gifData.userInputFlag = false; + + gifData.applicationIDs = appIDs; + gifData.authenticationCodes = authCodes; + gifData.applicationData = appData; + + return gifData; + } + + public static void main(String args[]) throws Exception { + OpaquePNGToGIFTest test = new OpaquePNGToGIFTest(); + } + + class ImageCanvas extends Canvas { + + Image im = null; + + public void setImage(Image img) { + im = img; + } + + public void clearImage() { + im = null; + repaint(); + } + + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + + if (im != null) { + g2d.drawImage(im, 1, 1, getWidth(), getHeight(), this); + } + } + } +} + diff --git a/jdk/test/java/awt/image/opaque_input.png b/jdk/test/java/awt/image/opaque_input.png new file mode 100644 index 0000000000000000000000000000000000000000..54eba5724f9c325871c2546f2aa9358261201262 GIT binary patch literal 775 zcmeAS@N?(olHy`uVBq!ia0vp^T|nH)!2~303eD#NDVB6cUq=Rpjs4tz5?L7-nD%+P zIEGZjy}kR^Puh`(^}>f|dn!4coNC$%9!uVw9sF^*(A=+azbh_rt@JZd2{;y@;WYCpcG8I=(jUcRtY zy@Q191MhDA%fjUuFJJrG@7ZDd-_*o*-_@_zw?B7tTOI#K;`#cl^VL>$6JE`8jJ!9m zy6bcL*5`?K5z^m2vAkG#y#K&*NUS|wU2~@q5lhDJR%z(ZkgIy(DZHS4UP;-h@Si)F zUoLE)XTk^+OHaQO8W?AQh{P%DKNYfHg2(x}9jh1ZNvL|UP~EpduIkcF&G@H}`IfW; znLs<$=gut*cda~#uq=4rspGO9h!pgAUDu~3gk{TXruJJ;n0Kuzj=^!Ggh_?huVcWJ O&EV Date: Tue, 15 Nov 2016 10:00:00 +0100 Subject: [PATCH 123/402] 8169632: Update compare script for clean compare Reviewed-by: tbell --- common/bin/compare.sh | 75 +++++---------------------- common/bin/compare_exceptions.sh.incl | 2 + 2 files changed, 14 insertions(+), 63 deletions(-) diff --git a/common/bin/compare.sh b/common/bin/compare.sh index 21c9051e426..ba60485ea53 100644 --- a/common/bin/compare.sh +++ b/common/bin/compare.sh @@ -372,7 +372,7 @@ compare_general_files() { $CAT $OTHER_DIR/$f | eval "$HTML_FILTER" > $OTHER_FILE & $CAT $THIS_DIR/$f | eval "$HTML_FILTER" > $THIS_FILE & wait - elif [ "$f" = "./lib/classlist" ]; then + elif [[ "$f" = *"/lib/classlist" ]]; then # The classlist files may have some lines in random order OTHER_FILE=$WORK_DIR/$f.other THIS_FILE=$WORK_DIR/$f.this @@ -642,69 +642,18 @@ compare_bin_file() { if [ "$OPENJDK_TARGET_OS" = "windows" ]; then unset _NT_SYMBOL_PATH - # On windows we need to unzip the debug symbols, if present - OTHER_FILE_BASE=${OTHER_FILE/.dll/} - OTHER_FILE_BASE=${OTHER_FILE_BASE/.exe/} - OTHER_FILE_BASE=${OTHER_FILE_BASE/.cpl/} - DIZ_NAME=$(basename $OTHER_FILE_BASE).diz - # Some .exe files have the same name as a .dll file. Make sure the exe - # files get the right debug symbols. - if [ "$NAME" = "java.exe" ] \ - && [ -f "$OTHER/support/native/java.base/java_objs/java.diz" ]; then - OTHER_DIZ_FILE="$OTHER/support/native/java.base/java_objs/java.diz" - elif [ "$NAME" = "jimage.exe" ] \ - && [ -f "$OTHER/support/native/jdk.jlink/jimage_objs/jimage.diz" ]; then - OTHER_DIZ_FILE="$OTHER/support/modules_cmds/jdk.jlink/jimage.diz" - elif [ "$NAME" = "javacpl.exe" ] \ - && [ -f "$OTHER/support/native/jdk.plugin/javacpl/javacpl.diz" ]; then - OTHER_DIZ_FILE="$OTHER/support/modules_cmds/jdk.deploy.controlpanel/javacpl.diz" - elif [ -f "${OTHER_FILE_BASE}.diz" ]; then - OTHER_DIZ_FILE=${OTHER_FILE_BASE}.diz - else - # Some files, jli.dll, appears twice in the image but only one of - # them has a diz file next to it. - OTHER_DIZ_FILE="$($FIND $OTHER_DIR -name $DIZ_NAME | $SED 1q)" - if [ ! -f "$OTHER_DIZ_FILE" ]; then - # As a last resort, look for diz file in the whole build output - # dir. - OTHER_DIZ_FILE="$($FIND $OTHER -name $DIZ_NAME | $SED 1q)" - fi - fi - if [ -n "$OTHER_DIZ_FILE" ]; then - $MKDIR -p $FILE_WORK_DIR/other - (cd $FILE_WORK_DIR/other ; $UNARCHIVE -o $OTHER_DIZ_FILE) - export _NT_SYMBOL_PATH="$FILE_WORK_DIR/other" - fi - - THIS_FILE_BASE=${THIS_FILE/.dll/} - THIS_FILE_BASE=${THIS_FILE_BASE/.exe/} - THIS_FILE_BASE=${THIS_FILE_BASE/.cpl/} - # Some .exe files have the same name as a .dll file. Make sure the exe - # files get the right debug symbols. - if [ "$NAME" = "java.exe" ] \ - && [ -f "$THIS/support/native/java.base/java_objs/java.diz" ]; then - THIS_DIZ_FILE="$THIS/support/native/java.base/java_objs/java.diz" - elif [ "$NAME" = "jimage.exe" ] \ - && [ -f "$THIS/support/native/jdk.jlink/jimage_objs/jimage.diz" ]; then - THIS_DIZ_FILE="$THIS/support/modules_cmds/jdk.jlink/jimage.diz" - elif [ "$NAME" = "javacpl.exe" ] \ - && [ -f "$THIS/support/native/jdk.plugin/javacpl/javacpl.diz" ]; then - THIS_DIZ_FILE="$THIS/support/modules_cmds/jdk.deploy.controlpanel/javacpl.diz" - elif [ -f "${THIS_FILE_BASE}.diz" ]; then - THIS_DIZ_FILE=${THIS_FILE/.dll/}.diz - else - THIS_DIZ_FILE="$($FIND $THIS_DIR -name $DIZ_NAME | $SED 1q)" - if [ ! -f "$THIS_DIZ_FILE" ]; then - # As a last resort, look for diz file in the whole build output - # dir. - THIS_DIZ_FILE="$($FIND $THIS -name $DIZ_NAME | $SED 1q)" - fi - fi - if [ -n "$THIS_DIZ_FILE" ]; then - $MKDIR -p $FILE_WORK_DIR/this - (cd $FILE_WORK_DIR/this ; $UNARCHIVE -o $THIS_DIZ_FILE) - export _NT_SYMBOL_PATH="$_NT_SYMBOL_PATH;$FILE_WORK_DIR/this" + if [ "$(uname -o)" = "Cygwin" ]; then + THIS=$(cygpath -msa $THIS) + OTHER=$(cygpath -msa $OTHER) fi + # Build an _NT_SYMBOL_PATH that contains all known locations for + # pdb files. + PDB_DIRS="$(ls -d \ + {$OTHER,$THIS}/support/modules_{cmds,libs}/{*,*/*} \ + {$OTHER,$THIS}/support/demos/image/jvmti/*/lib \ + {$OTHER,$THIS}/support/native/java.base/java_objs \ + )" + export _NT_SYMBOL_PATH="$(echo $PDB_DIRS | tr ' ' ';')" fi if [ -z "$SKIP_BIN_DIFF" ]; then diff --git a/common/bin/compare_exceptions.sh.incl b/common/bin/compare_exceptions.sh.incl index a4c4278299a..5042cdcc104 100644 --- a/common/bin/compare_exceptions.sh.incl +++ b/common/bin/compare_exceptions.sh.incl @@ -431,6 +431,8 @@ if [ "$OPENJDK_TARGET_OS" = "windows" ]; then ACCEPTED_JARZIP_CONTENTS=" /modules_libs/java.security.jgss/w2k_lsa_auth.diz + /modules_libs/java.security.jgss/w2k_lsa_auth.pdb + /modules_libs/java.security.jgss/w2k_lsa_auth.map /modules_libs/java.security.jgss/w2k_lsa_auth.dll " From 8d64cef95c113d9f85a6c31c92221fb5a37d4d01 Mon Sep 17 00:00:00 2001 From: Jim Laskey Date: Tue, 15 Nov 2016 10:53:32 -0400 Subject: [PATCH 124/402] 8169720: jimage help message for --include option should be corrected Reviewed-by: alanb, sundar --- .../classes/jdk/tools/jimage/resources/jimage.properties | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties index 24bffe3e1a5..2b53cf8d64f 100644 --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties @@ -71,9 +71,7 @@ main.opt.footer=\ \ separated list of elements each using one the following forms:\n\ \ \n\ \ glob:\n\ -\ regex:\n\ -\ @ where filename is the name of a file containing patterns to be\ -\ used, one pattern per line\n\ +\ regex: main.opt.full-version=\ From 3630a6a4f815f7d8d9e7e02266a2aabc1a9174e9 Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Tue, 15 Nov 2016 08:40:36 -0800 Subject: [PATCH 125/402] 8168500: (se) EPollArrayWrapper optimization for update events should be robust to dynamic changes in file descriptor resource limits Make eventsHigh final and always initialize it to an empty Map. Reviewed-by: alanb --- .../linux/classes/sun/nio/ch/EPollArrayWrapper.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/jdk/src/java.base/linux/classes/sun/nio/ch/EPollArrayWrapper.java b/jdk/src/java.base/linux/classes/sun/nio/ch/EPollArrayWrapper.java index e6a2b584d96..f34274eed99 100644 --- a/jdk/src/java.base/linux/classes/sun/nio/ch/EPollArrayWrapper.java +++ b/jdk/src/java.base/linux/classes/sun/nio/ch/EPollArrayWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -118,7 +118,7 @@ class EPollArrayWrapper { // file descriptors higher than MAX_UPDATE_ARRAY_SIZE (unlimited case at // least) then the update is stored in a map. private final byte[] eventsLow = new byte[MAX_UPDATE_ARRAY_SIZE]; - private Map eventsHigh; + private final Map eventsHigh = new HashMap<>(); // Used by release and updateRegistrations to track whether a file // descriptor is registered with epoll. @@ -133,10 +133,6 @@ class EPollArrayWrapper { int allocationSize = NUM_EPOLLEVENTS * SIZE_EPOLLEVENT; pollArray = new AllocatedNativeObject(allocationSize, true); pollArrayAddress = pollArray.address(); - - // eventHigh needed when using file descriptors > 64k - if (OPEN_MAX > MAX_UPDATE_ARRAY_SIZE) - eventsHigh = new HashMap<>(); } void initInterrupt(int fd0, int fd1) { From 8aba8526f92b8ab784306d1b626292f33b94d695 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Tue, 15 Nov 2016 17:45:29 +0000 Subject: [PATCH 126/402] 8169723: remove jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/COPYRIGHT.html Reviewed-by: rriggs --- .../classes/org/w3c/dom/xpath/COPYRIGHT.html | 106 ------------------ 1 file changed, 106 deletions(-) delete mode 100644 jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/COPYRIGHT.html diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/COPYRIGHT.html b/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/COPYRIGHT.html deleted file mode 100644 index c7e0e497a5f..00000000000 --- a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/COPYRIGHT.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - W3C IPR SOFTWARE NOTICE - - - -

    - W3C IPR SOFTWARE NOTICE -

    -

    - Copyright © 2002 World Wide Web - Consortium, (Massachusetts - Institute of Technology, Institut - National de Recherche en Informatique et en Automatique, Keio University). All Rights - Reserved. -

    -

    - The DOM bindings are published under the W3C Software Copyright Notice - and License. The software license requires "Notice of any changes or - modifications to the W3C files, including the date changes were made." - Consequently, modified versions of the DOM bindings must document that - they do not conform to the W3C standard; in the case of the IDL - definitions, the pragma prefix can no longer be 'w3c.org'; in the case of - the Java language binding, the package names can no longer be in the - 'org.w3c' package. -

    -

    - Note: The original version of the W3C Software Copyright Notice - and License could be found at http://www.w3.org/Consortium/Legal/copyright-software-19980720 -

    -

    - Copyright © 1994-2002 World Wide Web - Consortium, (Massachusetts - Institute of Technology, Institut - National de Recherche en Informatique et en Automatique, Keio University). All Rights - Reserved. http://www.w3.org/Consortium/Legal/ -

    -

    - This W3C work (including software, documents, or other related items) is - being provided by the copyright holders under the following license. By - obtaining, using and/or copying this work, you (the licensee) agree that - you have read, understood, and will comply with the following terms and - conditions: -

    -

    - Permission to use, copy, and modify this software and its documentation, - with or without modification,  for any purpose and without fee or - royalty is hereby granted, provided that you include the following on ALL - copies of the software and documentation or portions thereof, including - modifications, that you make: -

    -
      -
    1. - The full text of this NOTICE in a location viewable to users of the - redistributed or derivative work. -
    2. -
    3. - Any pre-existing intellectual property disclaimers, notices, or terms - and conditions. If none exist, a short notice of the following form - (hypertext is preferred, text is permitted) should be used within the - body of any redistributed or derivative code: "Copyright © - [$date-of-software] World Wide Web - Consortium, (Massachusetts - Institute of Technology, Institut - National de Recherche en Informatique et en Automatique, Keio University). All Rights - Reserved. http://www.w3.org/Consortium/Legal/" -
    4. -
    5. - Notice of any changes or modifications to the W3C files, including the - date changes were made. (We recommend you provide URIs to the location - from which the code is derived.) -
    6. -
    -

    - THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT - HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, - INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS - FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR - DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, - TRADEMARKS OR OTHER RIGHTS. -

    -

    - COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR - CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR - DOCUMENTATION. -

    -

    - The name and trademarks of copyright holders may NOT be used in - advertising or publicity pertaining to the software without specific, - written prior permission. Title to copyright in this software and any - associated documentation will at all times remain with copyright - holders. -

    - - From cbebd0fb3e6c88d87bf5854da9a2ff2dc01d07cf Mon Sep 17 00:00:00 2001 From: Roman Grigoriadi Date: Tue, 15 Nov 2016 23:28:01 +0300 Subject: [PATCH 127/402] 8164479: Update JAX-WS RI integration to latest version (2.3.0-SNAPSHOT) Reviewed-by: alanb, joehw, lancea, mchung --- jaxp/src/java.xml/share/classes/module-info.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/jaxp/src/java.xml/share/classes/module-info.java b/jaxp/src/java.xml/share/classes/module-info.java index 2e21ed692cf..d9259677564 100644 --- a/jaxp/src/java.xml/share/classes/module-info.java +++ b/jaxp/src/java.xml/share/classes/module-info.java @@ -61,12 +61,6 @@ module java.xml { java.xml.ws; exports com.sun.org.apache.xml.internal.dtm to java.xml.crypto; - exports com.sun.org.apache.xml.internal.resolver to - java.xml.ws, - jdk.xml.bind; - exports com.sun.org.apache.xml.internal.resolver.tools to - java.xml.ws, - jdk.xml.bind; exports com.sun.org.apache.xml.internal.utils to java.xml.crypto; exports com.sun.org.apache.xpath.internal to From 2f39e1bd30f3cec6935d6689a9ff18448ba7c67b Mon Sep 17 00:00:00 2001 From: Roman Grigoriadi Date: Tue, 15 Nov 2016 23:43:38 +0300 Subject: [PATCH 128/402] 8164479: Update JAX-WS RI integration to latest version (2.3.0-SNAPSHOT) Reviewed-by: alanb, joehw, lancea, mchung --- .../classes/javax/activation/CommandInfo.java | 104 +++++++++- .../share/classes/module-info.java | 2 - .../com/sun/xml/internal/bind/util/Which.java | 4 +- .../classes/javax/xml/bind/JAXBContext.java | 4 +- .../javax/xml/bind/attachment/package.html | 6 +- .../helpers/AbstractUnmarshallerImpl.java | 18 +- .../javax/xml/bind/helpers/package.html | 6 +- .../share/classes/javax/xml/bind/package.html | 6 +- .../classes/javax/xml/bind/util/package.html | 6 +- .../ws/encoding/XmlDataContentHandler.java | 7 +- .../xml/internal/ws/model/RuntimeModeler.java | 28 ++- .../xml/internal/ws/util/version.properties | 2 +- .../sun/xml/internal/ws/util/xml/XmlUtil.java | 137 ++++++------- .../share/classes/module-info.java | 1 - .../sun/codemodel/internal/JCodeModel.java | 62 +++++- .../codemodel/internal/JExportsDirective.java | 67 +++++++ .../com/sun/codemodel/internal/JModule.java | 189 ++++++++++++++++++ .../codemodel/internal/JModuleDirective.java | 115 +++++++++++ .../com/sun/codemodel/internal/JPackage.java | 11 +- .../internal/JRequiresDirective.java | 91 +++++++++ .../internal/writer/FileCodeWriter.java | 8 +- .../internal/writer/FilterCodeWriter.java | 5 +- .../internal/writer/ProgressCodeWriter.java | 7 +- .../internal/writer/PrologCodeWriter.java | 3 +- .../writer/SingleStreamCodeWriter.java | 11 +- .../internal/writer/ZipCodeWriter.java | 9 +- .../internal/xjc/MessageBundle.properties | 6 +- .../com/sun/tools/internal/xjc/Messages.java | 5 +- .../com/sun/tools/internal/xjc/Options.java | 94 +++++---- .../internal/xjc/ProgressCodeWriter.java | 31 ++- .../xjc/generator/bean/BeanGenerator.java | 9 +- .../bean/ObjectFactoryGeneratorImpl.java | 10 +- .../internal/xjc/model/CBuiltinLeafInfo.java | 4 +- .../tools/internal/xjc/model/Constructor.java | 4 +- .../xjc/reader/dtd/bindinfo/BIInterface.java | 6 +- .../xsom/impl/parser/NGCCRuntimeEx.java | 100 ++++++++- .../impl/parser/state/attributeDeclBody.java | 24 +-- .../impl/parser/state/attributeGroupDecl.java | 24 +-- .../xsom/impl/parser/state/complexType.java | 27 +-- .../impl/parser/state/elementDeclBody.java | 26 +-- .../xsom/impl/parser/state/group.java | 24 +-- .../impl/parser/state/identityConstraint.java | 26 +-- .../xsom/impl/parser/state/notation.java | 25 +-- .../xsom/impl/parser/state/qname.java | 18 +- .../xsom/impl/parser/state/simpleType.java | 25 +-- .../modeler/annotation/TypeModeler.java | 31 ++- .../modeler/annotation/WebServiceAp.java | 76 +------ .../WebServiceWrapperGenerator.java | 26 ++- .../ws/resources/wscompile.properties | 3 +- .../sun/tools/internal/ws/version.properties | 2 +- .../ws/wscompile/FilerCodeWriter.java | 16 +- .../internal/ws/wscompile/WsgenTool.java | 29 +-- .../ws/wscompile/WsimportOptions.java | 18 +- .../internal/ws/wscompile/WsimportTool.java | 36 +--- 54 files changed, 1151 insertions(+), 483 deletions(-) create mode 100644 jaxws/src/jdk.xml.bind/share/classes/com/sun/codemodel/internal/JExportsDirective.java create mode 100644 jaxws/src/jdk.xml.bind/share/classes/com/sun/codemodel/internal/JModule.java create mode 100644 jaxws/src/jdk.xml.bind/share/classes/com/sun/codemodel/internal/JModuleDirective.java create mode 100644 jaxws/src/jdk.xml.bind/share/classes/com/sun/codemodel/internal/JRequiresDirective.java diff --git a/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java b/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java index b8dfd8b7091..b6312e0c253 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,10 @@ package javax.activation; import java.io.*; -import java.beans.Beans; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; /** * The CommandInfo class is used by CommandMap implementations to @@ -84,8 +87,15 @@ public class CommandInfo { /** * Return the instantiated JavaBean component. *

    - * Begin by instantiating the component with - * {@code Beans.instantiate()}. + * If {@code java.beans.Beans} is visible then it's + * {@code java.beans.Beans#instantiate} method is invoked to instantiate + * the component as a JavaBeans component. + * When {@code java.beans.Beans} is not visible (when {@code java.desktop} + * module is not readable or when the runtime image does not contain the + * {@code java.desktop} module) then the command's class is loaded and + * instantiated with its public no-args constructor. + *

    + * The component class needs to be public. *

    * If the bean implements the {@code javax.activation.CommandObject} * interface, call its {@code setCommandContext} method. @@ -102,7 +112,7 @@ public class CommandInfo { * this method will check if it implements the * java.io.Externalizable interface. If it does, the bean's * readExternal method will be called if an InputStream - * can be acquired from the DataHandler. + * can be acquired from the DataHandler.

    * * @param dh The DataHandler that describes the data to be * passed to the command. @@ -116,7 +126,7 @@ public class CommandInfo { Object new_bean = null; // try to instantiate the bean - new_bean = java.beans.Beans.instantiate(loader, className); + new_bean = Beans.instantiate(loader, className); // if we got one and it is a CommandObject if (new_bean != null) { @@ -135,4 +145,86 @@ public class CommandInfo { return new_bean; } + + /** + * Helper class to invoke Beans.instantiate reflectively or the equivalent + * with core reflection when module java.desktop is not readable. + */ + private static final class Beans { + static final Method instantiateMethod; + + static { + Method m; + try { + Class c = Class.forName("java.beans.Beans"); + m = c.getDeclaredMethod("instantiate", ClassLoader.class, String.class); + } catch (ClassNotFoundException e) { + m = null; + } catch (NoSuchMethodException e) { + m = null; + } + instantiateMethod = m; + } + + /** + * Equivalent to invoking java.beans.Beans.instantiate(loader, cn) + */ + static Object instantiate(ClassLoader loader, String cn) + throws IOException, ClassNotFoundException { + + Exception exception; + + if (instantiateMethod != null) { + + // invoke Beans.instantiate + try { + return instantiateMethod.invoke(null, loader, cn); + } catch (InvocationTargetException e) { + exception = e; + } catch (IllegalAccessException e) { + exception = e; + } + + } else { + + SecurityManager security = System.getSecurityManager(); + if (security != null) { + // if it's ok with the SecurityManager, it's ok with me. + String cname = cn.replace('/', '.'); + if (cname.startsWith("[")) { + int b = cname.lastIndexOf('[') + 2; + if (b > 1 && b < cname.length()) { + cname = cname.substring(b); + } + } + int i = cname.lastIndexOf('.'); + if (i != -1) { + security.checkPackageAccess(cname.substring(0, i)); + } + } + + // Beans.instantiate specified to use SCL when loader is null + if (loader == null) { + loader = (ClassLoader) + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + ClassLoader cl = null; + try { + cl = ClassLoader.getSystemClassLoader(); + } catch (SecurityException ex) { } + return cl; + } + }); + } + Class beanClass = Class.forName(cn, false, loader); + try { + return beanClass.getDeclaredConstructor().newInstance(); + } catch (Exception ex) { + throw new ClassNotFoundException(beanClass + ": " + ex, ex); + } + + } + return null; + } + } } diff --git a/jaxws/src/java.activation/share/classes/module-info.java b/jaxws/src/java.activation/share/classes/module-info.java index dca632ee776..1ba4eb115ec 100644 --- a/jaxws/src/java.activation/share/classes/module-info.java +++ b/jaxws/src/java.activation/share/classes/module-info.java @@ -28,8 +28,6 @@ */ module java.activation { requires public java.datatransfer; - // dependence on java.beans.Beans to be eliminated - requires java.desktop; requires java.logging; exports javax.activation; diff --git a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/util/Which.java b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/util/Which.java index 4e52d9cce11..bb9eeb5faf8 100644 --- a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/util/Which.java +++ b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/util/Which.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,7 +41,7 @@ public class Which { /** * Search the specified classloader for the given classname. - * + * Then give the return value. * @param classname the fully qualified name of the class to search for * @param loader the classloader to search * @return the source location of the resource, or null if it wasn't found diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java index a2d9bceb37f..4b4f6e55c46 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java @@ -450,8 +450,8 @@ public abstract class JAXBContext { * in an empty map. * * @return a new instance of a {@code JAXBContext} - * @throws JAXBException - * if an error was encountered while creating the {@code JAXBContext} such as + * @throws JAXBException if an error was encountered while creating the + * {@code JAXBContext} such as *

      *
    1. failure to locate either ObjectFactory.class or jaxb.index in the packages
    2. *
    3. an ambiguity among global elements contained in the contextPath
    4. diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/package.html b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/package.html index c452cb9ad7f..499643d184d 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/package.html +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/package.html @@ -1,6 +1,6 @@ - @since 1.6, JAXB 2.0 + @since JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/AbstractUnmarshallerImpl.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/AbstractUnmarshallerImpl.java index cef1cf68e72..78f5232a446 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/AbstractUnmarshallerImpl.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/AbstractUnmarshallerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,9 +47,7 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; -import java.io.File; -import java.io.Reader; -import java.net.MalformedURLException; +import java.io.*; import java.net.URL; /** @@ -178,16 +176,8 @@ public abstract class AbstractUnmarshallerImpl implements Unmarshaller } try { - // copied from JAXP - String path = f.getAbsolutePath(); - if (File.separatorChar != '/') - path = path.replace(File.separatorChar, '/'); - if (!path.startsWith("/")) - path = "/" + path; - if (!path.endsWith("/") && f.isDirectory()) - path = path + "/"; - return unmarshal(new URL("file", "", path)); - } catch( MalformedURLException e ) { + return unmarshal(new BufferedInputStream(new FileInputStream(f))); + } catch( FileNotFoundException e ) { throw new IllegalArgumentException(e.getMessage()); } } diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/package.html b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/package.html index 059abed0a0b..02588965592 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/package.html +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/helpers/package.html @@ -1,6 +1,6 @@ - + + + + - @@ -550,6 +552,7 @@ grant codeBase "file:/${basedir}/test/script/basic/JDK-8158467.js" { + diff --git a/nashorn/src/jdk.dynalink/share/classes/jdk/dynalink/beans/ClassString.java b/nashorn/src/jdk.dynalink/share/classes/jdk/dynalink/beans/ClassString.java index 06b3cdb2348..f7a2c56577c 100644 --- a/nashorn/src/jdk.dynalink/share/classes/jdk/dynalink/beans/ClassString.java +++ b/nashorn/src/jdk.dynalink/share/classes/jdk/dynalink/beans/ClassString.java @@ -88,6 +88,7 @@ import java.lang.invoke.MethodType; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.Arrays; import java.util.LinkedList; import java.util.List; import jdk.dynalink.internal.AccessControlContextFactory; @@ -149,6 +150,11 @@ final class ClassString { return hashCode; } + @Override + public String toString() { + return "ClassString[" + Arrays.toString(classes) + "]"; + } + boolean isVisibleFrom(final ClassLoader classLoader) { return AccessController.doPrivileged(new PrivilegedAction() { @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java index acd8db54044..adda5988910 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java @@ -31,24 +31,13 @@ import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_VARARGS; -import static jdk.internal.org.objectweb.asm.Opcodes.AALOAD; import static jdk.internal.org.objectweb.asm.Opcodes.ALOAD; -import static jdk.internal.org.objectweb.asm.Opcodes.ARRAYLENGTH; import static jdk.internal.org.objectweb.asm.Opcodes.ASTORE; import static jdk.internal.org.objectweb.asm.Opcodes.D2F; -import static jdk.internal.org.objectweb.asm.Opcodes.GETSTATIC; -import static jdk.internal.org.objectweb.asm.Opcodes.GOTO; import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC; -import static jdk.internal.org.objectweb.asm.Opcodes.ICONST_0; -import static jdk.internal.org.objectweb.asm.Opcodes.IF_ICMPGE; -import static jdk.internal.org.objectweb.asm.Opcodes.ILOAD; import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEVIRTUAL; -import static jdk.internal.org.objectweb.asm.Opcodes.ISTORE; import static jdk.internal.org.objectweb.asm.Opcodes.I2B; import static jdk.internal.org.objectweb.asm.Opcodes.I2S; -import static jdk.internal.org.objectweb.asm.Opcodes.POP; -import static jdk.internal.org.objectweb.asm.Opcodes.PUTSTATIC; import static jdk.internal.org.objectweb.asm.Opcodes.RETURN; import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup; import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup; @@ -66,6 +55,7 @@ import java.lang.reflect.Modifier; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; +import java.security.ProtectionDomain; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; @@ -73,20 +63,14 @@ import java.util.Iterator; import java.util.List; import java.util.Set; import jdk.internal.org.objectweb.asm.ClassWriter; -import jdk.internal.org.objectweb.asm.FieldVisitor; -import jdk.internal.org.objectweb.asm.Handle; -import jdk.internal.org.objectweb.asm.Label; -import jdk.internal.org.objectweb.asm.MethodVisitor; -import jdk.internal.org.objectweb.asm.Opcodes; -import jdk.internal.org.objectweb.asm.Type; import jdk.internal.org.objectweb.asm.Handle; import jdk.internal.org.objectweb.asm.Label; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.org.objectweb.asm.Type; import jdk.internal.org.objectweb.asm.commons.InstructionAdapter; +import jdk.nashorn.api.scripting.ScriptObjectMirror; import jdk.nashorn.api.scripting.ScriptUtils; import jdk.nashorn.internal.codegen.CompilerConstants.Call; -import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptObject; import jdk.nashorn.internal.runtime.linker.AdaptationResult.Outcome; @@ -139,7 +123,8 @@ import jdk.internal.reflect.CallerSensitive; * to resemble Java anonymous classes) is actually equivalent to new X(a, b, { ... }). *

      * It is possible to create two different adapter classes: those that can have class-level overrides, and those that can - * have instance-level overrides. When {@link JavaAdapterFactory#getAdapterClassFor(Class[], ScriptObject)} is invoked + * have instance-level overrides. When {@link JavaAdapterFactory#getAdapterClassFor(Class[], ScriptObject, ProtectionDomain)} + * or {@link JavaAdapterFactory#getAdapterClassFor(Class[], ScriptObject, Lookup)} is invoked * with non-null {@code classOverrides} parameter, an adapter class is created that can have class-level overrides, and * the passed script object will be used as the implementations for its methods, just as in the above case of the * constructor taking a script object. Note that in the case of class-level overrides, a new adapter class is created on @@ -168,6 +153,7 @@ final class JavaAdapterBytecodeGenerator { private static final Type OBJECT_TYPE = Type.getType(Object.class); private static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class); private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class); + private static final Type SCRIPT_OBJECT_MIRROR_TYPE = Type.getType(ScriptObjectMirror.class); // JavaAdapterServices methods used in generated bytecode private static final Call CHECK_FUNCTION = lookupServiceMethod("checkFunction", ScriptFunction.class, Object.class, String.class); @@ -182,6 +168,7 @@ final class JavaAdapterBytecodeGenerator { private static final Call TO_CHAR_PRIMITIVE = lookupServiceMethod("toCharPrimitive", char.class, Object.class); private static final Call UNSUPPORTED = lookupServiceMethod("unsupported", UnsupportedOperationException.class); private static final Call WRAP_THROWABLE = lookupServiceMethod("wrapThrowable", RuntimeException.class, Throwable.class); + private static final Call UNWRAP_MIRROR = lookupServiceMethod("unwrapMirror", ScriptObject.class, Object.class, boolean.class); // Other methods invoked by the generated bytecode private static final Call UNWRAP = staticCallNoLookup(ScriptUtils.class, "unwrap", Object.class, Object.class); @@ -216,8 +203,7 @@ final class JavaAdapterBytecodeGenerator { private static final String GET_METHOD_PROPERTY_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE, SCRIPT_OBJECT_TYPE); private static final String VOID_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE); - static final String ADAPTER_PACKAGE_INTERNAL = "jdk/nashorn/javaadapters/"; - static final String ADAPTER_PACKAGE = "jdk.nashorn.javaadapters"; + private static final String ADAPTER_PACKAGE_INTERNAL = "jdk/nashorn/javaadapters/"; private static final int MAX_GENERATED_TYPE_NAME_LENGTH = 255; // Method name prefix for invoking super-methods @@ -265,7 +251,7 @@ final class JavaAdapterBytecodeGenerator { * @throws AdaptationException if the adapter can not be generated for some reason. */ JavaAdapterBytecodeGenerator(final Class superClass, final List> interfaces, - final ClassLoader commonLoader, final boolean classOverride) throws AdaptationException { + final ClassLoader commonLoader, final boolean classOverride) throws AdaptationException { assert superClass != null && !superClass.isInterface(); assert interfaces != null; @@ -369,7 +355,7 @@ final class JavaAdapterBytecodeGenerator { // If the class is a SAM, allow having ScriptFunction passed as class overrides mv.dup(); mv.instanceOf(SCRIPT_FUNCTION_TYPE); - mv.dup(); + mv.dup(); mv.putstatic(generatedClassName, IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR); final Label notFunction = new Label(); mv.ifeq(notFunction); @@ -389,9 +375,9 @@ final class JavaAdapterBytecodeGenerator { private void emitInitCallThis(final InstructionAdapter mv) { loadField(mv, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR); GET_CALL_THIS.invoke(mv); - if(classOverride) { + if(classOverride) { mv.putstatic(generatedClassName, CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR); - } else { + } else { // It is presumed ALOAD 0 was already executed mv.putfield(generatedClassName, CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR); } @@ -427,10 +413,10 @@ final class JavaAdapterBytecodeGenerator { if (samName == null) { return false; - } - // If all our abstract methods have a single name, generate an additional constructor, one that takes a - // ScriptFunction as its first parameter and assigns it as the implementation for all abstract methods. - generateOverridingConstructor(ctor, true); + } + // If all our abstract methods have a single name, generate an additional constructor, one that takes a + // ScriptFunction as its first parameter and assigns it as the implementation for all abstract methods. + generateOverridingConstructor(ctor, true); // If the original type only has a single abstract method name, as well as a default ctor, then it can // be automatically converted from JS function. return ctor.getParameterTypes().length == 0; @@ -456,14 +442,9 @@ final class JavaAdapterBytecodeGenerator { * constructor passed as the argument here, and delegate to it. However, it will take an additional argument of * either ScriptObject or ScriptFunction type (based on the value of the "fromFunction" parameter), and initialize * all the method handle fields of the adapter instance with functions from the script object (or the script - * function itself, if that's what's passed). There is one method handle field in the adapter class for every method - * that can be implemented or overridden; the name of every field is same as the name of the method, with a number - * suffix that makes it unique in case of overloaded methods. The generated constructor will invoke - * {@link #getHandle(ScriptFunction, MethodType, boolean)} or {@link #getHandle(Object, String, MethodType, - * boolean)} to obtain the method handles; these methods make sure to add the necessary conversions and arity - * adjustments so that the resulting method handles can be invoked from generated methods using {@code invokeExact}. - * The constructor that takes a script function will only initialize the methods with the same name as the single - * abstract method. The constructor will also store the Nashorn global that was current at the constructor + * function itself, if that's what's passed). Additionally, it will create another constructor with an additional + * Object type parameter that can be used for ScriptObjectMirror objects. + * The constructor will also store the Nashorn global that was current at the constructor * invocation time in a field named "global". The generated constructor will be public, regardless of whether the * supertype constructor was public or protected. The generated constructor will not be variable arity, even if the * supertype constructor was. @@ -524,14 +505,59 @@ final class JavaAdapterBytecodeGenerator { } } - // Object additional param accepting constructor - generated to handle null and undefined value - // for script adapters. This is effectively to throw TypeError on such script adapters. See - // JavaAdapterServices.getHandle as well. + // Object additional param accepting constructor for handling ScriptObjectMirror objects, which are + // unwrapped to work as ScriptObjects or ScriptFunctions. This also handles null and undefined values for + // script adapters by throwing TypeError on such script adapters. private void generateOverridingConstructorWithObjectParam(final InstructionAdapter mv, final String ctorDescriptor) { mv.visitCode(); final int extraArgOffset = emitSuperConstructorCall(mv, ctorDescriptor); + + // Check for ScriptObjectMirror + mv.visitVarInsn(ALOAD, extraArgOffset); + mv.instanceOf(SCRIPT_OBJECT_MIRROR_TYPE); + final Label notMirror = new Label(); + mv.ifeq(notMirror); + + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, extraArgOffset); + mv.iconst(0); + UNWRAP_MIRROR.invoke(mv); + mv.putfield(generatedClassName, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR); + + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, extraArgOffset); + mv.iconst(1); + UNWRAP_MIRROR.invoke(mv); + mv.putfield(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR); + + final Label done = new Label(); + + if (samName != null) { + mv.visitVarInsn(ALOAD, 0); + mv.getfield(generatedClassName, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR); + mv.instanceOf(SCRIPT_FUNCTION_TYPE); + mv.ifeq(done); + + // Assign "isFunction = true" + mv.visitVarInsn(ALOAD, 0); + mv.iconst(1); + mv.putfield(generatedClassName, IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR); + + mv.visitVarInsn(ALOAD, 0); + mv.dup(); + mv.getfield(generatedClassName, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR); + mv.checkcast(SCRIPT_FUNCTION_TYPE); + emitInitCallThis(mv); + mv.goTo(done); + } + + mv.visitLabel(notMirror); + + // Throw error if not a ScriptObject mv.visitVarInsn(ALOAD, extraArgOffset); NOT_AN_OBJECT.invoke(mv); + + mv.visitLabel(done); endInitMethod(mv); } @@ -678,7 +704,7 @@ final class JavaAdapterBytecodeGenerator { // stack: [callThis, delegate] mv.goTo(callCallee); mv.visitLabel(notFunction); - } else { + } else { // If it's not a SAM method, and the delegate is a function, // it'll fall back to default behavior mv.ifne(defaultBehavior); @@ -818,7 +844,7 @@ final class JavaAdapterBytecodeGenerator { if (isVarArgCall) { // Variable arity calls are always (Object callee, Object this, Object[] params) callParamTypes = new Class[] { Object.class, Object.class, Object[].class }; - } else { + } else { // Adjust invocation type signature for conversions we instituted in // convertParam; also, byte and short get passed as ints. final Class[] origParamTypes = type.parameterArray(); @@ -868,13 +894,13 @@ final class JavaAdapterBytecodeGenerator { private void loadField(final InstructionAdapter mv, final String name, final String desc) { - if(classOverride) { + if(classOverride) { mv.getstatic(generatedClassName, name, desc); - } else { - mv.visitVarInsn(ALOAD, 0); + } else { + mv.visitVarInsn(ALOAD, 0); mv.getfield(generatedClassName, name, desc); - } - } + } + } private static void convertReturnValue(final InstructionAdapter mv, final Class origReturnType) { if (origReturnType == void.class) { @@ -948,6 +974,7 @@ final class JavaAdapterBytecodeGenerator { } return len; } + /** * Emit code to restore the previous Nashorn Context when needed. * @param mv the instruction adapter @@ -999,9 +1026,9 @@ final class JavaAdapterBytecodeGenerator { } for (final Class iface : interfaces) { - if (cl.isAssignableFrom(iface)) { - return iface; - } + if (cl.isAssignableFrom(iface)) { + return iface; + } } // we better that interface that extends the given interface! @@ -1122,8 +1149,8 @@ final class JavaAdapterBytecodeGenerator { if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) { finalMethods.add(mi); } else if (!finalMethods.contains(mi) && methodInfos.add(mi) && Modifier.isAbstract(m)) { - abstractMethodNames.add(mi.getName()); - } + abstractMethodNames.add(mi.getName()); + } } } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java index ddd21163004..00fcb7eff96 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterFactory.java @@ -234,7 +234,7 @@ public final class JavaAdapterFactory { /** * For a given class, create its adapter class and associated info. * - * @param type the class for which the adapter is created + * @param types the class and interfaces for which the adapter is created * * @return the adapter info for the class. */ diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java index 19c6d32b337..346d66cc5eb 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java @@ -39,6 +39,7 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; +import java.lang.reflect.Field; import java.security.AccessController; import java.security.CodeSigner; import java.security.CodeSource; @@ -51,6 +52,7 @@ import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.org.objectweb.asm.Type; import jdk.internal.org.objectweb.asm.commons.InstructionAdapter; +import jdk.nashorn.api.scripting.ScriptObjectMirror; import jdk.nashorn.internal.objects.Global; import jdk.nashorn.internal.runtime.Context; import jdk.nashorn.internal.runtime.ECMAException; @@ -175,6 +177,23 @@ public final class JavaAdapterServices { return sobj.getMap().findProperty("toString") != null; } + /** + * Returns the ScriptObject or Global field value from a ScriptObjectMirror using reflection. + * + * @param mirror the mirror object + * @param getGlobal true if we want the global object, false to return the script object + * @return the script object or global object + */ + public static ScriptObject unwrapMirror(final Object mirror, final boolean getGlobal) { + assert mirror instanceof ScriptObjectMirror; + try { + final Field field = getGlobal ? MirrorFieldHolder.GLOBAL_FIELD : MirrorFieldHolder.SOBJ_FIELD; + return (ScriptObject) field.get(mirror); + } catch (final IllegalAccessException x) { + throw new RuntimeException(x); + } + } + /** * Delegate to {@link Bootstrap#bootstrap(Lookup, String, MethodType, int)}. * @param lookup MethodHandle lookup. @@ -291,4 +310,24 @@ public final class JavaAdapterServices { .asCollector(Object[].class, type.parameterCount()) .asType(type)); } + + // Initialization on demand holder for accessible ScriptObjectMirror fields + private static class MirrorFieldHolder { + + private static final Field SOBJ_FIELD = getMirrorField("sobj"); + private static final Field GLOBAL_FIELD = getMirrorField("global"); + + private static Field getMirrorField(final String fieldName) { + try { + final Field field = ScriptObjectMirror.class.getDeclaredField(fieldName); + AccessController.doPrivileged((PrivilegedAction) () -> { + field.setAccessible(true); + return null; + }); + return field; + } catch (final NoSuchFieldException e) { + throw new RuntimeException(e); + } + } + } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java index 12c22adf232..af23b6d1fe0 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornLinker.java @@ -157,12 +157,17 @@ final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTyp */ private static GuardedInvocation getSamTypeConverter(final Class sourceType, final Class targetType, final Supplier lookupSupplier) throws Exception { // If source type is more generic than ScriptFunction class, we'll need to use a guard - final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptFunction.class); + final boolean isSourceTypeGeneric = sourceType.isAssignableFrom(ScriptObject.class); if ((isSourceTypeGeneric || ScriptFunction.class.isAssignableFrom(sourceType)) && isAutoConvertibleFromFunction(targetType)) { - final MethodHandle ctor = JavaAdapterFactory.getConstructor(ScriptFunction.class, targetType, getCurrentLookup(lookupSupplier)); + final Class paramType = isSourceTypeGeneric ? Object.class : ScriptFunction.class; + // Using Object.class as constructor source type means we're getting an overloaded constructor handle, + // which is safe but slower than a single constructor handle. If the actual argument is a ScriptFunction it + // would be nice if we could change the formal parameter to ScriptFunction.class and add a guard for it + // in the main invocation. + final MethodHandle ctor = JavaAdapterFactory.getConstructor(paramType, targetType, getCurrentLookup(lookupSupplier)); assert ctor != null; // if isAutoConvertibleFromFunction() returned true, then ctor must exist. - return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_SCRIPT_FUNCTION : null); + return new GuardedInvocation(ctor, isSourceTypeGeneric ? IS_FUNCTION : null); } return null; } @@ -315,7 +320,7 @@ final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTyp } private static final MethodHandle IS_SCRIPT_OBJECT = Guards.isInstance(ScriptObject.class, MH.type(Boolean.TYPE, Object.class)); - private static final MethodHandle IS_SCRIPT_FUNCTION = Guards.isInstance(ScriptFunction.class, MH.type(Boolean.TYPE, Object.class)); + private static final MethodHandle IS_FUNCTION = findOwnMH("isFunction", boolean.class, Object.class); private static final MethodHandle IS_NATIVE_ARRAY = Guards.isOfClass(NativeArray.class, MH.type(Boolean.TYPE, Object.class)); private static final MethodHandle IS_NASHORN_OR_UNDEFINED_TYPE = findOwnMH("isNashornTypeOrUndefined", Boolean.TYPE, Object.class); @@ -348,6 +353,11 @@ final class NashornLinker implements TypeBasedGuardingDynamicLinker, GuardingTyp return obj instanceof ScriptObject? ScriptUtils.wrap((ScriptObject)obj) : obj; } + @SuppressWarnings("unused") + private static boolean isFunction(final Object obj) { + return obj instanceof ScriptFunction || obj instanceof ScriptObjectMirror && ((ScriptObjectMirror) obj).isFunction(); + } + private static MethodHandle findOwnMH(final String name, final Class rtype, final Class... types) { return MH.findStatic(MethodHandles.lookup(), NashornLinker.class, name, MH.type(rtype, types)); } diff --git a/nashorn/test/src/jdk/nashorn/internal/runtime/linker/test/JavaAdapterTest.java b/nashorn/test/src/jdk/nashorn/internal/runtime/linker/test/JavaAdapterTest.java index f7964aafafb..ad82e5febd0 100644 --- a/nashorn/test/src/jdk/nashorn/internal/runtime/linker/test/JavaAdapterTest.java +++ b/nashorn/test/src/jdk/nashorn/internal/runtime/linker/test/JavaAdapterTest.java @@ -29,11 +29,14 @@ import java.util.Deque; import java.util.List; import java.util.Map; import java.util.Queue; +import java.util.function.Function; import java.util.function.Supplier; import javax.script.Bindings; +import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; import jdk.nashorn.api.scripting.JSObject; +import jdk.nashorn.api.scripting.NashornScriptEngine; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; import jdk.nashorn.api.scripting.ScriptObjectMirror; import jdk.nashorn.internal.runtime.Context; @@ -277,4 +280,37 @@ public class JavaAdapterTest { Assert.assertEquals(tla.getQueue().peek(), "Queue"); Assert.assertEquals(tla.getDequeue().peek(), "Dequeue"); } + + @Test + public static void testMirrorAdapter() throws ScriptException { + final NashornScriptEngine e = (NashornScriptEngine) createEngine(); + e.setBindings(e.createBindings(), ScriptContext.GLOBAL_SCOPE); // Null by default + + // Referencing functions from across scopes causes them to be wrapped in ScriptObjectMirrors + e.eval("function convertObjectFromEngineScope(){ return new java.util.concurrent.Callable(o).call(); }", e.getBindings(ScriptContext.ENGINE_SCOPE)); + e.eval("function convertObjectFromGlobalScope(){ return new java.util.concurrent.Callable(o).call(); }", e.getBindings(ScriptContext.GLOBAL_SCOPE)); + e.eval("function convertFuncFromEngineScope(){ return new java.util.concurrent.Callable(g).call(); }", e.getBindings(ScriptContext.ENGINE_SCOPE)); + e.eval("function convertFuncFromGlobalScope(){ return new java.util.concurrent.Callable(g).call(); }", e.getBindings(ScriptContext.GLOBAL_SCOPE)); + e.eval("function convertParamFromEngineScope(){ return Java.type('jdk.nashorn.internal.runtime.linker.test.JavaAdapterTest').m(f);}", e.getBindings(ScriptContext.ENGINE_SCOPE)); + e.eval("function convertParamFromGlobalScope(){ return Java.type('jdk.nashorn.internal.runtime.linker.test.JavaAdapterTest').m(f);}", e.getBindings(ScriptContext.GLOBAL_SCOPE)); + + e.eval("var o = { call: function () { return 'ok from o'; } }", e.getBindings(ScriptContext.ENGINE_SCOPE)); + e.eval("function g() { return 'ok from g'; }", e.getBindings(ScriptContext.ENGINE_SCOPE)); + e.eval("function f(a) { return a.toUpperCase(); }", e.getBindings(ScriptContext.ENGINE_SCOPE)); + + try { + Assert.assertEquals(e.invokeFunction("convertObjectFromEngineScope"), "ok from o"); + Assert.assertEquals(e.invokeFunction("convertObjectFromGlobalScope"), "ok from o"); + Assert.assertEquals(e.invokeFunction("convertFuncFromEngineScope"), "ok from g"); + Assert.assertEquals(e.invokeFunction("convertFuncFromGlobalScope"), "ok from g"); + Assert.assertEquals(e.invokeFunction("convertParamFromEngineScope"), "OK"); + Assert.assertEquals(e.invokeFunction("convertParamFromGlobalScope"), "OK"); + } catch (final NoSuchMethodException x) { + throw new RuntimeException(x); + } + } + + public static String m(final Function f){ + return f.apply("ok"); + } } From c97f7be269b6be5468bc1a6bb16398d65bee84f6 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:05 +0000 Subject: [PATCH 139/402] Added tag jdk-9+145 for changeset b57b4dfdfeae --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 27933595820..60e0db5186c 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -387,3 +387,4 @@ f64afae7f1a5608e438585bbf0bc23785e69cba0 jdk-9+141 2b3e5caafe3594ea507c37675c4d3086f415dc64 jdk-9+142 1fc62b1c629fb80fdaa639d3b59452a184f0d705 jdk-9+143 8d337fd6333e28c48aa87880144b840aad82baaf jdk-9+144 +ff98aa9ec9fae991e426ce5926fc9036d25f5562 jdk-9+145 From f317eceb57eda0ab1808692be2d43ecd606c2862 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:06 +0000 Subject: [PATCH 140/402] Added tag jdk-9+145 for changeset 62743782a2cd --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 5ab3bfa0769..cd5f02b0b6d 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -547,3 +547,4 @@ fec31089c2ef5a12dd64f401b0bf2e00f56ee0d0 jdk-9+140 7b48d63dfd6b8e2657288de3d7b1f153dee02d7e jdk-9+142 d87d5d430c42342f0320ca7f5cbe0cbd1f9d62ba jdk-9+143 6187b582d02aee38341dc8ce4011906e9b364e9f jdk-9+144 +61e7ea56312351657e69198c503a6f7bf865af83 jdk-9+145 From e3675e43a45d3601c654a2f68a6889b5b0461401 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:06 +0000 Subject: [PATCH 141/402] Added tag jdk-9+145 for changeset 4a046fdccd54 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index 7ec4e1bd79d..909878451d9 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -387,3 +387,4 @@ b32f998da32b488ec7c4e9dbb3c750841b48e74d jdk-9+141 408c9c621938ca028e20bced0459f815de47eba8 jdk-9+142 6211236ef15ec796806357608b1dd1b70c258ece jdk-9+143 d4f1dae174098e799c48948e866054c52e11a186 jdk-9+144 +a44b156ae7f06bf41b9bece30df7775e482395dd jdk-9+145 From 184464493342892fbc3d4321843bfd2ebb9f8717 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:07 +0000 Subject: [PATCH 142/402] Added tag jdk-9+145 for changeset 5fce5ec624c7 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index 5d90ddab9df..0cce729770a 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -390,3 +390,4 @@ b2c18f755228d1d19a86cd7d5fa1abb6b1495dfb jdk-9+141 59101416d90160cfcb4f45dfbccaec15e2c27a29 jdk-9+142 1c988e708a06257119d54d8a57e99e3b0f37ff18 jdk-9+143 92523c51d6a48b0a83912ba3cc43bc57b8159c2a jdk-9+144 +29277a4e73077269358859c43bd6658593fc0410 jdk-9+145 From baccfc7adb79ca17af5f98dafff314b0f6be611e Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:07 +0000 Subject: [PATCH 143/402] Added tag jdk-9+145 for changeset 6ffe7113ca30 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index 900943ec381..c3fd9c28825 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -387,3 +387,4 @@ a8d5fe567ae72b4931040e59dd4478363f9004f5 jdk-9+137 bdafa0cc34a97a2f8db4847a4efd34b407943591 jdk-9+142 ce81d03ad7320dca3d673374c1a33bc0efd9136a jdk-9+143 99be33734ff62b75116b1202d49a4d4e1bda4226 jdk-9+144 +71558b38bad786f11350790cef7d2c6409813e91 jdk-9+145 From 964fb2939dabfd4921a02680a0ab2e9d38253f6b Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:08 +0000 Subject: [PATCH 144/402] Added tag jdk-9+145 for changeset fb4ce696b742 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index d39ded9908c..766e790c648 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -387,3 +387,4 @@ e93b7ea559759f036c9f69fd2ddaf47bb4e98385 jdk-9+140 6ce43dd8e954b452f330dd7a412df5107f7e1923 jdk-9+142 8dbc8594f9d5149bf1c22221272284609408227a jdk-9+143 efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 +99b7853cfbd8227c4441de4b6119c10742556840 jdk-9+145 From d71937b0ec8c92ffbf3ddfb3b1bb60582b3e10f6 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:09 +0000 Subject: [PATCH 145/402] Added tag jdk-9+145 for changeset eb674141ab03 --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index fc07f2de0a9..fd73992bc90 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -378,3 +378,4 @@ a46b7d3867957a868a6cc8ee66c05079b883733a jdk-9+141 d3f5d7311a1aec3152b17d75046d5d298245a0b4 jdk-9+142 b4e57ead3fae4939b70dd345d1f6744a1dedfa21 jdk-9+143 a7f21ee6ed30695a6de14e74035d2857a754f62b jdk-9+144 +4a68dd740be8aa0d1a25f94985b3cb2e190ccfce jdk-9+145 From 3c2c13f0f9bc8f4b4b5a15057640509f0bdc9b34 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Thu, 17 Nov 2016 17:50:09 +0000 Subject: [PATCH 146/402] Added tag jdk-9+145 for changeset 8b7412f7eecd --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index 4205f71b3ec..ab225307c96 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -387,3 +387,4 @@ dd56c243c199a540c9f1fbff4855f0934b32a9d0 jdk-9+137 d245e56f4a79a8a8d18bd143c08f079ee98ab638 jdk-9+142 6ef8a1453577832626b0efb7f70a3102b721ebbf jdk-9+143 47871e348144bafddea0ede3a44299461e254a2d jdk-9+144 +cb9e896265ef45295fdd09986dee76624e4d41e4 jdk-9+145 From 067d76740ccd4961f2d9862acdd60fcf9524dd5b Mon Sep 17 00:00:00 2001 From: Frank Yuan Date: Fri, 18 Nov 2016 10:34:56 +0800 Subject: [PATCH 147/402] 8169829: ProblemList update for javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh Reviewed-by: joehw, lana --- jaxp/test/ProblemList.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jaxp/test/ProblemList.txt b/jaxp/test/ProblemList.txt index ce63d06ff47..547afbb1e21 100644 --- a/jaxp/test/ProblemList.txt +++ b/jaxp/test/ProblemList.txt @@ -23,4 +23,4 @@ # ########################################################################### -javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8147431 generic-all +javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8169827 generic-all From 813b2be3934672de902f6a3593c7c71574e57749 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Thu, 17 Nov 2016 21:49:07 -0800 Subject: [PATCH 148/402] 8158619: Very large CDATA section in XML document causes OOME Reviewed-by: dfuchs, lancea, clanger --- .../xalan/internal/xsltc/compiler/Parser.java | 6 + .../xalan/internal/xsltc/compiler/XSLTC.java | 57 ++-- .../internal/xsltc/trax/TemplatesImpl.java | 7 +- .../xsltc/trax/TransformerFactoryImpl.java | 18 +- .../internal/xsltc/trax/TransformerImpl.java | 4 + .../xalan/internal/xsltc/trax/Util.java | 12 +- .../internal/dom/DOMConfigurationImpl.java | 5 +- .../xerces/internal/impl/PropertyManager.java | 2 + .../internal/impl/XML11EntityScanner.java | 120 +++----- .../internal/impl/XMLDTDScannerImpl.java | 2 +- .../impl/XMLDocumentFragmentScannerImpl.java | 102 +++---- .../internal/impl/XMLDocumentScannerImpl.java | 2 + .../internal/impl/XMLEntityManager.java | 6 +- .../internal/impl/XMLEntityScanner.java | 13 +- .../xerces/internal/impl/XMLScanner.java | 6 +- .../internal/impl/xs/XMLSchemaLoader.java | 26 +- .../internal/impl/xs/XMLSchemaValidator.java | 17 +- .../impl/xs/opti/SchemaParsingConfig.java | 4 +- .../impl/xs/traversers/XSDHandler.java | 53 ++-- .../validation/StreamValidatorHelper.java | 129 ++++---- .../jaxp/validation/XMLSchemaFactory.java | 2 + .../XMLSchemaValidatorComponentManager.java | 4 + .../internal/parsers/DTDConfiguration.java | 5 +- .../parsers/NonValidatingConfiguration.java | 5 +- .../internal/parsers/XML11Configuration.java | 5 +- .../xml/internal/utils/XMLReaderManager.java | 18 +- .../classes/jdk/xml/internal/JdkXmlUtils.java | 77 ++++- .../jdk/xml/internal/SecuritySupport.java | 15 +- .../unittest/common/CDataChunkSizeTest.java | 284 ++++++++++++++++++ 29 files changed, 713 insertions(+), 293 deletions(-) create mode 100644 jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java index d8d16ecb516..2fb0b470db2 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java @@ -530,6 +530,10 @@ public class Parser implements Constants, ContentHandler { XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se); } + // try setting other JDK-impl properties, ignore if not supported + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + _xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false); + return(parse(reader, input)); } catch (ParserConfigurationException e) { @@ -1342,12 +1346,14 @@ public class Parser implements Constants, ContentHandler { } else { SyntaxTreeNode parent = _parentStack.peek(); + if (element.getClass().isAssignableFrom(Import.class) && parent.notTypeOf(Import.class)) { ErrorMsg err = new ErrorMsg(ErrorMsg.IMPORT_PRECEDE_OTHERS_ERR, prefix+':'+localname); throw new SAXException(err.toString()); } + parent.addElement(element); element.setParent(parent); } diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java index b6080fb86da..e8f80a2c502 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java @@ -43,12 +43,14 @@ import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Vector; +import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import javax.xml.XMLConstants; import javax.xml.catalog.CatalogFeatures; import jdk.xml.internal.JdkXmlFeatures; +import jdk.xml.internal.JdkXmlUtils; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; @@ -116,8 +118,8 @@ public final class XSLTC { private File _destDir = null; // -d private int _outputType = FILE_OUTPUT; // by default - private Vector _classes; - private Vector _bcelClasses; + private ArrayList _classes; + private ArrayList _bcelClasses; private boolean _callsNodeset = false; private boolean _multiDocument = false; private boolean _hasIdCall = false; @@ -160,13 +162,18 @@ public final class XSLTC { /** * HashMap with the loaded classes */ - private final Map _externalExtensionFunctions; + private final Map> _externalExtensionFunctions; /** * Catalog features */ CatalogFeatures _catalogFeatures; + /** + * CDATA chunk size + */ + int _cdataChunkSize; + /** * XSLTC compiler constructor */ @@ -230,6 +237,8 @@ public final class XSLTC { return _extensionClassLoader; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { return _catalogFeatures; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + return _cdataChunkSize; } return null; } @@ -254,6 +263,8 @@ public final class XSLTC { _externalExtensionFunctions.clear(); } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { _catalogFeatures = (CatalogFeatures)value; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = Integer.parseInt((String)value); } } @@ -284,11 +295,11 @@ public final class XSLTC { public void init() { reset(); _reader = null; - _classes = new Vector(); - _bcelClasses = new Vector(); + _classes = new ArrayList<>(); + _bcelClasses = new ArrayList<>(); } - private void setExternalExtensionFunctions(String name, Class clazz) { + private void setExternalExtensionFunctions(String name, Class clazz) { if (_isSecureProcessing && clazz != null && !_externalExtensionFunctions.containsKey(name)) { _externalExtensionFunctions.put(name, clazz); } @@ -319,7 +330,7 @@ public final class XSLTC { * Returns unmodifiable view of HashMap with loaded external extension * functions - will be needed for the TransformerImpl */ - public Map getExternalExtensionFunctions() { + public Map> getExternalExtensionFunctions() { return Collections.unmodifiableMap(_externalExtensionFunctions); } @@ -563,7 +574,7 @@ public final class XSLTC { final int count = _classes.size(); final byte[][] result = new byte[count][1]; for (int i = 0; i < count; i++) - result[i] = (byte[])_classes.elementAt(i); + result[i] = _classes.get(i).toByteArray(); return result; } @@ -907,7 +918,7 @@ public final class XSLTC { getOutputFile(clazz.getClassName())))); break; case JAR_OUTPUT: - _bcelClasses.addElement(clazz); + _bcelClasses.add(clazz); break; case BYTEARRAY_OUTPUT: case BYTEARRAY_AND_FILE_OUTPUT: @@ -915,13 +926,13 @@ public final class XSLTC { case CLASSLOADER_OUTPUT: ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); - _classes.addElement(out.toByteArray()); + _classes.add(out); if (_outputType == BYTEARRAY_AND_FILE_OUTPUT) clazz.dump(new BufferedOutputStream( new FileOutputStream(getOutputFile(clazz.getClassName())))); else if (_outputType == BYTEARRAY_AND_JAR_OUTPUT) - _bcelClasses.addElement(clazz); + _bcelClasses.add(clazz); break; } @@ -945,30 +956,24 @@ public final class XSLTC { // create the manifest final Manifest manifest = new Manifest(); final java.util.jar.Attributes atrs = manifest.getMainAttributes(); - atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION,"1.2"); + atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2"); - final Map map = manifest.getEntries(); + final Map map = manifest.getEntries(); // create manifest - Enumeration classes = _bcelClasses.elements(); final String now = (new Date()).toString(); final java.util.jar.Attributes.Name dateAttr = new java.util.jar.Attributes.Name("Date"); - while (classes.hasMoreElements()) { - final JavaClass clazz = (JavaClass)classes.nextElement(); - final String className = clazz.getClassName().replace('.','/'); - final java.util.jar.Attributes attr = new java.util.jar.Attributes(); - attr.put(dateAttr, now); - map.put(className+".class", attr); - } final File jarFile = new File(_destDir, _jarFileName); final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest); - classes = _bcelClasses.elements(); - while (classes.hasMoreElements()) { - final JavaClass clazz = (JavaClass)classes.nextElement(); - final String className = clazz.getClassName().replace('.','/'); - jos.putNextEntry(new JarEntry(className+".class")); + + for (JavaClass clazz : _bcelClasses) { + final String className = clazz.getClassName().replace('.', '/'); + final java.util.jar.Attributes attr = new java.util.jar.Attributes(); + attr.put(dateAttr, now); + map.put(className + ".class", attr); + jos.putNextEntry(new JarEntry(className + ".class")); final ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); // dump() closes it's output stream out.writeTo(jos); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java index 164c220d27f..37a346e9ea1 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java @@ -165,14 +165,14 @@ public final class TemplatesImpl implements Templates, Serializable { }; static final class TransletClassLoader extends ClassLoader { - private final Map _loadedExternalExtensionFunctions; + private final Map> _loadedExternalExtensionFunctions; TransletClassLoader(ClassLoader parent) { super(parent); _loadedExternalExtensionFunctions = null; } - TransletClassLoader(ClassLoader parent,Map mapEF) { + TransletClassLoader(ClassLoader parent, Map> mapEF) { super(parent); _loadedExternalExtensionFunctions = mapEF; } @@ -215,7 +215,7 @@ public final class TemplatesImpl implements Templates, Serializable { /** * Create an XSLTC template object from the translet class definition(s). */ - protected TemplatesImpl(Class[] transletClasses, String transletName, + protected TemplatesImpl(Class[] transletClasses, String transletName, Properties outputProperties, int indentNumber, TransformerFactoryImpl tfactory) { @@ -481,6 +481,7 @@ public final class TemplatesImpl implements Templates, Serializable { // the module needs access to runtime classes Module thisModule = TemplatesImpl.class.getModule(); + Arrays.asList(Constants.PKGS_USED_BY_TRANSLET_CLASSES).forEach(p -> { thisModule.addExports(p, m); }); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java index c0b29dbf0e9..e00a764e95b 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java @@ -222,7 +222,8 @@ public class TransformerFactoryImpl private boolean _useServicesMechanism; /** - * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element. + * protocols allowed for external references set by the stylesheet + * processing instruction, Import and Include element. */ private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT; /** @@ -240,7 +241,7 @@ public class TransformerFactoryImpl // Unmodifiable view of external extension function from xslt compiler // It will be populated by user-specified extension functions during the // type checking - private Map _xsltcExtensionFunctions; + private Map> _xsltcExtensionFunctions; CatalogResolver _catalogUriResolver; CatalogFeatures _catalogFeatures; @@ -251,6 +252,8 @@ public class TransformerFactoryImpl String _catalogPrefer = null; String _catalogResolve = null; + int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT; + /** * javax.xml.transform.sax.TransformerFactory implementation. */ @@ -283,7 +286,7 @@ public class TransformerFactoryImpl _xsltcExtensionFunctions = null; } - public Map getExternalExtensionsMap() { + public Map> getExternalExtensionsMap() { return _xsltcExtensionFunctions; } @@ -367,6 +370,8 @@ public class TransformerFactoryImpl return _catalogResolve; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { return buildCatalogFeatures(); + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + return _cdataChunkSize; } /** Check to see if the property is managed by the security manager **/ @@ -507,6 +512,9 @@ public class TransformerFactoryImpl _catalogResolve = (String) value; cfBuilder = CatalogFeatures.builder().with(Feature.RESOLVE, _catalogResolve); return; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize); + return; } if (_xmlSecurityManager != null && @@ -896,10 +904,10 @@ public class TransformerFactoryImpl transletName = _packageName + "." + transletName; try { - final Class clazz = ObjectFactory.findProviderClass(transletName, true); + final Class clazz = ObjectFactory.findProviderClass(transletName, true); resetTransientAttributes(); - templates = new TemplatesImpl(new Class[]{clazz}, transletName, null, _indentNumber, this); + templates = new TemplatesImpl(new Class[]{clazz}, transletName, null, _indentNumber, this); if (_uriResolver != null) { templates.setURIResolver(_uriResolver); } diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java index 97de2fdfbdf..23da98ea4eb 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java @@ -230,6 +230,7 @@ public final class TransformerImpl extends Transformer // Catalog is enabled by default boolean _useCatalog = true; + int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT; /** * This class wraps an ErrorListener into a MessageHandler in order to @@ -284,6 +285,9 @@ public final class TransformerImpl extends Transformer _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing); _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager); + _cdataChunkSize = JdkXmlUtils.getValue(_tfactory.getAttribute(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); + _readerManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, _cdataChunkSize); _useCatalog = _tfactory.getFeature(XMLConstants.USE_CATALOG); if (_useCatalog) { diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java index bf477fc364f..a6f89185efd 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java @@ -137,13 +137,11 @@ public final class Util { reader.setFeature ("http://xml.org/sax/features/namespace-prefixes",false); - try { - reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, - xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD)); - } catch (SAXNotRecognizedException e) { - XMLSecurityManager.printWarning(reader.getClass().getName(), - XMLConstants.ACCESS_EXTERNAL_DTD, e); - } + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD, + xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true); + + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false); String lastProperty = ""; try { diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java index 22e286948b9..f43b982ba27 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java @@ -292,7 +292,8 @@ public class DOMConfigurationImpl extends ParserConfigurationSettings JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -368,6 +369,8 @@ public class DOMConfigurationImpl extends ParserConfigurationSettings for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java index 026bcf8635b..12bb248a40d 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java @@ -144,6 +144,8 @@ public class PropertyManager { for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { supportedProps.put(f.getPropertyName(), null); } + + supportedProps.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } private void initWriterProps(){ diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java index a13dfbe1d0d..76bbc572b72 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java @@ -1041,14 +1041,14 @@ public class XML11EntityScanner * * @param delimiter The string that signifies the end of the character * data to be scanned. - * @param data The data structure to fill. + * @param buffer The data structure to fill. + * @param chunkLimit the size limit of the data to be scanned * * @return Returns true if there is more data to scan, false otherwise. * * @throws IOException Thrown if i/o error occurs. - * @throws EOFException Thrown on end of file. */ - protected boolean scanData(String delimiter, XMLStringBuffer buffer) + protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit) throws IOException { boolean done = false; @@ -1152,82 +1152,50 @@ public class XML11EntityScanner } // iterate over buffer looking for delimiter - if (external) { - OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (c == charAt0) { - // looks like we just hit the delimiter - int delimOffset = fCurrentEntity.position - 1; - for (int i = 1; i < delimLen; i++) { - if (fCurrentEntity.position == fCurrentEntity.count) { - fCurrentEntity.position -= i; - break OUTER; - } - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (delimiter.charAt(i) != c) { - fCurrentEntity.position--; - break; - } - } - if (fCurrentEntity.position == delimOffset + delimLen) { - done = true; - break; - } - } - else if (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) { - fCurrentEntity.position--; - break; - } - // In external entities control characters cannot appear - // as literals so do not skip over them. - else if (!XML11Char.isXML11ValidLiteral(c)) { - fCurrentEntity.position--; - int length = fCurrentEntity.position - offset; - fCurrentEntity.columnNumber += length - newlines; - checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); - buffer.append(fCurrentEntity.ch, offset, length); - return true; - } - } - } - else { - OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (c == charAt0) { - // looks like we just hit the delimiter - int delimOffset = fCurrentEntity.position - 1; - for (int i = 1; i < delimLen; i++) { - if (fCurrentEntity.position == fCurrentEntity.count) { - fCurrentEntity.position -= i; - break OUTER; - } - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (delimiter.charAt(i) != c) { - fCurrentEntity.position--; - break; - } + OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { + c = fCurrentEntity.ch[fCurrentEntity.position++]; + if (c == charAt0) { + // looks like we just hit the delimiter + int delimOffset = fCurrentEntity.position - 1; + for (int i = 1; i < delimLen; i++) { + if (fCurrentEntity.position == fCurrentEntity.count) { + fCurrentEntity.position -= i; + break OUTER; } - if (fCurrentEntity.position == delimOffset + delimLen) { - done = true; + c = fCurrentEntity.ch[fCurrentEntity.position++]; + if (delimiter.charAt(i) != c) { + fCurrentEntity.position--; break; } - } - else if (c == '\n') { - fCurrentEntity.position--; + } + if (fCurrentEntity.position == delimOffset + delimLen) { + done = true; break; - } - // Control characters are allowed to appear as literals - // in internal entities. - else if (!XML11Char.isXML11Valid(c)) { - fCurrentEntity.position--; - int length = fCurrentEntity.position - offset; - fCurrentEntity.columnNumber += length - newlines; - checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); - buffer.append(fCurrentEntity.ch, offset, length); - return true; - } + } + } + else if ((external && (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028)) + || (!external && c == '\n')) { + fCurrentEntity.position--; + break; + } + // In external entities control characters cannot appear + // as literals so do not skip over them. + else if ((external && !XML11Char.isXML11ValidLiteral(c)) + // Control characters are allowed to appear as literals in internal entities. + || (!external && !XML11Char.isXML11Valid(c))) { + fCurrentEntity.position--; + int length = fCurrentEntity.position - offset; + fCurrentEntity.columnNumber += length - newlines; + checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); + buffer.append(fCurrentEntity.ch, offset, length); + return true; + } + if (chunkLimit > 0 && + (buffer.length + fCurrentEntity.position - offset) >= chunkLimit) { + break; } } + int length = fCurrentEntity.position - offset; fCurrentEntity.columnNumber += length - newlines; checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); @@ -1236,8 +1204,10 @@ public class XML11EntityScanner } buffer.append(fCurrentEntity.ch, offset, length); - // return true if string was skipped - } while (!done); + if (chunkLimit > 0 && buffer.length >= chunkLimit) { + break; + } + } while (!done && chunkLimit == 0); return !done; } // scanData(String,XMLString) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java index ca6f5572fd6..6e3547cdc83 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java @@ -388,7 +388,7 @@ implements XMLDTDScanner, XMLComponent, XMLEntityHandler { return false; fStringBuffer.clear(); - while (fEntityScanner.scanData("]", fStringBuffer)) { + while (fEntityScanner.scanData("]", fStringBuffer, 0)) { int c = fEntityScanner.peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java index 6cd1fd0435c..04b228026f6 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java @@ -200,7 +200,8 @@ public class XMLDocumentFragmentScannerImpl JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ @@ -212,7 +213,8 @@ public class XMLDocumentFragmentScannerImpl null, null, null, - null + null, + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; @@ -269,6 +271,9 @@ public class XMLDocumentFragmentScannerImpl /** SubScanner state: inside scanContent method. */ protected boolean fInScanContent = false; protected boolean fLastSectionWasCData = false; + protected boolean fCDataStart = false; + protected boolean fInCData = false; + protected boolean fCDataEnd = false; protected boolean fLastSectionWasEntityReference = false; protected boolean fLastSectionWasCharacterData = false; @@ -318,6 +323,11 @@ public class XMLDocumentFragmentScannerImpl /** Xerces Feature: Disallow doctype declaration. */ protected boolean fDisallowDoctype = false; + /** + * CDATA chunk size limit + */ + private int fChunkSize; + /** * comma-delimited list of protocols that are allowed for the purpose * of accessing external dtd or entity references @@ -490,12 +500,18 @@ public class XMLDocumentFragmentScannerImpl //therefore we don't need to take care of anything here. So Just break; break; case XMLStreamConstants.CDATA: - fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity); - fDocumentHandler.startCDATA(null); - //xxx: check if CDATA values comes from getCharacterData() function + fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity); + if (fCDataStart) { + fDocumentHandler.startCDATA(null); + fCDataStart = false; + fInCData = true; + } + fDocumentHandler.characters(getCharacterData(),null); - fDocumentHandler.endCDATA(null); - //System.out.println(" in CDATA of the XMLNSDocumentScannerImpl"); + if (fCDataEnd) { + fDocumentHandler.endCDATA(null); + fCDataEnd = false; + } break; case XMLStreamConstants.NOTATION_DECLARATION : break; @@ -603,6 +619,8 @@ public class XMLDocumentFragmentScannerImpl fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fStrictURI = componentManager.getFeature(STANDARD_URI_CONFORMANT, false); + fChunkSize = JdkXmlUtils.getValue(componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); resetCommon(); //fEntityManager.test(); @@ -647,6 +665,8 @@ public class XMLDocumentFragmentScannerImpl fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER); + fChunkSize = JdkXmlUtils.getValue(propertyManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); resetCommon(); } // reset(XMLComponentManager) @@ -1665,34 +1685,11 @@ public class XMLDocumentFragmentScannerImpl while (true) { //scanData will fill the contentBuffer - if (!fEntityScanner.scanData("]]>", contentBuffer)) { + if (!fEntityScanner.scanData("]]>", contentBuffer, fChunkSize)) { + fInCData = false; + fCDataEnd = true; + fMarkupDepth--; break ; - /** We dont need all this code if we pass ']]>' as delimeter.. - * int brackets = 2; - * while (fEntityScanner.skipChar(']')) { - * brackets++; - * } - * - * //When we find more than 2 square brackets - * if (fDocumentHandler != null && brackets > 2) { - * //we dont need to clear the buffer.. - * //contentBuffer.clear(); - * for (int i = 2; i < brackets; i++) { - * contentBuffer.append(']'); - * } - * fDocumentHandler.characters(contentBuffer, null); - * } - * - * if (fEntityScanner.skipChar('>')) { - * break; - * } - * if (fDocumentHandler != null) { - * //we dont need to clear the buffer now.. - * //contentBuffer.clear(); - * contentBuffer.append("]]"); - * fDocumentHandler.characters(contentBuffer, null); - * } - **/ } else { int c = fEntityScanner.peekChar(); if (c != -1 && isInvalidLiteral(c)) { @@ -1705,6 +1702,9 @@ public class XMLDocumentFragmentScannerImpl new Object[]{Integer.toString(c,16)}); fEntityScanner.scanChar(null); } + } else { + //CData partially returned due to the size limit + break; } //by this time we have also read surrogate contents if any... if (fDocumentHandler != null) { @@ -1712,16 +1712,6 @@ public class XMLDocumentFragmentScannerImpl } } } - fMarkupDepth--; - - if (fDocumentHandler != null && contentBuffer.length > 0) { - //fDocumentHandler.characters(contentBuffer, null); - } - - // call handler - if (fDocumentHandler != null) { - //fDocumentHandler.endCDATA(null); - } return true; @@ -2635,6 +2625,7 @@ public class XMLDocumentFragmentScannerImpl } setScannerState(SCANNER_STATE_COMMENT); } else if (fEntityScanner.skipString(cdata)) { + fCDataStart = true; setScannerState(SCANNER_STATE_CDATA ); } else if (!scanForDoctypeHook()) { reportFatalError("MarkupNotRecognizedInContent", @@ -3015,9 +3006,11 @@ public class XMLDocumentFragmentScannerImpl //xxx: What if CDATA is the first event //<>]]>append - //we should not clear the buffer only when the last state was either SCANNER_STATE_REFERENCE or + //we should not clear the buffer only when the last state was + //either SCANNER_STATE_REFERENCE or //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE - if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ + if(fIsCoalesce && ( fLastSectionWasEntityReference || + fLastSectionWasCData || fLastSectionWasCharacterData)){ fLastSectionWasCData = true ; fLastSectionWasEntityReference = false; fLastSectionWasCharacterData = false; @@ -3026,7 +3019,7 @@ public class XMLDocumentFragmentScannerImpl fContentBuffer.clear(); } fUsebuffer = true; - //CDATA section is completely read in all the case. + //CDATA section is read up to the chunk size limit scanCDATASection(fContentBuffer , true); setScannerState(SCANNER_STATE_CONTENT); //1. if fIsCoalesce is set to true we set the variable fLastSectionWasCData to true @@ -3036,13 +3029,16 @@ public class XMLDocumentFragmentScannerImpl //2. Check if application has set for reporting CDATA event //3. if the application has neither set the fIsCoalesce to true nor fReportCdataEvent //return the cdata event as characters. - if(fIsCoalesce){ + if (fIsCoalesce) { fLastSectionWasCData = true ; //there might be more data to coalesce. continue; - }else if(fReportCdataEvent){ + } else if(fReportCdataEvent) { + if (!fCDataEnd) { + setScannerState(SCANNER_STATE_CDATA); + } return XMLEvent.CDATA; - } else{ + } else { return XMLEvent.CHARACTERS; } } @@ -3051,9 +3047,11 @@ public class XMLDocumentFragmentScannerImpl fMarkupDepth++; foundBuiltInRefs = false; - //we should not clear the buffer only when the last state was either CDATA or + //we should not clear the buffer only when the last state was + //either CDATA or //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE - if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ + if(fIsCoalesce && ( fLastSectionWasEntityReference || + fLastSectionWasCData || fLastSectionWasCharacterData)){ //fLastSectionWasEntityReference or fLastSectionWasCData are only //used when fIsCoalesce is set to true. fLastSectionWasEntityReference = true ; diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java index 7189b1ba7a9..1c7cc3d6407 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java @@ -968,9 +968,11 @@ public class XMLDocumentScannerImpl case SCANNER_STATE_CONTENT: { reportFatalError("ContentIllegalInProlog", null); fEntityScanner.scanChar(null); + return -1; } case SCANNER_STATE_REFERENCE: { reportFatalError("ReferenceIllegalInProlog", null); + return -1; } /** diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java index 5ed41e82fc8..eb16a26a85d 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java @@ -217,7 +217,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver { JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ @@ -232,7 +233,8 @@ public class XMLEntityManager implements XMLComponent, XMLEntityResolver { null, null, null, - null + null, + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; private static final String XMLEntity = "[xml]".intern(); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java index 09d006065d8..36c23007951 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java @@ -1350,13 +1350,15 @@ public class XMLEntityScanner implements XMLLocator { * @param delimiter The string that signifies the end of the character * data to be scanned. * @param buffer The XMLStringBuffer to fill. + * @param chunkLimit the size limit of the data to be scanned. Zero by default + * indicating no limit. * * @return Returns true if there is more data to scan, false otherwise. * * @throws IOException Thrown if i/o error occurs. * @throws EOFException Thrown on end of file. */ - protected boolean scanData(String delimiter, XMLStringBuffer buffer) + protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit) throws IOException { boolean done = false; @@ -1505,6 +1507,10 @@ public class XMLEntityScanner implements XMLLocator { buffer.append(fCurrentEntity.ch, offset, length); return true; } + if (chunkLimit > 0 && + (buffer.length + fCurrentEntity.position - offset) >= chunkLimit) { + break; + } } int length = fCurrentEntity.position - offset; fCurrentEntity.columnNumber += length - newlines; @@ -1520,7 +1526,10 @@ public class XMLEntityScanner implements XMLLocator { print(); System.out.println(" -> " + done); } - } while (!done); + if (chunkLimit > 0 && buffer.length >= chunkLimit) { + break; + } + } while (!done && chunkLimit == 0); return !done; } // scanData(String, XMLStringBuffer) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java index dbd4597f431..51ec8ba1376 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java @@ -760,7 +760,7 @@ public abstract class XMLScanner // since scanData appends the parsed data to the buffer passed // a while loop would append the whole of parsed data to the buffer(data:XMLStringBuffer) //until all of the data is buffered. - if (fEntityScanner.scanData("?>", data)) { + if (fEntityScanner.scanData("?>", data, 0)) { do { int c = fEntityScanner.peekChar(); if (c != -1) { @@ -772,7 +772,7 @@ public abstract class XMLScanner fEntityScanner.scanChar(null); } } - } while (fEntityScanner.scanData("?>", data)); + } while (fEntityScanner.scanData("?>", data, 0)); } } // scanPIData(String,XMLString) @@ -797,7 +797,7 @@ public abstract class XMLScanner // text // REVISIT: handle invalid character, eof text.clear(); - while (fEntityScanner.scanData("--", text)) { + while (fEntityScanner.scanData("--", text, 0)) { int c = fEntityScanner.peekChar(); //System.out.println( "XMLScanner#scanComment#text.toString() == " + text.toString() ); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java index d9425cccd70..6aeb0f46fae 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java @@ -250,7 +250,8 @@ XSLoader, DOMConfiguration { JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; // Data @@ -282,7 +283,7 @@ XSLoader, DOMConfiguration { private XSDDescription fXSDDescription = new XSDDescription(); private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT; - private WeakHashMap fJAXPCache; + private WeakHashMap fJAXPCache; private Locale fLocale = Locale.getDefault(); // XSLoader attributes @@ -366,7 +367,7 @@ XSLoader, DOMConfiguration { } fCMBuilder = builder; fSchemaHandler = new XSDHandler(fGrammarBucket); - fJAXPCache = new WeakHashMap(); + fJAXPCache = new WeakHashMap<>(); fSettingsChanged = true; } @@ -377,7 +378,7 @@ XSLoader, DOMConfiguration { * are recognized. */ public String[] getRecognizedFeatures() { - return (String[])(RECOGNIZED_FEATURES.clone()); + return RECOGNIZED_FEATURES.clone(); } // getRecognizedFeatures(): String[] /** @@ -419,7 +420,7 @@ XSLoader, DOMConfiguration { * are recognized. */ public String[] getRecognizedProperties() { - return (String[])(RECOGNIZED_PROPERTIES.clone()); + return RECOGNIZED_PROPERTIES.clone(); } // getRecognizedProperties(): String[] /** @@ -568,7 +569,7 @@ XSLoader, DOMConfiguration { desc.setBaseSystemId(source.getBaseSystemId()); desc.setLiteralSystemId( source.getSystemId()); // none of the other fields make sense for preparsing - Map locationPairs = new HashMap(); + Map locationPairs = new HashMap<>(); // Process external schema location properties. // We don't call tokenizeSchemaLocationStr here, because we also want // to check whether the values are valid URI. @@ -665,7 +666,7 @@ XSLoader, DOMConfiguration { // add external schema locations to the location pairs public static void processExternalHints(String sl, String nsl, - Map locations, + Map locations, XMLErrorReporter er) { if (sl != null) { try { @@ -694,9 +695,10 @@ XSLoader, DOMConfiguration { if (nsl != null) { try { // similarly for no ns schema location property - XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); + XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl( + SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); attrDecl.fType.validate(nsl, null, null); - LocationArray la = ((LocationArray)locations.get(XMLSymbols.EMPTY_STRING)); + LocationArray la = locations.get(XMLSymbols.EMPTY_STRING); if(la == null) { la = new LocationArray(); locations.put(XMLSymbols.EMPTY_STRING, la); @@ -763,14 +765,14 @@ XSLoader, DOMConfiguration { return; } - Class componentType = fJAXPSource.getClass().getComponentType(); + Class componentType = fJAXPSource.getClass().getComponentType(); XMLInputSource xis = null; String sid = null; if (componentType == null) { // Not an array if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { - SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); + SchemaGrammar g = fJAXPCache.get(fJAXPSource); if (g != null) { fGrammarBucket.putGrammar(g); return; @@ -823,7 +825,7 @@ XSLoader, DOMConfiguration { for (int i = 0; i < objArr.length; i++) { if (objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { - SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); + SchemaGrammar g = fJAXPCache.get(objArr[i]); if (g != null) { fGrammarBucket.putGrammar(g); continue; diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java index c7e5dc79327..05031e1f590 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java @@ -344,13 +344,14 @@ public class XMLSchemaValidator JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null}; + null, null, null, null, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; // this is the number of valuestores of each kind // we expect an element to have. It's almost @@ -358,10 +359,14 @@ public class XMLSchemaValidator protected static final int ID_CONSTRAINT_NUM = 1; // xsi:* attribute declarations - static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); - static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); - static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); - static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); + static final XSAttributeDecl XSI_TYPE = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); + static final XSAttributeDecl XSI_NIL = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); + static final XSAttributeDecl XSI_SCHEMALOCATION = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); + static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); // // Data diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java index d01f4b01b58..3b4e5f0b61a 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java @@ -336,7 +336,8 @@ public class SchemaParsingConfig extends BasicParserConfiguration JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -368,6 +369,7 @@ public class SchemaParsingConfig extends BasicParserConfiguration fValidationManager = new ValidationManager(); fProperties.put(VALIDATION_MANAGER, fValidationManager); + fProperties.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); fVersionDetector = new XMLVersionDetector(); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java index d275e85c218..e6e3c64676f 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java @@ -350,7 +350,7 @@ public class XSDHandler { // This map's job is to act as a link between the Schema Element and its // XSDocumentInfo object. - private Map fDoc2XSDocumentMap = new HashMap(); + private Map fDoc2XSDocumentMap = new HashMap<>(); // map between elements and the XSDocumentInfo // objects that correspond to the documents being redefined. @@ -1104,10 +1104,12 @@ public class XSDHandler { fSchemaGrammarDescription.setTargetNamespace(callerTNS); boolean alreadyTraversed = false; - XMLInputSource schemaSource = resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true); + XMLInputSource schemaSource = + resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true); if (fNamespaceGrowth && refType == XSDDescription.CONTEXT_INCLUDE) { try { - final String schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); + final String schemaId = XMLEntityManager.expandSystemId( + schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); alreadyTraversed = sg.getDocumentLocations().contains(schemaId); } catch(MalformedURIException e) { @@ -1133,10 +1135,11 @@ public class XSDHandler { // To handle mutual s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { - newSchemaInfo = newSchemaRoot == null ? null : (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); + newSchemaInfo = newSchemaRoot == null ? null : fDoc2XSDocumentMap.get(newSchemaRoot); } else { - newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription, importCollision); + newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, + fSchemaGrammarDescription, importCollision); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && @@ -3552,9 +3555,11 @@ public class XSDHandler { // than checking its value. Don't set the ERROR_HANDLER // or LOCALE properties unless they've actually changed. if (fErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) { - fSchemaParser.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); + fSchemaParser.setProperty(ERROR_HANDLER, + (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); if (fAnnotationValidator != null) { - fAnnotationValidator.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); + fAnnotationValidator.setProperty(ERROR_HANDLER, + (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); } } if (fLocale != fSchemaParser.getProperty(LOCALE)) { @@ -3567,7 +3572,8 @@ public class XSDHandler { catch (XMLConfigurationException e) {} try { - fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); + fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, + fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); } catch (XMLConfigurationException e) {} try { @@ -3601,13 +3607,16 @@ public class XSDHandler { } } catch (XMLConfigurationException e) {} - fSecurityPropertyMgr = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); + fSecurityPropertyMgr = (XMLSecurityPropertyManager) + componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); //Passing on the setting to the parser fSchemaParser.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr); - fAccessExternalDTD = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); - fAccessExternalSchema = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); + fAccessExternalDTD = fSecurityPropertyMgr.getValue( + XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); + fAccessExternalSchema = fSecurityPropertyMgr.getValue( + XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); // Passing the Catalog settings to the parser fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG); @@ -3620,9 +3629,16 @@ public class XSDHandler { fResolve = (String)componentManager.getProperty(JdkXmlUtils.CATALOG_RESOLVE); for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { - fSchemaParser.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); - fEntityManager.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); + fSchemaParser.setProperty(f.getPropertyName(), + componentManager.getProperty(f.getPropertyName())); + fEntityManager.setProperty(f.getPropertyName(), + componentManager.getProperty(f.getPropertyName())); } + + fSchemaParser.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); + fEntityManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); } // reset(XMLComponentManager) @@ -3635,11 +3651,10 @@ public class XSDHandler { for (int i = 0; i < fLocalElemStackPos; i++) { Element currElem = fLocalElementDecl[i]; - //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem)); - //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getRoot(DOMUtil.getDocument(currElem))); XSDocumentInfo currSchema = fLocalElementDecl_schema[i]; SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); - fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); + fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, + currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); // If it's an empty particle, remove it from the containing component. if (fParticle[i].fType == XSParticleDecl.PARTICLE_EMPTY) { XSModelGroupImpl group = null; @@ -4065,7 +4080,8 @@ public class XSDHandler { Element decl, XSDocumentInfo decl_Doc) { if (DEBUG_NODE_POOL) { - System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaElement).hashCode()); + System.out.println("DOCUMENT NS:" + currSchema.fTargetNamespace + " hashcode:" + + ((Object)currSchema.fSchemaElement).hashCode()); } Object temp = decl_Doc; if (temp == null) { @@ -4091,7 +4107,8 @@ public class XSDHandler { // returns whether more than s occur in children of elem private boolean nonAnnotationContent(Element elem) { - for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { + for(Element child = DOMUtil.getFirstChildElement(elem); child != null; + child = DOMUtil.getNextSiblingElement(child)) { if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; } return false; diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java index c400bb5360d..ade0b6ff691 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. */ -/* + /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. @@ -17,7 +17,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.sun.org.apache.xerces.internal.jaxp.validation; import com.sun.org.apache.xerces.internal.impl.Constants; @@ -47,7 +46,8 @@ import jdk.xml.internal.JdkXmlUtils; import org.xml.sax.SAXException; /** - *

      A validator helper for StreamSources.

      + *

      + * A validator helper for StreamSources.

      * * @author Michael Glavassevich, IBM * @author Sunitha Reddy @@ -55,74 +55,98 @@ import org.xml.sax.SAXException; final class StreamValidatorHelper implements ValidatorHelper { // feature identifiers - - /** Feature identifier: parser settings. */ - private static final String PARSER_SETTINGS = - Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; + /** + * Feature identifier: parser settings. + */ + private static final String PARSER_SETTINGS + = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; // property identifiers + /** + * Property identifier: entity resolver. + */ + private static final String ENTITY_RESOLVER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; - /** Property identifier: entity resolver. */ - private static final String ENTITY_RESOLVER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; + /** + * Property identifier: error handler. + */ + private static final String ERROR_HANDLER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; - /** Property identifier: error handler. */ - private static final String ERROR_HANDLER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; + /** + * Property identifier: error reporter. + */ + private static final String ERROR_REPORTER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; - /** Property identifier: error reporter. */ - private static final String ERROR_REPORTER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; + /** + * Property identifier: XML Schema validator. + */ + private static final String SCHEMA_VALIDATOR + = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; - /** Property identifier: XML Schema validator. */ - private static final String SCHEMA_VALIDATOR = - Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; + /** + * Property identifier: symbol table. + */ + private static final String SYMBOL_TABLE + = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; - /** Property identifier: symbol table. */ - private static final String SYMBOL_TABLE = - Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; + /** + * Property identifier: validation manager. + */ + private static final String VALIDATION_MANAGER + = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; - /** Property identifier: validation manager. */ - private static final String VALIDATION_MANAGER = - Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; + private static final String DEFAULT_TRANSFORMER_IMPL + = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; - private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; - - /** Property id: security manager. */ - private static final String SECURITY_MANAGER = - Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; + /** + * Property id: security manager. + */ + private static final String SECURITY_MANAGER + = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; // // Data // + /** + * SoftReference to parser configuration. * + */ + private SoftReference fConfiguration = new SoftReference<>(null); - /** SoftReference to parser configuration. **/ - private SoftReference fConfiguration = new SoftReference(null); - - /** Schema validator. **/ + /** + * Schema validator. * + */ private com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator fSchemaValidator; - /** Component manager. **/ + /** + * Component manager. * + */ private XMLSchemaValidatorComponentManager fComponentManager; private ValidatorHandlerImpl handler = null; public StreamValidatorHelper(XMLSchemaValidatorComponentManager componentManager) { fComponentManager = componentManager; - fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator) fComponentManager.getProperty(SCHEMA_VALIDATOR); + fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator) + fComponentManager.getProperty(SCHEMA_VALIDATOR); } public void validate(Source source, Result result) - throws SAXException, IOException { + throws SAXException, IOException { if (result == null || result instanceof StreamResult) { final StreamSource streamSource = (StreamSource) source; - TransformerHandler identityTransformerHandler ; + TransformerHandler identityTransformerHandler; - if( result!=null ) { + if (result != null) { try { - SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ? - (SAXTransformerFactory)SAXTransformerFactory.newInstance() - : (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StreamValidatorHelper.class.getClassLoader()); + SAXTransformerFactory tf = fComponentManager.getFeature( + Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ? + (SAXTransformerFactory) SAXTransformerFactory.newInstance() : + (SAXTransformerFactory) TransformerFactory.newInstance( + DEFAULT_TRANSFORMER_IMPL, + StreamValidatorHelper.class.getClassLoader()); identityTransformerHandler = tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new TransformerFactoryConfigurationError(e); @@ -133,13 +157,14 @@ final class StreamValidatorHelper implements ValidatorHelper { identityTransformerHandler.setResult(result); } - XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null, false); + XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), + streamSource.getSystemId(), null, false); input.setByteStream(streamSource.getInputStream()); input.setCharacterStream(streamSource.getReader()); // Gets the parser configuration. We'll create and initialize a new one, if we // haven't created one before or if the previous one was garbage collected. - XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get(); + XMLParserConfiguration config = fConfiguration.get(); if (config == null) { config = initialize(); } @@ -155,18 +180,17 @@ final class StreamValidatorHelper implements ValidatorHelper { try { config.parse(input); - } - catch (XMLParseException e) { + } catch (XMLParseException e) { throw Util.toSAXParseException(e); - } - catch (XNIException e) { + } catch (XNIException e) { throw Util.toSAXException(e); } return; } - throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), + throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage( + fComponentManager.getLocale(), "SourceResultMismatch", - new Object [] {source.getClass().getName(), result.getClass().getName()})); + new Object[]{source.getClass().getName(), result.getClass().getName()})); } private XMLParserConfiguration initialize() { @@ -197,7 +221,10 @@ final class StreamValidatorHelper implements ValidatorHelper { // Passing on the CatalogFeatures settings JdkXmlUtils.catalogFeaturesConfig2Config(fComponentManager, config); - fConfiguration = new SoftReference(config); + config.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + fComponentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); + + fConfiguration = new SoftReference<>(config); return config; } diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java index 96b9125c9ad..d47f56a2bf2 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java @@ -165,6 +165,8 @@ public final class XMLSchemaFactory extends SchemaFactory { for (Feature f : Feature.values()) { fXMLSchemaLoader.setProperty(f.getPropertyName(), null); } + + fXMLSchemaLoader.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } /** diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java index 70426b826b2..17a8c4094f9 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java @@ -48,6 +48,7 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLComponent; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; import javax.xml.catalog.CatalogFeatures; +import jdk.xml.internal.JdkXmlUtils; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; @@ -311,6 +312,9 @@ final class XMLSchemaValidatorComponentManager extends ParserConfigurationSettin for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), grammarContainer.getProperty(f.getPropertyName())); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + grammarContainer.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); } /** diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java index aa95ac2e6ba..708d00faa52 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java @@ -345,7 +345,8 @@ public class DTDConfiguration JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -429,6 +430,8 @@ public class DTDConfiguration for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable,XMLGrammarPool) // diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java index 8db7bdc5bcb..3d27c713c38 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java @@ -328,7 +328,8 @@ public class NonValidatingConfiguration JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -391,6 +392,8 @@ public class NonValidatingConfiguration for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable,XMLGrammarPool) // diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java index 61529aca688..f56467532b6 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java @@ -561,7 +561,8 @@ public class XML11Configuration extends ParserConfigurationSettings JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -629,6 +630,8 @@ public class XML11Configuration extends ParserConfigurationSettings fProperties.put(f.getPropertyName(), null); } + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); + fConfigUpdated = false; } // (SymbolTable,XMLGrammarPool) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java index 3bf0b43bff0..60884b043bc 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java @@ -81,6 +81,8 @@ public class XMLReaderManager { private boolean _useCatalog; private CatalogFeatures _catalogFeatures; + private int _cdataChunkSize; + /** * Hidden constructor */ @@ -173,13 +175,12 @@ public class XMLReaderManager { } } - try { - //reader is cached, but this property might have been reset - reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); - } catch (SAXException se) { - XMLSecurityManager.printWarning(reader.getClass().getName(), - XMLConstants.ACCESS_EXTERNAL_DTD, se); - } + //reader is cached, but this property might have been reset + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD, + _accessExternalDTD, true); + + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + _cdataChunkSize, false); String lastProperty = ""; try { @@ -278,7 +279,8 @@ public class XMLReaderManager { _xmlSecurityManager = (XMLSecurityManager)value; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { _catalogFeatures = (CatalogFeatures)value; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize); } - } } diff --git a/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java b/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java index c6cd3f4b2c4..7611ceb2b75 100644 --- a/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java +++ b/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java @@ -25,6 +25,7 @@ package jdk.xml.internal; +import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager; import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; @@ -39,6 +40,7 @@ import org.xml.sax.XMLReader; * Constants for use across JAXP processors. */ public class JdkXmlUtils { + /** * Catalog features */ @@ -58,11 +60,63 @@ public class JdkXmlUtils { /** * Default value of USE_CATALOG. This will read the System property */ - public static final boolean USE_CATALOG_DEFAULT = - SecuritySupport.getJAXPSystemProperty(SP_USE_CATALOG, true); + public static final boolean USE_CATALOG_DEFAULT + = SecuritySupport.getJAXPSystemProperty(Boolean.class, SP_USE_CATALOG, "true"); + + /** + * JDK features (will be consolidated in the next major feature revamp + */ + public final static String CDATA_CHUNK_SIZE = "jdk.xml.cdataChunkSize"; + public static final int CDATA_CHUNK_SIZE_DEFAULT + = SecuritySupport.getJAXPSystemProperty(Integer.class, CDATA_CHUNK_SIZE, "0"); + + /** + * Returns the value. + * + * @param value the specified value + * @param defValue the default value + * @return the value, or the default value if the value is null + */ + public static int getValue(Object value, int defValue) { + if (value == null) { + return defValue; + } + + if (value instanceof Number) { + return ((Number) value).intValue(); + } else if (value instanceof String) { + return Integer.parseInt(String.valueOf(value)); + } else { + throw new IllegalArgumentException("Unexpected class: " + + value.getClass()); + } + } + + /** + * Sets the XMLReader instance with the specified property if the the + * property is supported, ignores error if not, issues a warning if so + * requested. + * + * @param reader an XMLReader instance + * @param property the name of the property + * @param value the value of the property + * @param warn a flag indicating whether a warning should be issued + */ + public static void setXMLReaderPropertyIfSupport(XMLReader reader, String property, + Object value, boolean warn) { + try { + reader.setProperty(property, value); + } catch (SAXNotRecognizedException | SAXNotSupportedException e) { + if (warn) { + XMLSecurityManager.printWarning(reader.getClass().getName(), + property, e); + } + } + } /** * Returns the value of a Catalog feature by the property name. + * * @param features a CatalogFeatures instance * @param name the name of a Catalog feature * @return the value of a Catalog feature, null if the name does not match @@ -106,10 +160,9 @@ public class JdkXmlUtils { return builder.build(); } - /** - * Passing on the CatalogFeatures settings from one Xerces configuration object - * to another. + * Passing on the CatalogFeatures settings from one Xerces configuration + * object to another. * * @param config1 a Xerces configuration object * @param config2 a Xerces configuration object @@ -120,14 +173,13 @@ public class JdkXmlUtils { boolean useCatalog = config1.getFeature(XMLConstants.USE_CATALOG); try { config2.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); - } - catch (XMLConfigurationException e) { + } catch (XMLConfigurationException e) { supportCatalog = false; } if (supportCatalog && useCatalog) { try { - for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { + for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { config2.setProperty(f.getPropertyName(), config1.getProperty(f.getPropertyName())); } } catch (XMLConfigurationException e) { @@ -137,8 +189,8 @@ public class JdkXmlUtils { } /** - * Passing on the CatalogFeatures settings from a Xerces configuration object - * to an XMLReader. + * Passing on the CatalogFeatures settings from a Xerces configuration + * object to an XMLReader. * * @param config a Xerces configuration object * @param reader an XMLReader @@ -148,14 +200,13 @@ public class JdkXmlUtils { boolean useCatalog = config.getFeature(XMLConstants.USE_CATALOG); try { reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); - } - catch (SAXNotRecognizedException | SAXNotSupportedException e) { + } catch (SAXNotRecognizedException | SAXNotSupportedException e) { supportCatalog = false; } if (supportCatalog && useCatalog) { try { - for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { + for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { reader.setProperty(f.getPropertyName(), config.getProperty(f.getPropertyName())); } } catch (SAXNotRecognizedException | SAXNotSupportedException e) { diff --git a/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java b/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java index 9f64d6e0e6c..b75a612f839 100644 --- a/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java +++ b/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java @@ -83,19 +83,26 @@ public class SecuritySupport { } /** - * Reads boolean type system property. + * Reads a system property. * + * @param the type of the property value + * @param type the type of the property value * @param propName the name of the property * @param defValue the default value * @return the value of the property, or the default value of no system * property is found */ - public static boolean getJAXPSystemProperty(String propName, boolean defValue) { + public static T getJAXPSystemProperty(Class type, String propName, String defValue) { String value = getJAXPSystemProperty(propName); if (value == null) { - return defValue; + value = defValue; } - return Boolean.parseBoolean(value); + if (Integer.class.isAssignableFrom(type)) { + return type.cast(Integer.parseInt(value)); + } else if (Boolean.class.isAssignableFrom(type)) { + return type.cast(Boolean.parseBoolean(value)); + } + return type.cast(value); } /** diff --git a/jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java b/jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java new file mode 100644 index 00000000000..d733bc704ce --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package common; + +import java.io.StringReader; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.XMLEvent; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.ext.DefaultHandler2; + +/* + * @test + * @bug 8158619 + * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest + * @run testng/othervm -DrunSecMngr=true common.CDataChunkSizeTest + * @run testng/othervm common.CDataChunkSizeTest + * @summary Verifies the support of property jdk.xml.cdataChunkSize + */ +@Listeners({jaxp.library.BasePolicy.class}) +public class CDataChunkSizeTest { + + final static String CDATA_CHUNK_SIZE = "jdk.xml.cdataChunkSize"; + final static int NO_LIMIT = 0; + + /* + * @bug 8158619 + * Verifies SAXParser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testSAX(String xml, int chunkSize, int numOfChunks, boolean withinLimit) throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader reader = spf.newSAXParser().getXMLReader(); + MyHandler handler = new MyHandler(chunkSize); + reader.setContentHandler(handler); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + + if (chunkSize > 0) { + reader.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + + reader.parse(new InputSource(new StringReader(xml))); + System.out.println("CData num of chunks:" + handler.getNumOfCDataChunks()); + System.out.println("CData size within limit:" + handler.chunkSizeWithinLimit()); + Assert.assertEquals(handler.getNumOfCDataChunks(), numOfChunks); + Assert.assertEquals(handler.chunkSizeWithinLimit(), withinLimit); + + } + + + /* + * @bug 8158619 + * Verifies StAX parser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testStAX(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { + XMLInputFactory xifactory = XMLInputFactory.newInstance(); + xifactory.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); + if (chunkSize > 0) { + xifactory.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + XMLStreamReader streamReader = xifactory.createXMLStreamReader(new StringReader(xml)); + + StringBuilder cdata = new StringBuilder(); + int numOfChunks = 0; + boolean isWithinLimit = true; + while (streamReader.hasNext()) { + int eventType = streamReader.next(); + switch (eventType) { + case XMLStreamConstants.START_ELEMENT: + debugPrint("\nElement: " + streamReader.getLocalName()); + break; + case XMLStreamConstants.CDATA: + String text = streamReader.getText(); + numOfChunks++; + if (text.length() > chunkSize) { + isWithinLimit = false; + } + debugPrint("\nCDATA: " + text.length()); + cdata.append(text); + break; + case XMLStreamConstants.CHARACTERS: + debugPrint("\nCharacters: " + streamReader.getText().length()); + break; + } + } + debugPrint("CData in single chunk:" + cdata.toString().length()); + Assert.assertEquals(numOfChunks, expectedNumOfChunks); + Assert.assertEquals(isWithinLimit, withinLimit); + } + + /* + * @bug 8158619 + * Verifies StAX parser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testEventReader(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { + XMLInputFactory xif = XMLInputFactory.newInstance(); + xif.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); + if (chunkSize > 0) { + xif.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + XMLEventReader reader = xif.createXMLEventReader(new StringReader(xml)); + + StringBuilder cdata = new StringBuilder(); + int numOfChunks = 0; + boolean isWithinLimit = true; + while (reader.hasNext()) { + XMLEvent event = reader.nextEvent(); + //All text events get reported as Characters events + if (event.getEventType() == XMLStreamConstants.CHARACTERS) { + Characters cdataEvent = (Characters) event; + if (cdataEvent.isCData()) { + String text = cdataEvent.getData(); + numOfChunks++; + if (text.length() > chunkSize) { + isWithinLimit = false; + } + debugPrint("\nCDATA: " + text.length()); + cdata.append(text); + } + } + } + debugPrint("CData in single chunk:" + cdata.toString().length()); + Assert.assertEquals(numOfChunks, expectedNumOfChunks); + Assert.assertEquals(isWithinLimit, withinLimit); + } + + /* + * Data for tests: + * xml, size limit, expected number of chunks, expected that the size of all chunks is within the limit + */ + @DataProvider(name = "xml-data") + public Object[][] xmlData() throws Exception { + return new Object[][]{ + //{xml, NO_LIMIT, 1, false}, + {xml, 80, 13, true},}; + } + + final static String xml = "\n" + + "\n" + + " * XML Catalogs, OASIS Standard V1.1, 7 October 2005.\n" + + " *

      \n" + + " * A catalog is an XML file that contains a root {@code catalog} entry with a list of catalog entries. The entries can also be grouped with a {@code group} entry. The catalog and group entries may specify {@code prefer} and {@code xml:base} attributes that set preference of public or system type of entries and base URI to resolve relative URIs.\n" + + "]]>"; + + final static String xmlVal = "\n" + + "\n" + + " \n" + + "\n" + + ""; + + final static String xsd = "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + //{1,8000} + " \n" + + " \n" + + "\n" + + ""; + + /** + * SAX Handler + */ + class MyHandler extends DefaultHandler2 { + + StringBuilder text = new StringBuilder(); + StringBuilder cdata = new StringBuilder(); + + int cdataChunkSize = 0; + boolean cdataStart = false; + boolean cdataEnd = false; + int numOfCDataChunks; + boolean withinLimit = true; + + public MyHandler(int chunkSize) { + cdataChunkSize = chunkSize; + } + + public String getText() { + return text.toString(); + } + + public String getCData() { + return cdata.toString(); + } + + public int getNumOfCDataChunks() { + return numOfCDataChunks; + } + + public boolean chunkSizeWithinLimit() { + return withinLimit; + } + + @Override + public void startCDATA() { + cdataStart = true; + debugPrint("\nstartCDATA"); + } + + public void endCDATA() { + cdataEnd = true; + debugPrint(cdata.toString()); + debugPrint("\nendCDATA"); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + if (cdataStart && !cdataEnd) { + numOfCDataChunks++; + cdata.append(ch, start, length); + if (length > cdataChunkSize) { + withinLimit = false; + } + } else { + text.append(ch, start, length); + } + + debugPrint("\ncharacter event\n" + new String(ch, start, length)); + } + } + + void debugPrint(String msg) { + if (DEBUG) { + System.out.println(msg); + } + } + + static final boolean DEBUG = false; +} From ca6b8807072452f6f8778c8c9e682eca97c9184a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20Walln=C3=B6fer?= Date: Fri, 18 Nov 2016 15:26:24 +0100 Subject: [PATCH 149/402] 8169886: Add test for JDK-8162839 that runs with SecurityManager Reviewed-by: sundar --- nashorn/test/script/basic/JDK-8169886.js | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 nashorn/test/script/basic/JDK-8169886.js diff --git a/nashorn/test/script/basic/JDK-8169886.js b/nashorn/test/script/basic/JDK-8169886.js new file mode 100644 index 00000000000..d5998df3c32 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8169886.js @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * JDK-8169886: Add test for JDK-8162839 that runs with SecurityManager + * + * @test + * @run + */ + + +var m = new javax.script.ScriptEngineManager(); +var e = m.getEngineByName("nashorn"); + +e.eval("function f() { return 'ok' }"); +var f = e.get("f"); + +var c = new java.util.concurrent.Callable(f); +Assert.assertEquals(c.call(), 'ok'); + From 7ae986d83ecc77034319dd0e849a76baa9c342ea Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Fri, 18 Nov 2016 15:50:43 +0100 Subject: [PATCH 150/402] 8169860: Clean up and unify the refactored Javadoc generation Reviewed-by: erikj --- make/Javadoc.gmk | 535 ++++++++-------------------------- make/common/CORE_PKGS.gmk | 305 ------------------- make/common/MakeBase.gmk | 6 +- make/common/NON_CORE_PKGS.gmk | 132 --------- test/make/TestMakeBase.gmk | 5 +- 5 files changed, 135 insertions(+), 848 deletions(-) delete mode 100644 make/common/CORE_PKGS.gmk delete mode 100644 make/common/NON_CORE_PKGS.gmk diff --git a/make/Javadoc.gmk b/make/Javadoc.gmk index 98bf06f2e28..8a0a4cf0fd6 100644 --- a/make/Javadoc.gmk +++ b/make/Javadoc.gmk @@ -55,12 +55,6 @@ DOCROOTPARENT_FLAG = TRUE # depend on it. CORE_INDEX_FILE := $(JAVADOC_OUTPUTDIR)/api/index.html -# Symbols -TRADEMARK := ™ -COPYRIGHT_SYMBOL := &$(HASH)x00a9; -COPYRIGHT_TEXT := Copyright -ALL_RIGHTS_RESERVED := All rights reserved. - # URLs JAVADOC_BASE_URL := http://docs.oracle.com/javase/$(VERSION_SPECIFICATION)/docs BUG_SUBMIT_URL := http://bugreport.java.com/bugreport/ @@ -69,18 +63,16 @@ BUG_SUBMIT_URL := http://bugreport.java.com/bugreport/ # Text snippets FULL_COMPANY_NAME := Oracle and/or its affiliates -COMPANY_ADDRESS := 500 Oracle Parkway
      Redwood Shores, CA 94065 USA. +COMPANY_ADDRESS := 500 Oracle Parkway
      Redwood Shores, CA 94065 USA BUG_SUBMIT_LINE := Submit a bug or feature -JAVA_TRADEMARK_LINE := Java is a trademark or registered trademark of \ - $(FULL_COMPANY_NAME) in the US and other countries. -COMMON_BOTTOM_ADDRESS := $(COMPANY_ADDRESS) -COMMON_BOTTOM_TEXT := $(BUG_SUBMIT_LINE)
      $(JAVA_TRADEMARK_LINE) +COMMON_BOTTOM_TEXT := $(BUG_SUBMIT_LINE)
      Java is a trademark or registered \ + trademark of $(FULL_COMPANY_NAME) in the US and other countries. CORE_BOTTOM_COPYRIGHT_URL := {@docroot}/../legal/cpyr.html -CORE_BOTTOM_TEXT := $(BUG_SUBMIT_LINE)\ -
      For further API reference and developer documentation, \ -see Java SE \ +CORE_BOTTOM_TEXT := $(BUG_SUBMIT_LINE) \ +
      For further API reference and developer documentation, see \ +
      Java SE \ Documentation. That documentation contains more detailed, \ developer-targeted descriptions, with conceptual overviews, definitions of \ terms, workarounds, and working code examples. @@ -94,18 +86,19 @@ else # We need a draft format when not building the GA version. DRAFT_HEADER :=
      DRAFT $(VERSION_STRING) DRAFT_BOTTOM :=
      DRAFT $(VERSION_STRING) - DRAFT_WINTITLE := $(VERSION_BUILD) + ifeq ($(VERSION_BUILD), 0) + DRAFT_WINTITLE := [ad-hoc build] + else + DRAFT_WINTITLE := [build $(VERSION_BUILD)] + endif CORE_TOP_EARLYACCESS := \

      \
      \ -Please note that the specifications and other information \ -contained herein are not final and are subject to change. \ -The information is being made available to you solely for purpose of \ -evaluation. \ -
      +margin-left: 6px; margin-right: 6px; text-align: justify; font-size: 80%; \ +font-family: Helvetica, Arial, sans-serif; font-weight: normal;"> \ +Please note that the specifications and other information contained herein are \ +not final and are subject to change. The information is being made available \ +to you solely for purpose of evaluation. endif ################################################################################ @@ -127,22 +120,17 @@ endef # Arguments: # arg 1: first copyright year # arg 2: copyright url (optional) -# arg 3: company address (optional) -# arg 4: free-form text snippet (optional) +# arg 3: free-form text snippet (optional) define GenerateBottom - $(if $(strip $4), $(strip $4))
      $(if \ - $(strip $2),$(COPYRIGHT_TEXT),$(COPYRIGHT_TEXT)) \ - $(COPYRIGHT_SYMBOL) $(strip $1), $(COPYRIGHT_YEAR), \ - $(FULL_COMPANY_NAME). $(strip $3) \ - $(ALL_RIGHTS_RESERVED)$(if $(strip $4), )
      + $(if $(strip $3), $(strip $3))
      $(if \ + $(strip $2),Copyright,Copyright) \ + © $(strip $1), $(COPYRIGHT_YEAR), $(FULL_COMPANY_NAME). \ + $(COMPANY_ADDRESS). All rights reserved.
      endef # Speed up finding by filling cache $(eval $(call FillCacheFind, $(wildcard $(JAVADOC_SOURCE_DIRS)))) -# Prevent # from expanding -EscapeHash = $(subst $(HASH),{hash},$(strip $1)) - ################################################################################ # Setup make rules for running javadoc. # @@ -154,7 +142,6 @@ EscapeHash = $(subst $(HASH),{hash},$(strip $1)) # Remaining parameters are named arguments. These include: # MODULES - Modules to include # PACKAGES - Packages to include -# PACKAGE_FILTER - Filter for packages # IS_CORE - Set to TRUE for the Core API package which needs special treatment # API_ROOT - Where to base the documentation (jre or jdk) # DEST_DIR - A directory relative to the API root @@ -164,15 +151,10 @@ EscapeHash = $(subst $(HASH),{hash},$(strip $1)) # HEADER_TITLE - Title to use in -header. Computed from TITLE if empty. # DOC_TITLE - Title to use in -doctitle. Computed from TITLE if empty. # FIRST_COPYRIGHT_YEAR - First year this bundle was introduced -# DOCLINT - Doclint level. Defaults to "all". +# DISABLED_DOCLINT - Doclint warnings to exclude. # DOCLINT_PACKAGES - Optional -Xdoclint/package value -# ENCODING - Change character encoding (defaults to 'ascii') -# SPLIT_INDEX - Enable -splitIndex -# BREAKITERATOR - Enable -breakiterator -# NODEPRECATEDLIST - Enable nodeprecatedlist -# NOINDEX - Enable -noindex and -nonavbar +# SPLIT_INDEX - Enable -splitIndex (split index-all.html if it is too large) # BOTTOM_COPYRIGHT_URL - Copyright URL to use in -bottom -# BOTTOM_ADDRESS - Company address to use in -bottom # BOTTOM_TEXT - Extra text to use in -bottom # EXTRA_TOP - Additional -top data # @@ -185,16 +167,13 @@ define SetupJavadocGenerationBody $1_JAVA := $$(JAVA_SMALL) $1_OUTPUT_DIRNAME := $$($1_API_ROOT)/api/$$($1_DEST_DIR) - ifeq ($$($1_RELATIVE_CORE_DIR),) - # Compute a relative path to core root. - # The non-core api javadocs need to be able to access the root of the core - # api directory, so for jdk/api or jre/api to get to the core api/ - # directory we would use this - # NOTE: Need to be able to override for broken old code in JShell - $1_RELATIVE_CORE_DIR := $$(strip $$(subst $$(call DirToDotDot, \ - $$(JAVADOC_OUTPUTDIR))/,, $$(call DirToDotDot, \ - $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)))) - endif + # Compute a relative path to core root. + # The non-core api javadocs need to be able to access the root of the core + # api directory, so for jdk/api or jre/api to get to the core api/ + # directory we would use this + $1_RELATIVE_CORE_DIR := $$(strip $$(subst $$(call DirToDotDot, \ + $$(JAVADOC_OUTPUTDIR))/,, $$(call DirToDotDot, \ + $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)))) $1_DEPS += $(CORE_INDEX_FILE) endif @@ -203,12 +182,11 @@ define SetupJavadocGenerationBody $1_DEPS += $$($1_OVERVIEW) endif - ifeq ($$($1_ENCODING), ) - $1_ENCODING := ascii - endif - - ifeq ($$($1_DOCLINT), ) + ifeq ($$($1_DISABLED_DOCLINT), ) $1_DOCLINT := all + else + # Create a string like "all,-syntax,-html" + $1_DOCLINT := all,$$(call CommaList, $$(addprefix -, $$($1_DISABLED_DOCLINT))) endif ifeq ($$($1_DOC_TITLE), ) @@ -216,23 +194,27 @@ define SetupJavadocGenerationBody endif ifeq ($$($1_WINDOW_TITLE), ) - $1_WINDOW_TITLE := $$(strip $$(subst $$(TRADEMARK),, $$($1_TITLE))) + $1_WINDOW_TITLE := $$(strip $$(subst ™,, $$($1_TITLE))) endif ifeq ($$($1_HEADER_TITLE), ) - $1_HEADER_TITLE := $$(strip $$(subst $$(TRADEMARK),, $$($1_TITLE))) + $1_HEADER_TITLE := $$(strip $$(subst ™,, $$($1_TITLE))) endif $1_HEADER := $$($1_HEADER_TITLE) + ifeq ($$($1_BOTTOM_TEXT), ) + $1_BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT) + endif + $1_BOTTOM := $$(call GenerateBottom, $$($1_FIRST_COPYRIGHT_YEAR), \ - $$($1_BOTTOM_COPYRIGHT_URL), $$($1_BOTTOM_ADDRESS), $$($1_BOTTOM_TEXT)) + $$($1_BOTTOM_COPYRIGHT_URL), $$($1_BOTTOM_TEXT)) # The index.html, options, and packages files $1_INDEX_FILE := $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)/index.html $1_OPTIONS_FILE := $$(SUPPORT_OUTPUTDIR)/docs/$1.options $1_PACKAGES_FILE := $$(SUPPORT_OUTPUTDIR)/docs/$1.packages - $1_PACKAGES_VARDEPS := $$($1_PACKAGES) $$($1_PACKAGES_SINGLE_CLASS) + $1_PACKAGES_VARDEPS := $$($1_PACKAGES) $1_PACKAGES_VARDEPS_FILE := $$(call DependOnVariable, $1_PACKAGES_VARDEPS, \ $$($1_PACKAGES_FILE).vardeps) @@ -240,24 +222,14 @@ define SetupJavadocGenerationBody $$($1_PACKAGES_FILE): $$($1_PACKAGES_VARDEPS_FILE) $$(call LogInfo, Creating Javadoc package file for $1) $$(call MakeDir, $$(@D)) - ifeq ($$($1_PACKAGES_SINGLE_CLASS), ) - $$(ECHO) $$($1_PACKAGES) | $$(TR) ' ' '\n' > $$@ - else - # NOTE: This is for backwards compatibility for taglet - $$(ECHO) $$($1_PACKAGES_SINGLE_CLASS) > $$@ - endif + $$(ECHO) $$($1_PACKAGES) | $$(TR) ' ' '\n' > $$@ - # NOTE: Not including $$($1_EXTRA_TOP) due to $$(HASH) - $1_OPTIONS_VARDEPS := $$(call EscapeHash, \ - $$($DOCROOTPARENT_FLAG) $$(JAVADOC_BASE_URL) $$($1_NO_COMMON_TAGS) \ - $$($1_DOCLINT) $$($1_DOCLINT_PACKAGES) $$(JAVADOC_SOURCE_DIRS) \ - $$($1_MODULES) $$($1_ENCODING) $$($1_NODEPRECATEDLIST) \ - $$($1_BREAKITERATOR) $$($1_SPLIT_INDEX) $$($1_OVERVIEW) \ - $$($1_DOC_TITLE) $$($1_WINDOW_TITLE) $$(DRAFT_WINTITLE) \ - $$($1_HEADER) $$(DRAFT_HEADER) $$($1_NOINDEX) $$($1_EXTRA_TOP_2) \ - $$($1_BOTTOM) $$(DRAFT_BOTTOM)) $$($1_PACKAGE_FILTER) $$($1_RELATIVE_CORE_DIR) \ - $$(JAVADOC_OUTPUTDIR) \ - ) + $1_OPTIONS_VARDEPS := $$($1_EXTRA_TOP) \ + $$($DOCROOTPARENT_FLAG) $$(JAVADOC_BASE_URL) $$($1_DISABLED_DOCLINT) \ + $$($1_DOCLINT_PACKAGES) $$(JAVADOC_SOURCE_DIRS) $$($1_MODULES) \ + $$($1_SPLIT_INDEX) $$($1_OVERVIEW) $$($1_DOC_TITLE) $$($1_WINDOW_TITLE) \ + $$(DRAFT_WINTITLE) $$($1_HEADER) $$(DRAFT_HEADER) $$($1_BOTTOM) \ + $$(DRAFT_BOTTOM)) $$($1_RELATIVE_CORE_DIR) $$(JAVADOC_OUTPUTDIR) $1_OPTIONS_VARDEPS_FILE := $$(call DependOnVariable, $1_OPTIONS_VARDEPS, \ $$($1_OPTIONS_FILE).vardeps) @@ -273,35 +245,32 @@ define SetupJavadocGenerationBody $$(call AddOption, -use) $$(call AddOption, -keywords) ifneq ($$($DOCROOTPARENT_FLAG), ) - # NOTE: Argument to -Xdocrootparent is not quoted to keep backwards compatibility. - $$(call AddOption, -Xdocrootparent $(JAVADOC_BASE_URL)) - endif - ifneq ($$($1_NO_COMMON_TAGS), TRUE) - # In order to get a specific ordering it's necessary to specify the total - # ordering of tags as the tags are otherwise ordered in order of definition. - $$(call AddOption, -tag, beaninfo:X) - $$(call AddOption, -tag, revised:X) - $$(call AddOption, -tag, since.unbundled:X) - $$(call AddOption, -tag, spec:X) - $$(call AddOption, -tag, specdefault:X) - $$(call AddOption, -tag, Note:X) - $$(call AddOption, -tag, ToDo:X) - $$(call AddOption, -tag, apiNote:a:API Note:) - $$(call AddOption, -tag, implSpec:a:Implementation Requirements:) - $$(call AddOption, -tag, implNote:a:Implementation Note:) - $$(call AddOption, -tag, param) - $$(call AddOption, -tag, return) - $$(call AddOption, -tag, throws) - $$(call AddOption, -tag, since) - $$(call AddOption, -tag, version) - $$(call AddOption, -tag, serialData) - $$(call AddOption, -tag, factory) - $$(call AddOption, -tag, see) - $$(call AddOption, -tag, \ - jvms:a:See The Java™ Virtual Machine Specification:) - $$(call AddOption, -tag, \ - jls:a:See The Java™ Language Specification:) + $$(call AddOption, -Xdocrootparent, $(JAVADOC_BASE_URL)) endif + # In order to get a specific ordering it's necessary to specify the total + # ordering of tags as the tags are otherwise ordered in order of definition. + $$(call AddOption, -tag, beaninfo:X) + $$(call AddOption, -tag, revised:X) + $$(call AddOption, -tag, since.unbundled:X) + $$(call AddOption, -tag, spec:X) + $$(call AddOption, -tag, specdefault:X) + $$(call AddOption, -tag, Note:X) + $$(call AddOption, -tag, ToDo:X) + $$(call AddOption, -tag, apiNote:a:API Note:) + $$(call AddOption, -tag, implSpec:a:Implementation Requirements:) + $$(call AddOption, -tag, implNote:a:Implementation Note:) + $$(call AddOption, -tag, param) + $$(call AddOption, -tag, return) + $$(call AddOption, -tag, throws) + $$(call AddOption, -tag, since) + $$(call AddOption, -tag, version) + $$(call AddOption, -tag, serialData) + $$(call AddOption, -tag, factory) + $$(call AddOption, -tag, see) + $$(call AddOption, -tag, \ + jvms:a:See The Java™ Virtual Machine Specification:) + $$(call AddOption, -tag, \ + jls:a:See The Java™ Language Specification:) $$(call AddOption, -Xdoclint:$$($1_DOCLINT)) ifneq ($$($1_DOCLINT_PACKAGES), ) $$(call AddOption, -Xdoclint/package:$$(call CommaList, $$($1_DOCLINT_PACKAGES))) @@ -309,13 +278,10 @@ define SetupJavadocGenerationBody $$(call AddOption, --system, none) $$(call AddOption, --module-source-path, $$(subst ",, $$(call PathList, $$(JAVADOC_SOURCE_DIRS)))) $$(call AddOption, --add-modules, $$(call CommaList, $$($1_MODULES))) - $$(call AddOption, -encoding, $$($1_ENCODING)) - ifneq ($$($1_NODEPRECATEDLIST), ) - $$(call AddOption, -nodeprecatedlist) - endif - ifneq ($$($1_BREAKITERATOR), ) - $$(call AddOption, -breakiterator) - endif + $$(call AddOption, -encoding, ISO-8859-1) + $$(call AddOption, -breakiterator) + $$(call AddOption, -serialwarn) + $$(call AddOption, -notimestamp) ifneq ($$($1_SPLIT_INDEX), ) $$(call AddOption, -splitIndex) endif @@ -325,17 +291,7 @@ define SetupJavadocGenerationBody $$(call AddOption, -doctitle, $$($1_DOC_TITLE)) $$(call AddOption, -windowtitle, $$($1_WINDOW_TITLE) $$(DRAFT_WINTITLE)) $$(call AddOption, -header, $$($1_HEADER)$$(DRAFT_HEADER)) - ifneq ($$($1_NOINDEX), ) - $$(call AddOption, -nonavbar) - $$(call AddOption, -noindex) - endif - ifneq ($$($1_EXTRA_TOP_2), ) - $$(call AddOption, -top,$$($1_EXTRA_TOP_2)) - endif $$(call AddOption, -bottom, $$($1_BOTTOM)$$(DRAFT_BOTTOM)) - ifneq ($$($1_PACKAGE_FILTER), ) - $$(call AddOption, -group, Packages, $$($1_PACKAGE_FILTER)) - endif ifneq ($$($1_RELATIVE_CORE_DIR), ) $$(call AddOption, -linkoffline, $$($1_RELATIVE_CORE_DIR)/api, $$(JAVADOC_OUTPUTDIR)/api/) endif @@ -367,232 +323,34 @@ endef ################################################################################ -CORE_PACKAGES := \ - java.applet \ - java.awt \ - java.awt.color \ - java.awt.datatransfer \ - java.awt.desktop \ - java.awt.dnd \ - java.awt.event \ - java.awt.font \ - java.awt.geom \ - java.awt.im \ - java.awt.im.spi \ - java.awt.image \ - java.awt.image.renderable \ - java.awt.print \ - java.beans \ - java.beans.beancontext \ - java.io \ - java.lang \ - java.lang.annotation \ - java.lang.instrument \ - java.lang.invoke \ - java.lang.management \ - java.lang.module \ - java.lang.ref \ - java.lang.reflect \ - java.math \ - java.net \ - java.net.http \ - java.net.spi \ - java.nio \ - java.nio.channels \ - java.nio.channels.spi \ - java.nio.charset \ - java.nio.charset.spi \ - java.nio.file \ - java.nio.file.attribute \ - java.nio.file.spi \ - java.rmi \ - java.rmi.activation \ - java.rmi.dgc \ - java.rmi.registry \ - java.rmi.server \ - java.security \ - java.security.acl \ - java.security.cert \ - java.security.interfaces \ - java.security.spec \ - java.sql \ - java.text \ - java.text.spi \ - java.time \ - java.time.chrono \ - java.time.format \ - java.time.temporal \ - java.time.zone \ - java.util \ - java.util.concurrent \ - java.util.concurrent.atomic \ - java.util.concurrent.locks \ - java.util.function \ - java.util.jar \ - java.util.logging \ - java.util.prefs \ - java.util.regex \ - java.util.spi \ - java.util.stream \ - java.util.zip \ - javax.accessibility \ - javax.activation \ - javax.activity \ - javax.annotation \ - javax.annotation.processing \ - javax.crypto \ - javax.crypto.interfaces \ - javax.crypto.spec \ - javax.imageio \ - javax.imageio.event \ - javax.imageio.metadata \ - javax.imageio.plugins.jpeg \ - javax.imageio.plugins.bmp \ - javax.imageio.plugins.tiff \ - javax.imageio.spi \ - javax.imageio.stream \ - javax.jws \ - javax.jws.soap \ - javax.lang.model \ - javax.lang.model.element \ - javax.lang.model.type \ - javax.lang.model.util \ - javax.management \ - javax.management.loading \ - javax.management.monitor \ - javax.management.relation \ - javax.management.openmbean \ - javax.management.timer \ - javax.management.modelmbean \ - javax.management.remote \ - javax.management.remote.rmi \ - javax.naming \ - javax.naming.directory \ - javax.naming.event \ - javax.naming.ldap \ - javax.naming.spi \ - javax.net \ - javax.net.ssl \ - javax.print \ - javax.print.attribute \ - javax.print.attribute.standard \ - javax.print.event \ - javax.rmi \ - javax.rmi.CORBA \ - javax.rmi.ssl \ - javax.script \ - javax.security.auth \ - javax.security.auth.callback \ - javax.security.auth.kerberos \ - javax.security.auth.login \ - javax.security.auth.spi \ - javax.security.auth.x500 \ - javax.security.cert \ - javax.security.sasl \ - javax.sound.sampled \ - javax.sound.sampled.spi \ - javax.sound.midi \ - javax.sound.midi.spi \ - javax.sql \ - javax.sql.rowset \ - javax.sql.rowset.serial \ - javax.sql.rowset.spi \ - javax.swing \ - javax.swing.border \ - javax.swing.colorchooser \ - javax.swing.filechooser \ - javax.swing.event \ - javax.swing.table \ - javax.swing.text \ - javax.swing.text.html \ - javax.swing.text.html.parser \ - javax.swing.text.rtf \ - javax.swing.tree \ - javax.swing.undo \ - javax.swing.plaf \ - javax.swing.plaf.basic \ - javax.swing.plaf.metal \ - javax.swing.plaf.multi \ - javax.swing.plaf.nimbus \ - javax.swing.plaf.synth \ - javax.tools \ - javax.transaction \ - javax.transaction.xa \ - javax.xml.catalog \ - javax.xml.parsers \ - javax.xml.bind \ - javax.xml.bind.annotation \ - javax.xml.bind.annotation.adapters \ - javax.xml.bind.attachment \ - javax.xml.bind.helpers \ - javax.xml.bind.util \ - javax.xml.soap \ - javax.xml.ws \ - javax.xml.ws.handler \ - javax.xml.ws.handler.soap \ - javax.xml.ws.http \ - javax.xml.ws.soap \ - javax.xml.ws.spi \ - javax.xml.ws.spi.http \ - javax.xml.ws.wsaddressing \ - javax.xml.transform \ - javax.xml.transform.sax \ - javax.xml.transform.dom \ - javax.xml.transform.stax \ - javax.xml.transform.stream \ - javax.xml \ - javax.xml.crypto \ - javax.xml.crypto.dom \ - javax.xml.crypto.dsig \ - javax.xml.crypto.dsig.dom \ - javax.xml.crypto.dsig.keyinfo \ - javax.xml.crypto.dsig.spec \ - javax.xml.datatype \ - javax.xml.validation \ - javax.xml.namespace \ - javax.xml.xpath \ - javax.xml.stream \ - javax.xml.stream.events \ - javax.xml.stream.util \ - org.ietf.jgss \ - org.omg.CORBA \ - org.omg.CORBA.DynAnyPackage \ - org.omg.CORBA.ORBPackage \ - org.omg.CORBA.TypeCodePackage \ - org.omg.stub.java.rmi \ - org.omg.CORBA.portable \ - org.omg.CORBA_2_3 \ - org.omg.CORBA_2_3.portable \ - org.omg.CosNaming \ - org.omg.CosNaming.NamingContextExtPackage \ - org.omg.CosNaming.NamingContextPackage \ - org.omg.SendingContext \ - org.omg.PortableServer \ - org.omg.PortableServer.CurrentPackage \ - org.omg.PortableServer.POAPackage \ - org.omg.PortableServer.POAManagerPackage \ - org.omg.PortableServer.ServantLocatorPackage \ - org.omg.PortableServer.portable \ - org.omg.PortableInterceptor \ - org.omg.PortableInterceptor.ORBInitInfoPackage \ - org.omg.Messaging \ - org.omg.IOP \ - org.omg.IOP.CodecFactoryPackage \ - org.omg.IOP.CodecPackage \ - org.omg.Dynamic \ - org.omg.DynamicAny \ - org.omg.DynamicAny.DynAnyPackage \ - org.omg.DynamicAny.DynAnyFactoryPackage \ - org.w3c.dom \ - org.w3c.dom.events \ - org.w3c.dom.bootstrap \ - org.w3c.dom.ls \ - org.w3c.dom.ranges \ - org.w3c.dom.traversal \ - org.w3c.dom.views \ - org.xml.sax \ - org.xml.sax.ext \ - org.xml.sax.helpers +# Core packages are all packages beginning with java, javax or org, except a few +# excludes. + +ALL_PKG_DIRS := $(dir $(filter %.java, $(call CacheFind, \ + $(wildcard $(JAVADOC_SOURCE_DIRS))))) +ALL_SRC_PREFIXES := $(addsuffix /%, $(wildcard $(JAVADOC_SOURCE_DIRS))) +ALL_PKG_DIRNAMES := $(foreach prefix, $(ALL_SRC_PREFIXES), \ + $(patsubst $(prefix),%, $(filter $(prefix), $(ALL_PKG_DIRS)))) +ALL_PACKAGES := $(sort $(subst /,., $(patsubst %/, %, $(ALL_PKG_DIRNAMES)))) + +JAVA_PACKAGES := $(filter java.%, $(ALL_PACKAGES)) +JAVAX_PACKAGES := $(filter javax.%, $(ALL_PACKAGES)) +ORG_PACKAGES := $(filter org.%, $(ALL_PACKAGES)) + +# Allow custom makefile to add more excluded packages +CORE_EXCLUDED_PACKAGES += \ + java.awt.dnd.peer \ + java.awt.peer \ + javax.smartcardio \ + org.jcp.xml.dsig.internal% \ + org.w3c.dom.css \ + org.w3c.dom.html \ + org.w3c.dom.stylesheets \ + org.w3c.dom.xpath \ + # + +CORE_PACKAGES := $(filter-out $(CORE_EXCLUDED_PACKAGES), \ + $(JAVA_PACKAGES) $(JAVAX_PACKAGES) $(ORG_PACKAGES)) $(eval $(call SetupJavadocGeneration, coredocs, \ MODULES := java.se.ee, \ @@ -600,13 +358,12 @@ $(eval $(call SetupJavadocGeneration, coredocs, \ IS_CORE := TRUE, \ OVERVIEW := $(JDK_TOPDIR)/src/java.base/share/classes/overview-core.html, \ WINDOW_TITLE := Java Platform SE $(VERSION_SPECIFICATION), \ - HEADER_TITLE := Java$(TRADEMARK) Platform
      Standard Ed. $(VERSION_SPECIFICATION), \ - DOC_TITLE := Java$(TRADEMARK) Platform$(COMMA) Standard Edition \ + HEADER_TITLE := Java™ Platform
      Standard Ed. $(VERSION_SPECIFICATION), \ + DOC_TITLE := Java™ Platform$(COMMA) Standard Edition \ $(VERSION_SPECIFICATION)
      API Specification, \ FIRST_COPYRIGHT_YEAR := 1993, \ - DOCLINT := reference, \ + DISABLED_DOCLINT := accessibility html missing syntax, \ DOCLINT_PACKAGES := -org.omg.* jdk.internal.logging.*, \ - ENCODING := ISO-8859-1, \ SPLIT_INDEX := TRUE, \ BOTTOM_COPYRIGHT_URL := $(CORE_BOTTOM_COPYRIGHT_URL), \ BOTTOM_TEXT := $(CORE_BOTTOM_TEXT), \ @@ -623,14 +380,10 @@ $(eval $(call SetupJavadocGeneration, docletapi, \ jdk.javadoc.doclet \ jdk.javadoc.doclet.taglet \ jdk.javadoc.doclets, \ - PACKAGE_FILTER := jdk.javadoc.doclet*, \ API_ROOT := jdk, \ DEST_DIR := javadoc/doclet, \ TITLE := Doclet API, \ FIRST_COPYRIGHT_YEAR := 1993, \ - BREAKITERATOR := TRUE, \ - BOTTOM_ADDRESS := $(COMMON_BOTTOM_ADDRESS), \ - BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT), \ )) TARGETS += $(docletapi) @@ -640,36 +393,23 @@ TARGETS += $(docletapi) $(eval $(call SetupJavadocGeneration, old-docletapi, \ MODULES := jdk.javadoc, \ PACKAGES := com.sun.javadoc, \ - PACKAGE_FILTER := com.sun.javadoc, \ API_ROOT := jdk, \ DEST_DIR := javadoc/old/doclet, \ TITLE := Doclet API, \ FIRST_COPYRIGHT_YEAR := 1993, \ - BREAKITERATOR := TRUE, \ - BOTTOM_ADDRESS := $(COMMON_BOTTOM_ADDRESS), \ - BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT), \ )) TARGETS += $(old-docletapi) ################################################################################ -# Specify a single class instead of a package -TAGLET_PACKAGE_SINGLE_CLASS := com/sun/tools/doclets/Taglet.java -TAGLET_PACKAGE_DIR := $(LANGTOOLS_TOPDIR)/src/jdk.javadoc/share/classes - $(eval $(call SetupJavadocGeneration, tagletapi, \ MODULES := jdk.javadoc, \ PACKAGES := com.sun.tools.doclets, \ - PACKAGES_SINGLE_CLASS := $(TAGLET_PACKAGE_DIR)/$(TAGLET_PACKAGE_SINGLE_CLASS), \ API_ROOT := jdk, \ DEST_DIR := javadoc/old/taglet, \ TITLE := Taglet API, \ FIRST_COPYRIGHT_YEAR := 1993, \ - BREAKITERATOR := TRUE, \ - NOINDEX := TRUE, \ - BOTTOM_ADDRESS := $(COMMON_BOTTOM_ADDRESS), \ - BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT), \ )) TARGETS += $(tagletapi) @@ -691,15 +431,12 @@ $(eval $(call SetupJavadocGeneration, domapi, \ org.w3c.dom.css \ org.w3c.dom.events \ org.w3c.dom.views, \ - PACKAGE_FILTER := org.w3c.dom*, \ API_ROOT := jre, \ DEST_DIR := plugin/dom, \ TITLE := Common DOM API, \ FIRST_COPYRIGHT_YEAR := 2005, \ - DOCLINT := none, \ + DISABLED_DOCLINT := accessibility html missing, \ SPLIT_INDEX := TRUE, \ - BOTTOM_ADDRESS := $(COMMON_BOTTOM_ADDRESS), \ - BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT), \ )) TARGETS += $(domapi) @@ -717,9 +454,10 @@ $(eval $(call SetupJavadocGeneration, jdi, \ API_ROOT := jdk, \ DEST_DIR := jpda/jdi, \ OVERVIEW := $(JDK_TOPDIR)/src/jdk.jdi/share/classes/jdi-overview.html, \ - TITLE := Java$(TRADEMARK) Debug Interface, \ + TITLE := Java™ Debug Interface, \ FIRST_COPYRIGHT_YEAR := 1999, \ - DOCLINT := none, \ + DISABLED_DOCLINT := accessibility missing syntax, \ + SPLIT_INDEX := TRUE, \ )) TARGETS += $(jdi) @@ -736,9 +474,9 @@ $(eval $(call SetupJavadocGeneration, jaas, \ API_ROOT := jre, \ DEST_DIR := security/jaas/spec, \ OVERVIEW := $(JDK_TOPDIR)/src/jdk.security.auth/share/classes/jaas-overview.html, \ - TITLE := Java$(TRADEMARK) Authentication and Authorization Service, \ + TITLE := Java™ Authentication and Authorization Service, \ FIRST_COPYRIGHT_YEAR := 1998, \ - DOCLINT := none, \ + DISABLED_DOCLINT := missing, \ )) TARGETS += $(jaas) @@ -751,10 +489,8 @@ $(eval $(call SetupJavadocGeneration, jgss, \ API_ROOT := jre, \ DEST_DIR := security/jgss/spec, \ OVERVIEW := $(JDK_TOPDIR)/src/java.security.jgss/share/classes/jgss-overview.html, \ - TITLE := Java$(TRADEMARK) GSS-API Utilities, \ + TITLE := Java™ GSS-API Utilities, \ FIRST_COPYRIGHT_YEAR := 2000, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ )) TARGETS += $(jgss) @@ -766,10 +502,8 @@ $(eval $(call SetupJavadocGeneration, smartcardio, \ PACKAGES := javax.smartcardio, \ API_ROOT := jre, \ DEST_DIR := security/smartcardio/spec, \ - TITLE := Java$(TRADEMARK) Smart Card I/O, \ + TITLE := Java™ Smart Card I/O, \ FIRST_COPYRIGHT_YEAR := 2005, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ )) TARGETS += $(smartcardio) @@ -783,10 +517,9 @@ $(eval $(call SetupJavadocGeneration, httpserver, \ com.sun.net.httpserver.spi, \ API_ROOT := jre, \ DEST_DIR := net/httpserver/spec, \ - TITLE := Java$(TRADEMARK) HTTP Server, \ + TITLE := Java™ HTTP Server, \ FIRST_COPYRIGHT_YEAR := 2005, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + DISABLED_DOCLINT := accessibility missing syntax, \ )) TARGETS += $(httpserver) @@ -799,9 +532,7 @@ $(eval $(call SetupJavadocGeneration, jsobject, \ API_ROOT := jre, \ DEST_DIR := plugin/jsobject, \ FIRST_COPYRIGHT_YEAR := 1993, \ - TITLE := Java$(TRADEMARK) JSObject Doc, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + TITLE := Java™ JSObject Doc, \ )) TARGETS += $(jsobject) @@ -814,10 +545,9 @@ $(eval $(call SetupJavadocGeneration, mgmt, \ API_ROOT := jre, \ DEST_DIR := management/extension, \ OVERVIEW := $(JDK_TOPDIR)/src/java.management/share/classes/mgmt-overview.html, \ - TITLE := Monitoring and Management Interface for the Java$(TRADEMARK) Platform, \ + TITLE := Monitoring and Management Interface for the Java™ Platform, \ FIRST_COPYRIGHT_YEAR := 2003, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + DISABLED_DOCLINT := accessibility missing reference, \ )) TARGETS += $(mgmt) @@ -833,8 +563,7 @@ $(eval $(call SetupJavadocGeneration, attach, \ DEST_DIR := attach/spec, \ TITLE := Attach API, \ FIRST_COPYRIGHT_YEAR := 2005, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + DISABLED_DOCLINT := reference, \ )) TARGETS += $(attach) @@ -848,15 +577,12 @@ $(eval $(call SetupJavadocGeneration, jconsole, \ DEST_DIR := jconsole/spec, \ TITLE := JConsole API, \ FIRST_COPYRIGHT_YEAR := 2006, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ )) TARGETS += $(jconsole) ################################################################################ -# NOTE: Need to override RELATIVE_CORE_DIR to be bug compatible with old code. $(eval $(call SetupJavadocGeneration, jshellapi, \ MODULES := jdk.jshell, \ PACKAGES := \ @@ -865,10 +591,8 @@ $(eval $(call SetupJavadocGeneration, jshellapi, \ jdk.jshell.execution, \ API_ROOT := jdk, \ DEST_DIR := jshell, \ - RELATIVE_CORE_DIR := ../../../.., \ OVERVIEW := $(LANGTOOLS_TOPDIR)/src/jdk.jshell/share/classes/jdk/jshell/overview.html, \ TITLE := JShell API, \ - HEADER_TITLE := JSHELL API, \ FIRST_COPYRIGHT_YEAR := 2015, \ )) @@ -882,11 +606,11 @@ $(eval $(call SetupJavadocGeneration, treeapi, \ com.sun.source.doctree \ com.sun.source.tree \ com.sun.source.util, \ - PACKAGE_FILTER := com.sun.source.*, \ API_ROOT := jdk, \ DEST_DIR := javac/tree, \ TITLE := Compiler Tree API, \ FIRST_COPYRIGHT_YEAR := 2005, \ + SPLIT_INDEX := TRUE, \ )) TARGETS += $(treeapi) @@ -898,11 +622,11 @@ $(eval $(call SetupJavadocGeneration, nashornapi, \ PACKAGES := \ jdk.nashorn.api.scripting \ jdk.nashorn.api.tree, \ - PACKAGE_FILTER := jdk.nashorn.api.*, \ API_ROOT := jdk, \ DEST_DIR := nashorn, \ TITLE := Nashorn API, \ FIRST_COPYRIGHT_YEAR := 2014, \ + SPLIT_INDEX := TRUE, \ )) TARGETS += $(nashornapi) @@ -934,8 +658,6 @@ $(eval $(call SetupJavadocGeneration, sctp, \ DEST_DIR := nio/sctp/spec, \ TITLE := SCTP API, \ FIRST_COPYRIGHT_YEAR := 2009, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ )) TARGETS += $(sctp) @@ -949,7 +671,6 @@ $(eval $(call SetupJavadocGeneration, jaccess, \ DEST_DIR := accessibility/jaccess/spec, \ TITLE := JACCESS API, \ FIRST_COPYRIGHT_YEAR := 2002, \ - NODEPRECATEDLIST := TRUE, \ )) TARGETS += $(jaccess) @@ -963,8 +684,7 @@ $(eval $(call SetupJavadocGeneration, jdknet, \ DEST_DIR := net/socketoptions/spec, \ TITLE := jdk.net API, \ FIRST_COPYRIGHT_YEAR := 2014, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + DISABLED_DOCLINT := missing, \ )) TARGETS += $(jdknet) @@ -980,8 +700,7 @@ $(eval $(call SetupJavadocGeneration, jlinkplugins, \ DEST_DIR := jlink, \ TITLE := JLink Plugin API - EXPERIMENTAL, \ FIRST_COPYRIGHT_YEAR := 2015, \ - DOCLINT := none, \ - NODEPRECATEDLIST := TRUE, \ + DISABLED_DOCLINT := html missing syntax, \ )) TARGETS += $(jlinkplugins) diff --git a/make/common/CORE_PKGS.gmk b/make/common/CORE_PKGS.gmk deleted file mode 100644 index 96c77123372..00000000000 --- a/make/common/CORE_PKGS.gmk +++ /dev/null @@ -1,305 +0,0 @@ -# -# Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Oracle designates this -# particular file as subject to the "Classpath" exception as provided -# by Oracle in the LICENSE file that accompanied this code. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# EXCLUDE_PKGS is the list of packages to exclude from the -# Java API Specification. Do not add these to CORE_PKGS. -# The concatenation of EXCLUDE_PKGS and CORE_PKGS -# should make up the list of all packages under the -# src/shared/classes directory of the JDK source tree. -# -EXCLUDE_PKGS = \ - java.awt.peer \ - java.awt.dnd.peer \ - sun.* \ - com.sun.* \ - org.apache.* \ - org.jcp.* \ - org.w3c.dom.css \ - org.w3c.dom.html \ - org.w3c.dom.stylesheets \ - org.omg.stub.javax.management.remote.rmi - -# -# ACTIVE_JSR_PKGS are packages that are part of an active JSR process-- -# one that is doing its own review. These packages are not included when -# creating diff pages for the platform's JCP process. -# -# (see /java/pubs/apisrc/jdk/6.0/beta/make/docs/active_jsr_pkgs) -# Note: -# This is a list of regular expressions. So foo.* matches "foo" and "foo.bar". -# -ACTIVE_JSR_PKGS= \ - java.lang.invoke \ - java.sql \ - javax.activation \ - javax.annotation.* \ - javax.jws.* \ - javax.lang.* \ - javax.management.* \ - javax.script \ - javax.sql.* \ - javax.tools.* \ - javax.xml.* \ - org.w3c.* \ - org.xml.sax - -# -# CORE_PKGS is the list of packages that form the -# Java API Specification. -# -### ***IMPORTANT NOTE*** -### There is also a "REGEXP" variable in the docs/makefile that -### determines which table the packages go in on the main page. -### Currently, there is only table ("Platform Packages") and -### everything goes in it, so REGEXP is "*". But if that policy -### changes, packages added will need to be reflected in that -### list of wildcard expressions, as well. -### -CORE_PKGS = \ - java.applet \ - java.awt \ - java.awt.color \ - java.awt.datatransfer \ - java.awt.desktop \ - java.awt.dnd \ - java.awt.event \ - java.awt.font \ - java.awt.geom \ - java.awt.im \ - java.awt.im.spi \ - java.awt.image \ - java.awt.image.renderable \ - java.awt.print \ - java.beans \ - java.beans.beancontext \ - java.io \ - java.lang \ - java.lang.annotation \ - java.lang.instrument \ - java.lang.invoke \ - java.lang.management \ - java.lang.module \ - java.lang.ref \ - java.lang.reflect \ - java.math \ - java.net \ - java.net.http \ - java.net.spi \ - java.nio \ - java.nio.channels \ - java.nio.channels.spi \ - java.nio.charset \ - java.nio.charset.spi \ - java.nio.file \ - java.nio.file.attribute \ - java.nio.file.spi \ - java.rmi \ - java.rmi.activation \ - java.rmi.dgc \ - java.rmi.registry \ - java.rmi.server \ - java.security \ - java.security.acl \ - java.security.cert \ - java.security.interfaces \ - java.security.spec \ - java.sql \ - java.text \ - java.text.spi \ - java.time \ - java.time.chrono \ - java.time.format \ - java.time.temporal \ - java.time.zone \ - java.util \ - java.util.concurrent \ - java.util.concurrent.atomic \ - java.util.concurrent.locks \ - java.util.function \ - java.util.jar \ - java.util.logging \ - java.util.prefs \ - java.util.regex \ - java.util.spi \ - java.util.stream \ - java.util.zip \ - javax.accessibility \ - javax.activation \ - javax.activity \ - javax.annotation \ - javax.annotation.processing \ - javax.crypto \ - javax.crypto.interfaces \ - javax.crypto.spec \ - javax.imageio \ - javax.imageio.event \ - javax.imageio.metadata \ - javax.imageio.plugins.jpeg \ - javax.imageio.plugins.bmp \ - javax.imageio.plugins.tiff \ - javax.imageio.spi \ - javax.imageio.stream \ - javax.jws \ - javax.jws.soap \ - javax.lang.model \ - javax.lang.model.element \ - javax.lang.model.type \ - javax.lang.model.util \ - javax.management \ - javax.management.loading \ - javax.management.monitor \ - javax.management.relation \ - javax.management.openmbean \ - javax.management.timer \ - javax.management.modelmbean \ - javax.management.remote \ - javax.management.remote.rmi \ - javax.naming \ - javax.naming.directory \ - javax.naming.event \ - javax.naming.ldap \ - javax.naming.spi \ - javax.net \ - javax.net.ssl \ - javax.print \ - javax.print.attribute \ - javax.print.attribute.standard \ - javax.print.event \ - javax.rmi \ - javax.rmi.CORBA \ - javax.rmi.ssl \ - javax.script \ - javax.security.auth \ - javax.security.auth.callback \ - javax.security.auth.kerberos \ - javax.security.auth.login \ - javax.security.auth.spi \ - javax.security.auth.x500 \ - javax.security.cert \ - javax.security.sasl \ - javax.sound.sampled \ - javax.sound.sampled.spi \ - javax.sound.midi \ - javax.sound.midi.spi \ - javax.sql \ - javax.sql.rowset \ - javax.sql.rowset.serial \ - javax.sql.rowset.spi \ - javax.swing \ - javax.swing.border \ - javax.swing.colorchooser \ - javax.swing.filechooser \ - javax.swing.event \ - javax.swing.table \ - javax.swing.text \ - javax.swing.text.html \ - javax.swing.text.html.parser \ - javax.swing.text.rtf \ - javax.swing.tree \ - javax.swing.undo \ - javax.swing.plaf \ - javax.swing.plaf.basic \ - javax.swing.plaf.metal \ - javax.swing.plaf.multi \ - javax.swing.plaf.nimbus \ - javax.swing.plaf.synth \ - javax.tools \ - javax.transaction \ - javax.transaction.xa \ - javax.xml.catalog \ - javax.xml.parsers \ - javax.xml.bind \ - javax.xml.bind.annotation \ - javax.xml.bind.annotation.adapters \ - javax.xml.bind.attachment \ - javax.xml.bind.helpers \ - javax.xml.bind.util \ - javax.xml.soap \ - javax.xml.ws \ - javax.xml.ws.handler \ - javax.xml.ws.handler.soap \ - javax.xml.ws.http \ - javax.xml.ws.soap \ - javax.xml.ws.spi \ - javax.xml.ws.spi.http \ - javax.xml.ws.wsaddressing \ - javax.xml.transform \ - javax.xml.transform.sax \ - javax.xml.transform.dom \ - javax.xml.transform.stax \ - javax.xml.transform.stream \ - javax.xml \ - javax.xml.crypto \ - javax.xml.crypto.dom \ - javax.xml.crypto.dsig \ - javax.xml.crypto.dsig.dom \ - javax.xml.crypto.dsig.keyinfo \ - javax.xml.crypto.dsig.spec \ - javax.xml.datatype \ - javax.xml.validation \ - javax.xml.namespace \ - javax.xml.xpath \ - javax.xml.stream \ - javax.xml.stream.events \ - javax.xml.stream.util \ - org.ietf.jgss \ - org.omg.CORBA \ - org.omg.CORBA.DynAnyPackage \ - org.omg.CORBA.ORBPackage \ - org.omg.CORBA.TypeCodePackage \ - org.omg.stub.java.rmi \ - org.omg.CORBA.portable \ - org.omg.CORBA_2_3 \ - org.omg.CORBA_2_3.portable \ - org.omg.CosNaming \ - org.omg.CosNaming.NamingContextExtPackage \ - org.omg.CosNaming.NamingContextPackage \ - org.omg.SendingContext \ - org.omg.PortableServer \ - org.omg.PortableServer.CurrentPackage \ - org.omg.PortableServer.POAPackage \ - org.omg.PortableServer.POAManagerPackage \ - org.omg.PortableServer.ServantLocatorPackage \ - org.omg.PortableServer.portable \ - org.omg.PortableInterceptor \ - org.omg.PortableInterceptor.ORBInitInfoPackage \ - org.omg.Messaging \ - org.omg.IOP \ - org.omg.IOP.CodecFactoryPackage \ - org.omg.IOP.CodecPackage \ - org.omg.Dynamic \ - org.omg.DynamicAny \ - org.omg.DynamicAny.DynAnyPackage \ - org.omg.DynamicAny.DynAnyFactoryPackage \ - org.w3c.dom \ - org.w3c.dom.events \ - org.w3c.dom.bootstrap \ - org.w3c.dom.ls \ - org.w3c.dom.ranges \ - org.w3c.dom.traversal \ - org.w3c.dom.views \ - org.xml.sax \ - org.xml.sax.ext \ - org.xml.sax.helpers diff --git a/make/common/MakeBase.gmk b/make/common/MakeBase.gmk index c54d7f5c640..9c2a3f135d1 100644 --- a/make/common/MakeBase.gmk +++ b/make/common/MakeBase.gmk @@ -121,6 +121,10 @@ endef # any present escapes before escaping so that no double escapes are added. EscapeDollar = $(subst $$,\$$,$(subst \$$,$$,$(strip $1))) +################################################################################ +# This macro works just like EscapeDollar above, but for #. +EscapeHash = $(subst \#,\\\#,$(subst \\\#,\#,$(strip $1))) + ################################################################################ # This macro translates $ into $$ to protect the string from make itself. DoubleDollar = $(subst $$,$$$$,$(strip $1)) @@ -833,7 +837,7 @@ DependOnVariableHelper = \ $(if $(findstring $(LOG_LEVEL), trace), \ $(info NewVariable $1: >$(strip $($1))<) \ $(info OldVariable $1: >$(strip $($1_old))<)) \ - $(call WriteFile, $1_old:=$(call DoubleDollar,$($1)), \ + $(call WriteFile, $1_old:=$(call DoubleDollar,$(call EscapeHash,$($1))), \ $(call DependOnVariableFileName, $1, $2))) \ $(call DependOnVariableFileName, $1, $2) \ ) diff --git a/make/common/NON_CORE_PKGS.gmk b/make/common/NON_CORE_PKGS.gmk deleted file mode 100644 index 26a387a5e90..00000000000 --- a/make/common/NON_CORE_PKGS.gmk +++ /dev/null @@ -1,132 +0,0 @@ -# -# Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Oracle designates this -# particular file as subject to the "Classpath" exception as provided -# by Oracle in the LICENSE file that accompanied this code. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# -# This file contains the package names of all the "non-core" -# API published in the Java 2 SDK documentation. "Non-core" means -# it includes all published API outside of the JDK API specification. -# -# These environment variables are used by javadoc in -# make/docs/Makefile and are referenced by the localization -# team when determining which APIs to extract javadoc -# comments from. - -DOMAPI_PKGS = org.w3c.dom \ - org.w3c.dom.bootstrap \ - org.w3c.dom.ls \ - org.w3c.dom.ranges \ - org.w3c.dom.traversal \ - org.w3c.dom.html \ - org.w3c.dom.stylesheets \ - org.w3c.dom.css \ - org.w3c.dom.events \ - org.w3c.dom.views - -JDI_PKGS = com.sun.jdi \ - com.sun.jdi.event \ - com.sun.jdi.request \ - com.sun.jdi.connect \ - com.sun.jdi.connect.spi - -MGMT_PKGS = com.sun.management - -JAAS_PKGS = com.sun.security.auth \ - com.sun.security.auth.callback \ - com.sun.security.auth.login \ - com.sun.security.auth.module - -JGSS_PKGS = com.sun.security.jgss - -OLD_JSSE_PKGS = com.sun.net.ssl - -HTTPSERVER_PKGS = com.sun.net.httpserver \ - com.sun.net.httpserver.spi - -NIO_PKGS = com.sun.nio.file - -OLD_DOCLETAPI_PKGS = com.sun.javadoc - -DOCLETAPI_PKGS = jdk.javadoc.doclet \ - jdk.javadoc.doclet.taglet \ - jdk.javadoc.doclets - -TAGLETAPI_FILE = com/sun/tools/doclets/Taglet.java - -TAGLETAPI_PKGS = com.sun.tools.doclets - -ATTACH_PKGS = com.sun.tools.attach \ - com.sun.tools.attach.spi - -JCONSOLE_PKGS = com.sun.tools.jconsole - -JSHELLAPI_PKGS = jdk.jshell \ - jdk.jshell.spi \ - jdk.jshell.execution - -TREEAPI_PKGS = com.sun.source.doctree \ - com.sun.source.tree \ - com.sun.source.util - -NASHORNAPI_PKGS = jdk.nashorn.api.scripting \ - jdk.nashorn.api.tree - -DYNALINKAPI_PKGS = jdk.dynalink \ - jdk.dynalink.beans \ - jdk.dynalink.linker \ - jdk.dynalink.linker.support \ - jdk.dynalink.support - -SMARTCARDIO_PKGS = javax.smartcardio - -SCTPAPI_PKGS = com.sun.nio.sctp - -ifeq ($(PLATFORM), macosx) - APPLE_EXT_PKGS = com.apple.eawt \ - com.apple.eawt.event \ - com.apple.eio -endif - -JDK_PKGS = jdk \ - jdk.net \ - jdk.management.cmm - -JACCESSAPI_PKGS = com.sun.java.accessibility.util - -JSOBJECT_PKGS = netscape.javascript - -# non-core packages in rt.jar -NON_CORE_PKGS = $(DOMAPI_PKGS) \ - $(JSOBJECT_PKGS) \ - $(MGMT_PKGS) \ - $(JAAS_PKGS) \ - $(JGSS_PKGS) \ - $(NIO_PKGS) \ - $(OLD_JSSE_PKGS) \ - $(HTTPSERVER_PKGS) \ - $(SMARTCARDIO_PKGS) \ - $(SCTPAPI_PKGS) \ - $(APPLE_EXT_PKGS) \ - $(JDK_PKGS) \ - $(JACCESSAPI_PKGS) diff --git a/test/make/TestMakeBase.gmk b/test/make/TestMakeBase.gmk index 547041b03f5..0bed3ea447c 100644 --- a/test/make/TestMakeBase.gmk +++ b/test/make/TestMakeBase.gmk @@ -226,10 +226,11 @@ $(eval $(call assert-equals, $(VARDEP_TEST_VAR2_old), $(VARDEP_TEST_VAR2), \ Wrong contents in vardeps file)) # Test with a variable value containing some problematic characters -VARDEP_TEST_VAR3 := foo '""' "''" bar \$$ORIGIN +VARDEP_TEST_VAR3 := foo '""' "''" bar \$$ORIGIN &\#x00a9 VARDEP_VALUE_FILE := $(call DependOnVariable, VARDEP_TEST_VAR3) -include $(VARDEP_VALUE_FILE) -$(eval $(call assert-equals, $(VARDEP_TEST_VAR3_old), $(VARDEP_TEST_VAR3), \ +$(eval $(call assert-equals, $(call EscapeHash,$(VARDEP_TEST_VAR3_old)), \ + $(call EscapeHash,$(VARDEP_TEST_VAR3)), \ Wrong contents in vardep file)) TEST_TARGETS += test-vardep From f9eb02a06612b54cdb28c7ee7175192e013808fc Mon Sep 17 00:00:00 2001 From: Robert Field Date: Fri, 18 Nov 2016 09:41:51 -0800 Subject: [PATCH 151/402] 8153402: jshell tool: completion provider for /help 8169818: jshell tool: completion provider for /vars /methods /types gives -history Reviewed-by: jlahoda --- .../jdk/internal/jshell/tool/JShellTool.java | 98 +++++++++++++++---- .../jdk/jshell/CommandCompletionTest.java | 65 ++++++++++-- .../test/jdk/jshell/ReplToolTesting.java | 2 +- 3 files changed, 138 insertions(+), 27 deletions(-) diff --git a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java index db943397e77..e7c2ffd79c9 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java @@ -45,6 +45,7 @@ import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -1051,8 +1052,12 @@ public class JShellTool implements MessageHandler { } static final CompletionProvider EMPTY_COMPLETION_PROVIDER = new FixedCompletionProvider(); - private static final CompletionProvider KEYWORD_COMPLETION_PROVIDER = new FixedCompletionProvider("-all ", "-start ", "-history "); - private static final CompletionProvider RELOAD_OPTIONS_COMPLETION_PROVIDER = new FixedCompletionProvider("-restore", "-quiet"); + private static final CompletionProvider SNIPPET_HISTORY_OPTION_COMPLETION_PROVIDER = new FixedCompletionProvider("-all", "-start ", "-history"); + private static final CompletionProvider SAVE_OPTION_COMPLETION_PROVIDER = new FixedCompletionProvider("-all ", "-start ", "-history "); + private static final CompletionProvider SNIPPET_OPTION_COMPLETION_PROVIDER = new FixedCompletionProvider("-all", "-start " ); + private static final CompletionProvider RELOAD_OPTIONS_COMPLETION_PROVIDER = new FixedCompletionProvider("-restore ", "-quiet "); + private static final CompletionProvider RESTORE_COMPLETION_PROVIDER = new FixedCompletionProvider("-restore"); + private static final CompletionProvider QUIET_COMPLETION_PROVIDER = new FixedCompletionProvider("-quiet"); private static final CompletionProvider SET_MODE_OPTIONS_COMPLETION_PROVIDER = new FixedCompletionProvider("-command", "-quiet", "-delete"); private static final CompletionProvider FILE_COMPLETION_PROVIDER = fileCompletions(p -> true); private final Map commands = new LinkedHashMap<>(); @@ -1106,24 +1111,62 @@ public class JShellTool implements MessageHandler { p.getFileName().toString().endsWith(".jar")); } + // Completion based on snippet supplier private CompletionProvider snippetCompletion(Supplier> snippetsSupplier) { return (prefix, cursor, anchor) -> { anchor[0] = 0; + int space = prefix.lastIndexOf(' '); + Set prior = new HashSet<>(Arrays.asList(prefix.split(" "))); + if (prior.contains("-all") || prior.contains("-history")) { + return Collections.emptyList(); + } + String argPrefix = prefix.substring(space + 1); return snippetsSupplier.get() + .filter(k -> !prior.contains(String.valueOf(k.id())) + && (!(k instanceof DeclarationSnippet) + || !prior.contains(((DeclarationSnippet) k).name()))) .flatMap(k -> (k instanceof DeclarationSnippet) - ? Stream.of(String.valueOf(k.id()), ((DeclarationSnippet) k).name()) - : Stream.of(String.valueOf(k.id()))) - .filter(k -> k.startsWith(prefix)) + ? Stream.of(String.valueOf(k.id()) + " ", ((DeclarationSnippet) k).name() + " ") + : Stream.of(String.valueOf(k.id()) + " ")) + .filter(k -> k.startsWith(argPrefix)) .map(k -> new ArgSuggestion(k)) .collect(Collectors.toList()); }; } - private CompletionProvider snippetKeywordCompletion(Supplier> snippetsSupplier) { + // Completion based on snippet supplier with -all -start (and sometimes -history) options + private CompletionProvider snippetWithOptionCompletion(CompletionProvider optionProvider, + Supplier> snippetsSupplier) { return (code, cursor, anchor) -> { List result = new ArrayList<>(); - result.addAll(KEYWORD_COMPLETION_PROVIDER.completionSuggestions(code, cursor, anchor)); + int pastSpace = code.lastIndexOf(' ') + 1; // zero if no space + if (pastSpace == 0) { + result.addAll(optionProvider.completionSuggestions(code, cursor, anchor)); + } result.addAll(snippetCompletion(snippetsSupplier).completionSuggestions(code, cursor, anchor)); + anchor[0] += pastSpace; + return result; + }; + } + + // Completion of help, commands and subjects + private CompletionProvider helpCompletion() { + return (code, cursor, anchor) -> { + List result; + int pastSpace = code.indexOf(' ') + 1; // zero if no space + if (pastSpace == 0) { + result = new FixedCompletionProvider(commands.values().stream() + .filter(cmd -> cmd.kind.showInHelp || cmd.kind == CommandKind.HELP_SUBJECT) + .map(c -> c.command + " ") + .toArray(size -> new String[size])) + .completionSuggestions(code, cursor, anchor); + } else if (code.startsWith("/se")) { + result = new FixedCompletionProvider(SET_SUBCOMMANDS) + .completionSuggestions(code.substring(pastSpace), cursor - pastSpace, anchor); + } else { + result = Collections.emptyList(); + } + anchor[0] += pastSpace; return result; }; } @@ -1133,7 +1176,7 @@ public class JShellTool implements MessageHandler { List result = new ArrayList<>(); int space = code.indexOf(' '); if (space == (-1)) { - result.addAll(KEYWORD_COMPLETION_PROVIDER.completionSuggestions(code, cursor, anchor)); + result.addAll(SAVE_OPTION_COMPLETION_PROVIDER.completionSuggestions(code, cursor, anchor)); } result.addAll(FILE_COMPLETION_PROVIDER.completionSuggestions(code.substring(space + 1), cursor - space - 1, anchor)); anchor[0] += space + 1; @@ -1143,9 +1186,25 @@ public class JShellTool implements MessageHandler { private static CompletionProvider reloadCompletion() { return (code, cursor, anchor) -> { - List result = new ArrayList<>(); + CompletionProvider provider; int pastSpace = code.indexOf(' ') + 1; // zero if no space - result.addAll(RELOAD_OPTIONS_COMPLETION_PROVIDER.completionSuggestions(code.substring(pastSpace), cursor - pastSpace, anchor)); + if (pastSpace == 0) { + provider = RELOAD_OPTIONS_COMPLETION_PROVIDER; + } else { + switch (code.substring(0, pastSpace - 1)) { + case "-quiet": + provider = RESTORE_COMPLETION_PROVIDER; + break; + case "-restore": + provider = QUIET_COMPLETION_PROVIDER; + break; + default: + provider = EMPTY_COMPLETION_PROVIDER; + break; + } + } + List result = provider.completionSuggestions( + code.substring(pastSpace), cursor - pastSpace, anchor); anchor[0] += pastSpace; return result; }; @@ -1210,10 +1269,12 @@ public class JShellTool implements MessageHandler { { registerCommand(new Command("/list", arg -> cmdList(arg), - snippetKeywordCompletion(this::allSnippets))); + snippetWithOptionCompletion(SNIPPET_HISTORY_OPTION_COMPLETION_PROVIDER, + this::allSnippets))); registerCommand(new Command("/edit", arg -> cmdEdit(arg), - snippetCompletion(this::allSnippets))); + snippetWithOptionCompletion(SNIPPET_OPTION_COMPLETION_PROVIDER, + this::allSnippets))); registerCommand(new Command("/drop", arg -> cmdDrop(arg), snippetCompletion(this::dropableSnippets), @@ -1226,13 +1287,16 @@ public class JShellTool implements MessageHandler { FILE_COMPLETION_PROVIDER)); registerCommand(new Command("/vars", arg -> cmdVars(arg), - snippetKeywordCompletion(this::allVarSnippets))); + snippetWithOptionCompletion(SNIPPET_OPTION_COMPLETION_PROVIDER, + this::allVarSnippets))); registerCommand(new Command("/methods", arg -> cmdMethods(arg), - snippetKeywordCompletion(this::allMethodSnippets))); + snippetWithOptionCompletion(SNIPPET_OPTION_COMPLETION_PROVIDER, + this::allMethodSnippets))); registerCommand(new Command("/types", arg -> cmdTypes(arg), - snippetKeywordCompletion(this::allTypeSnippets))); + snippetWithOptionCompletion(SNIPPET_OPTION_COMPLETION_PROVIDER, + this::allTypeSnippets))); registerCommand(new Command("/imports", arg -> cmdImports(), EMPTY_COMPLETION_PROVIDER)); @@ -1258,7 +1322,7 @@ public class JShellTool implements MessageHandler { CommandKind.HIDDEN)); registerCommand(new Command("/help", arg -> cmdHelp(arg), - EMPTY_COMPLETION_PROVIDER)); + helpCompletion())); registerCommand(new Command("/set", arg -> cmdSet(arg), new ContinuousCompletionProvider(Map.of( @@ -1276,7 +1340,7 @@ public class JShellTool implements MessageHandler { registerCommand(new Command("/?", "help.quest", arg -> cmdHelp(arg), - EMPTY_COMPLETION_PROVIDER, + helpCompletion(), CommandKind.NORMAL)); registerCommand(new Command("/!", "help.bang", diff --git a/langtools/test/jdk/jshell/CommandCompletionTest.java b/langtools/test/jdk/jshell/CommandCompletionTest.java index d2f6fc5ee4b..f7d5034a63a 100644 --- a/langtools/test/jdk/jshell/CommandCompletionTest.java +++ b/langtools/test/jdk/jshell/CommandCompletionTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8144095 8164825 + * @bug 8144095 8164825 8169818 8153402 * @summary Test Command Completion * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main @@ -61,12 +61,13 @@ public class CommandCompletionTest extends ReplToolTesting { public void testList() { test(false, new String[] {"--no-startup"}, a -> assertCompletion(a, "/l|", false, "/list "), - a -> assertCompletion(a, "/list |", false, "-all ", "-history ", "-start "), - a -> assertCompletion(a, "/list -h|", false, "-history "), + a -> assertCompletion(a, "/list |", false, "-all", "-history", "-start "), + a -> assertCompletion(a, "/list -h|", false, "-history"), a -> assertCompletion(a, "/list q|", false), a -> assertVariable(a, "int", "xray"), - a -> assertCompletion(a, "/list |", false, "-all ", "-history ", "-start ", "1", "xray"), - a -> assertCompletion(a, "/list x|", false, "xray") + a -> assertCompletion(a, "/list |", false, "-all", "-history", "-start ", "1 ", "xray "), + a -> assertCompletion(a, "/list x|", false, "xray "), + a -> assertCompletion(a, "/list xray |", false) ); } @@ -76,8 +77,8 @@ public class CommandCompletionTest extends ReplToolTesting { a -> assertClass(a, "class cTest {}", "class", "cTest"), a -> assertMethod(a, "int mTest() { return 0; }", "()I", "mTest"), a -> assertVariable(a, "int", "fTest"), - a -> assertCompletion(a, "/drop |", false, "1", "2", "3", "cTest", "fTest", "mTest"), - a -> assertCompletion(a, "/drop f|", false, "fTest") + a -> assertCompletion(a, "/drop |", false, "1 ", "2 ", "3 ", "cTest ", "fTest ", "mTest "), + a -> assertCompletion(a, "/drop f|", false, "fTest ") ); } @@ -88,8 +89,54 @@ public class CommandCompletionTest extends ReplToolTesting { a -> assertClass(a, "class cTest {}", "class", "cTest"), a -> assertMethod(a, "int mTest() { return 0; }", "()I", "mTest"), a -> assertVariable(a, "int", "fTest"), - a -> assertCompletion(a, "/edit |", false, "1", "2", "3", "cTest", "fTest", "mTest"), - a -> assertCompletion(a, "/edit f|", false, "fTest") + a -> assertCompletion(a, "/edit |", false, + "-all" , "-start " , "1 ", "2 ", "3 ", "cTest ", "fTest ", "mTest "), + a -> assertCompletion(a, "/edit cTest |", false, + "2 ", "3 ", "fTest ", "mTest "), + a -> assertCompletion(a, "/edit 1 fTest |", false, + "2 ", "mTest "), + a -> assertCompletion(a, "/edit f|", false, "fTest "), + a -> assertCompletion(a, "/edit mTest f|", false, "fTest ") + ); + } + + public void testHelp() { + assertCompletion("/help |", false, + "/! ", "/- ", "/ ", "/? ", "/classpath ", "/drop ", + "/edit ", "/exit ", "/help ", "/history ", "/imports ", + "/list ", "/methods ", "/open ", "/reload ", "/reset ", + "/save ", "/set ", "/types ", "/vars ", "intro ", "shortcuts "); + assertCompletion("/? |", false, + "/! ", "/- ", "/ ", "/? ", "/classpath ", "/drop ", + "/edit ", "/exit ", "/help ", "/history ", "/imports ", + "/list ", "/methods ", "/open ", "/reload ", "/reset ", + "/save ", "/set ", "/types ", "/vars ", "intro ", "shortcuts "); + assertCompletion("/help /s|", false, + "/save ", "/set "); + assertCompletion("/help /set |", false, + "editor", "feedback", "format", "mode", "prompt", "start", "truncation"); + assertCompletion("/help /edit |", false); + } + + public void testReload() { + assertCompletion("/reload |", false, "-quiet ", "-restore "); + assertCompletion("/reload -restore |", false, "-quiet"); + assertCompletion("/reload -quiet |", false, "-restore"); + assertCompletion("/reload -restore -quiet |", false); + } + + public void testVarsMethodsTypes() { + test(false, new String[]{"--no-startup"}, + a -> assertCompletion(a, "/v|", false, "/vars "), + a -> assertCompletion(a, "/m|", false, "/methods "), + a -> assertCompletion(a, "/t|", false, "/types "), + a -> assertClass(a, "class cTest {}", "class", "cTest"), + a -> assertMethod(a, "int mTest() { return 0; }", "()I", "mTest"), + a -> assertVariable(a, "int", "fTest"), + a -> assertCompletion(a, "/vars |", false, "-all", "-start ", "3 ", "fTest "), + a -> assertCompletion(a, "/meth |", false, "-all", "-start ", "2 ", "mTest "), + a -> assertCompletion(a, "/typ |", false, "-all", "-start ", "1 ", "cTest "), + a -> assertCompletion(a, "/var f|", false, "fTest ") ); } diff --git a/langtools/test/jdk/jshell/ReplToolTesting.java b/langtools/test/jdk/jshell/ReplToolTesting.java index e2b6e4950cf..96aa6c81ceb 100644 --- a/langtools/test/jdk/jshell/ReplToolTesting.java +++ b/langtools/test/jdk/jshell/ReplToolTesting.java @@ -476,7 +476,7 @@ public class ReplToolTesting { code = code.replace("|", ""); assertTrue(cursor > -1, "'|' not found: " + code); List completions = - js.commandCompletionSuggestions(code, cursor, new int[1]); //XXX: ignoring anchor for now + js.commandCompletionSuggestions(code, cursor, new int[] {-1}); //XXX: ignoring anchor for now return completions.stream() .filter(s -> isSmart == s.matchesType()) .map(s -> s.continuation()) From 8e8834a9e928b3075660696ff71910243e7fbd09 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Mon, 21 Nov 2016 07:13:21 -0800 Subject: [PATCH 152/402] 8170110: Problem list ExternalEditorTest.java Reviewed-by: ksrini --- langtools/test/ProblemList.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/test/ProblemList.txt b/langtools/test/ProblemList.txt index f8bdf1f6288..2977850c748 100644 --- a/langtools/test/ProblemList.txt +++ b/langtools/test/ProblemList.txt @@ -38,6 +38,7 @@ jdk/javadoc/doclet/testIOException/TestIOException.java jdk/jshell/EditorPadTest.java 8161276 windows-all Test set-up cannot press buttons jdk/jshell/ToolBasicTest.java 8139873 generic-all JShell tests failing +jdk/jshell/ExternalEditorTest.java 8170108 windows-all ########################################################################### # From dda0e054d50572807a023d8f030a5d0bca92fb21 Mon Sep 17 00:00:00 2001 From: Robert Field Date: Mon, 21 Nov 2016 12:28:56 -0800 Subject: [PATCH 153/402] 8114842: JShell: SourceCodeAnalysis splits code with array initialiazer incorrectly Reviewed-by: jlahoda --- .../classes/jdk/jshell/CompletenessAnalyzer.java | 12 +++++------- langtools/test/jdk/jshell/CompletenessTest.java | 13 ++++++++++++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/CompletenessAnalyzer.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/CompletenessAnalyzer.java index fc52ac0c9e1..10c5d0468e8 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/CompletenessAnalyzer.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/CompletenessAnalyzer.java @@ -233,7 +233,7 @@ class CompletenessAnalyzer { // Declarations and type parameters (thus expressions) EXTENDS(TokenKind.EXTENDS, XEXPR|XDECL), // extends - COMMA(TokenKind.COMMA, XEXPR|XDECL|XTERM), // , + COMMA(TokenKind.COMMA, XEXPR|XDECL), // , AMP(TokenKind.AMP, XEXPR|XDECL), // & GT(TokenKind.GT, XEXPR|XDECL), // > LT(TokenKind.LT, XEXPR|XDECL1), // < @@ -541,7 +541,10 @@ class CompletenessAnalyzer { ct = new CT(TK.tokenKindToTK(prevTK, current.kind), advance()); break; } - if (ct.kind.isStart() && !prevTK.isOkToTerminate()) { + // Detect an error if we are at starting position and the last + // token wasn't a terminating one. Special case: within braces, + // comma can proceed semicolon, e.g. the values list in enum + if (ct.kind.isStart() && !prevTK.isOkToTerminate() && prevTK != COMMA) { return new CT(ERROR, current, "No '" + prevTK + "' before '" + ct.kind + "'"); } if (stack.isEmpty() || ct.kind.isError()) { @@ -653,12 +656,7 @@ class CompletenessAnalyzer { } switch (token.kind) { case EQ: - // Check for array initializer nextToken(); - if (token.kind == BRACES) { - nextToken(); - return lastly(SEMI); - } return parseExpressionStatement(); case BRACES: case SEMI: diff --git a/langtools/test/jdk/jshell/CompletenessTest.java b/langtools/test/jdk/jshell/CompletenessTest.java index a435dc3aacb..62544a5c31e 100644 --- a/langtools/test/jdk/jshell/CompletenessTest.java +++ b/langtools/test/jdk/jshell/CompletenessTest.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8149524 8131024 8165211 8080071 8130454 8167343 8129559 + * @bug 8149524 8131024 8165211 8080071 8130454 8167343 8129559 8114842 * @summary Test SourceCodeAnalysis * @build KullaTesting TestingInputStream * @run testng CompletenessTest @@ -118,6 +118,10 @@ public class CompletenessTest extends KullaTesting { "baz: while (true) if (t()) printf('-'); else break baz", "java.util.function.IntFunction ggg = int[]::new", "List l", + "int[] m = {1, 2}", + "int[] m = {1, 2}, n = null", + "int[] m = {1, 2}, n", + "int[] m = {1, 2}, n = {3, 4}", }; static final String[] considered_incomplete = new String[] { @@ -177,6 +181,11 @@ public class CompletenessTest extends KullaTesting { "void f()", "void f() throws E", "@A(", + "int n = 4,", + "int n,", + "int[] m = {1, 2},", + "int[] m = {1, 2}, n = {3, 4},", + "Map Date: Mon, 21 Nov 2016 17:17:21 -0800 Subject: [PATCH 154/402] 8170049: tests under java/rmi/activation/ fail with "java.security.AccessControlException: access denied ("java.net.SocketPermission" "localhost:5281" "listen,resolve")" on windows Reviewed-by: rriggs --- .../Activatable/checkRegisterInLog/rmid.security.policy | 1 + .../activation/Activatable/forceLogSnapshot/rmid.security.policy | 1 + .../Activatable/restartCrashedService/rmid.security.policy | 1 + .../activation/Activatable/restartService/rmid.security.policy | 1 + .../ActivationSystem/modifyDescriptor/rmid.security.policy | 1 + 5 files changed, 5 insertions(+) diff --git a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy index fd9ccf3da7b..ce485f61343 100644 --- a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy @@ -5,4 +5,5 @@ grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy index fd9ccf3da7b..ce485f61343 100644 --- a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy @@ -5,4 +5,5 @@ grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy index fd9ccf3da7b..ce485f61343 100644 --- a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy @@ -5,4 +5,5 @@ grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff --git a/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy b/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy index b8a10fa78ae..3e6ac7893f0 100644 --- a/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy +++ b/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy @@ -5,4 +5,5 @@ grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy index 0e94162f0bd..a352c07a92b 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy @@ -7,4 +7,5 @@ grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; From 421c8d877849bca9086be09c1a60943c7595632c Mon Sep 17 00:00:00 2001 From: Amanda Jiang Date: Mon, 21 Nov 2016 22:50:22 -0800 Subject: [PATCH 155/402] 8169911: Enhanced tests for jarsigner -verbose -verify after JDK-8163304 Reviewed-by: weijun --- .../tools/jarsigner/TimestampCheck.java | 58 ++++++++++++++++++- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java index e2ac09bd9e6..9ba18ac0f05 100644 --- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java +++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java @@ -58,7 +58,7 @@ import sun.security.x509.X500Name; /* * @test - * @bug 6543842 6543440 6939248 8009636 8024302 8163304 + * @bug 6543842 6543440 6939248 8009636 8024302 8163304 8169911 * @summary checking response of timestamp * @modules java.base/sun.security.pkcs * java.base/sun.security.timestamp @@ -349,6 +349,18 @@ public class TimestampCheck { .shouldMatch("MD5withRSA.*-sigalg.*risk"); checkWeak("weak.jar"); + signWithAliasAndTsa("halfWeak", "old.jar", "old", "-digestalg", "MD5") + .shouldHaveExitValue(0); + checkHalfWeak("halfWeak.jar"); + + // sign with DSA key + signWithAliasAndTsa("sign1", "old.jar", "dsakey") + .shouldHaveExitValue(0); + // sign with RSAkeysize < 1024 + signWithAliasAndTsa("sign2", "sign1.jar", "weakkeysize") + .shouldHaveExitValue(0); + checkMultiple("sign2.jar"); + // When .SF or .RSA is missing or invalid checkMissingOrInvalidFiles("normal.jar"); } else { // Run as a standalone server @@ -447,6 +459,37 @@ public class TimestampCheck { .shouldMatch("SignatureException:.*Disabled"); } + static void checkHalfWeak(String file) throws Throwable { + verify(file) + .shouldHaveExitValue(0) + .shouldContain("treated as unsigned") + .shouldMatch("weak algorithm that is now disabled.") + .shouldMatch("Re-run jarsigner with the -verbose option for more details"); + verify(file, "-verbose") + .shouldHaveExitValue(0) + .shouldContain("treated as unsigned") + .shouldMatch("weak algorithm that is now disabled by") + .shouldMatch("Digest algorithm: .*weak") + .shouldNotMatch("Signature algorithm: .*weak") + .shouldNotMatch("Timestamp digest algorithm: .*weak") + .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak") + .shouldNotMatch("Timestamp signature algorithm: .*key.*weak"); + } + + static void checkMultiple(String file) throws Throwable { + verify(file) + .shouldHaveExitValue(0) + .shouldContain("jar verified"); + verify(file, "-verbose", "-certs") + .shouldHaveExitValue(0) + .shouldContain("jar verified") + .shouldMatch("X.509.*CN=dsakey") + .shouldNotMatch("X.509.*CN=weakkeysize") + .shouldMatch("Signed by .*CN=dsakey") + .shouldMatch("Signed by .*CN=weakkeysize") + .shouldMatch("Signature algorithm: .*key.*weak"); + } + static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception { try (JarFile jf = new JarFile(file)) { @@ -480,11 +523,16 @@ public class TimestampCheck { */ static OutputAnalyzer sign(String path, String... extra) throws Throwable { + String alias = path.equals("badku") ? "badku" : "old"; + return signWithAliasAndTsa(path, "old.jar", alias, extra); + } + + static OutputAnalyzer signWithAliasAndTsa (String path, String jar, + String alias, String...extra) throws Throwable { which++; System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra)); List args = List.of("-J-Djava.security.egd=file:/dev/./urandom", - "-debug", "-signedjar", path + ".jar", "old.jar", - path.equals("badku") ? "badku" : "old"); + "-debug", "-signedjar", path + ".jar", jar, alias); args = new ArrayList<>(args); if (!path.equals("none") && !path.equals("badku")) { args.add("-tsa"); @@ -499,6 +547,8 @@ public class TimestampCheck { Files.deleteIfExists(Paths.get("tsks")); keytool("-alias ca -genkeypair -ext bc -dname CN=CA"); keytool("-alias old -genkeypair -dname CN=old"); + keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey"); + keytool("-alias weakkeysize -genkeypair -keysize 512 -dname CN=weakkeysize"); keytool("-alias badku -genkeypair -dname CN=badku"); keytool("-alias ts -genkeypair -dname CN=ts"); keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1"); @@ -507,6 +557,8 @@ public class TimestampCheck { keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3"); gencert("old"); + gencert("dsakey"); + gencert("weakkeysize"); gencert("badku", "-ext ku:critical=keyAgreement"); gencert("ts", "-ext eku:critical=ts"); gencert("tsweak", "-ext eku:critical=ts"); From a9bb2d512b561d09c8bb49d40ff4774bd7d0d15d Mon Sep 17 00:00:00 2001 From: Rachna Goel Date: Tue, 22 Nov 2016 13:02:12 +0530 Subject: [PATCH 156/402] 8168906: Tighten permissions granted to the jdk.localedata module Reviewed-by: okutsu, naoto, alanb, mullan --- jdk/src/java.base/share/lib/security/default.policy | 1 - 1 file changed, 1 deletion(-) diff --git a/jdk/src/java.base/share/lib/security/default.policy b/jdk/src/java.base/share/lib/security/default.policy index 74c8463ea3c..de6e99a8f49 100644 --- a/jdk/src/java.base/share/lib/security/default.policy +++ b/jdk/src/java.base/share/lib/security/default.policy @@ -155,7 +155,6 @@ grant codeBase "jrt:/jdk.jsobject" { grant codeBase "jrt:/jdk.localedata" { permission java.lang.RuntimePermission "accessClassInPackage.sun.text.*"; permission java.lang.RuntimePermission "accessClassInPackage.sun.util.*"; - permission java.util.PropertyPermission "*", "read"; }; grant codeBase "jrt:/jdk.naming.dns" { From 460675bc0855af06da77e79104326eb666b29ade Mon Sep 17 00:00:00 2001 From: Bhanu Prakash Gopularam Date: Tue, 22 Nov 2016 08:22:57 +0000 Subject: [PATCH 157/402] 8158880: java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java fail with zh_CN locale Set locale explicitly in the test Reviewed-by: rriggs, naoto --- .../tck/java/time/format/TCKDateTimeFormatterBuilder.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java b/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java index 1aa39d1d406..7429f013060 100644 --- a/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java +++ b/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java @@ -594,7 +594,7 @@ public class TCKDateTimeFormatterBuilder { @Test(dataProvider = "formatGenericTimeZonePatterns") public void test_appendZoneText_formatGenericTimeZonePatterns(String pattern, String input, String expected) { ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(input)); - DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern); + DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US); assertEquals(zdt.format(df), expected); } @@ -641,7 +641,7 @@ public class TCKDateTimeFormatterBuilder { @Test(dataProvider = "formatNonGenericTimeZonePatterns_1") public void test_appendZoneText_parseNonGenricTimeZonePatterns_1(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); - DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); + DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(Locale.US); ZonedDateTime zdt = ZonedDateTime.of(ldt, zId); String actual = df.format(zdt); assertEquals(actual, expected); @@ -668,7 +668,7 @@ public class TCKDateTimeFormatterBuilder { @Test(dataProvider = "formatNonGenericTimeZonePatterns_2") public void test_appendZoneText_parseNonGenricTimeZonePatterns_2(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); - DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern).withZone(zId); + DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US).withZone(zId); String actual = df.format(ldt); assertEquals(actual, expected); } From a7eccd60dff9cd3d6f966f6d481e9722be100bc0 Mon Sep 17 00:00:00 2001 From: Hamlin Li Date: Tue, 22 Nov 2016 01:37:18 -0800 Subject: [PATCH 158/402] 8153543: java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java fails intermittently Reviewed-by: chegar --- .../reuseDefaultPort/ReuseDefaultPort.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java b/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java index 6fce16108f1..e8688ec8250 100644 --- a/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java +++ b/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ import java.rmi.server.UnicastRemoteObject; public class ReuseDefaultPort implements Remote { - private static final int PORT = TestLibrary.getUnusedRandomPort(); + private static int rmiPort = 0; private ReuseDefaultPort() { } @@ -64,7 +64,7 @@ public class ReuseDefaultPort implements Remote { Remote stub = UnicastRemoteObject.exportObject(impl, 0); System.err.println("- exported object: " + stub); try { - Registry registry = LocateRegistry.createRegistry(PORT); + Registry registry = LocateRegistry.createRegistry(rmiPort); System.err.println("- exported registry: " + registry); System.err.println("TEST PASSED"); } finally { @@ -77,13 +77,15 @@ public class ReuseDefaultPort implements Remote { RMISocketFactory.getDefaultSocketFactory(); SF() { } public Socket createSocket(String host, int port) throws IOException { + System.err.format("in SF::createSocket: %s, %d%n", host, port); return defaultFactory.createSocket(host, port); } public ServerSocket createServerSocket(int port) throws IOException { - if (port == 0) { - port = PORT; - } - return defaultFactory.createServerSocket(port); + System.err.format("in SF::createServerSocket: %d%n", port); + ServerSocket server = defaultFactory.createServerSocket(port); + rmiPort = server.getLocalPort(); + System.err.println("rmiPort: " + rmiPort); + return server; } } } From 25a65593b781ed02f1ea98b9505688efed8b6e36 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 13:44:41 +0100 Subject: [PATCH 159/402] 8170077: Properly parallelize javadoc generation Reviewed-by: erikj --- make/Javadoc.gmk | 333 +++++++++++++++++++++-------------------------- 1 file changed, 150 insertions(+), 183 deletions(-) diff --git a/make/Javadoc.gmk b/make/Javadoc.gmk index 8a0a4cf0fd6..807fafb6092 100644 --- a/make/Javadoc.gmk +++ b/make/Javadoc.gmk @@ -50,11 +50,6 @@ JAVADOC_SOURCE_DIRS = \ # Should we use -Xdocrootparent? Allow custom to overwrite. DOCROOTPARENT_FLAG = TRUE -# The core api index file is the target for the core api javadocs rule -# and needs to be defined early so that all other javadoc rules may -# depend on it. -CORE_INDEX_FILE := $(JAVADOC_OUTPUTDIR)/api/index.html - # URLs JAVADOC_BASE_URL := http://docs.oracle.com/javase/$(VERSION_SPECIFICATION)/docs BUG_SUBMIT_URL := http://bugreport.java.com/bugreport/ @@ -70,52 +65,82 @@ COMMON_BOTTOM_TEXT := $(BUG_SUBMIT_LINE)
      Java is a trademark or registered \ trademark of $(FULL_COMPANY_NAME) in the US and other countries. CORE_BOTTOM_COPYRIGHT_URL := {@docroot}/../legal/cpyr.html -CORE_BOTTOM_TEXT := $(BUG_SUBMIT_LINE) \ -
      For further API reference and developer documentation, see \ -Java SE \ -Documentation. That documentation contains more detailed, \ -developer-targeted descriptions, with conceptual overviews, definitions of \ -terms, workarounds, and working code examples. +CORE_BOTTOM_TEXT := \ + $(BUG_SUBMIT_LINE) \ +
      For further API reference and developer documentation, see \ + Java SE \ + Documentation. That documentation contains more detailed, \ + developer-targeted descriptions, with conceptual overviews, definitions of \ + terms, workarounds, and working code examples. ifeq ($(VERSION_IS_GA), true) - DRAFT_HEADER := - DRAFT_BOTTOM := - DRAFT_WINTITLE := - CORE_TOP_EARLYACCESS := + DRAFT_MARKER := + DRAFT_WINDOW_TITLE_MARKER := + EARLYACCESS_TOP := else # We need a draft format when not building the GA version. - DRAFT_HEADER :=
      DRAFT $(VERSION_STRING) - DRAFT_BOTTOM :=
      DRAFT $(VERSION_STRING) + DRAFT_MARKER :=
      DRAFT $(VERSION_STRING) ifeq ($(VERSION_BUILD), 0) - DRAFT_WINTITLE := [ad-hoc build] + DRAFT_WINDOW_TITLE_MARKER := $(SPACE)[ad-hoc build] else - DRAFT_WINTITLE := [build $(VERSION_BUILD)] + DRAFT_WINDOW_TITLE_MARKER := $(SPACE)[build $(VERSION_BUILD)] endif - CORE_TOP_EARLYACCESS := \ -
      \ -
      \ -Please note that the specifications and other information contained herein are \ -not final and are subject to change. The information is being made available \ -to you solely for purpose of evaluation.
      + EARLYACCESS_TOP := \ +
      Please note that the specifications \ + and other information contained herein are not final and are subject to \ + change. The information is being made available to you solely for \ + purpose of evaluation.
      endif +################################################################################ +# Special treatment for the core package list. All separate "small" javadoc +# invocation needs to be able to see the core package list. + +ALL_PKG_DIRS := $(dir $(filter %.java, $(call CacheFind, \ + $(wildcard $(JAVADOC_SOURCE_DIRS))))) +ALL_SRC_PREFIXES := $(addsuffix /%, $(wildcard $(JAVADOC_SOURCE_DIRS))) +ALL_PKG_DIRNAMES := $(foreach prefix, $(ALL_SRC_PREFIXES), \ + $(patsubst $(prefix),%, $(filter $(prefix), $(ALL_PKG_DIRS)))) +ALL_PACKAGES := $(sort $(subst /,., $(patsubst %/, %, $(ALL_PKG_DIRNAMES)))) + +# Core packages are all packages beginning with java, javax or org, except a few +# excludes. +JAVA_PACKAGES := $(filter java.%, $(ALL_PACKAGES)) +JAVAX_PACKAGES := $(filter javax.%, $(ALL_PACKAGES)) +ORG_PACKAGES := $(filter org.%, $(ALL_PACKAGES)) + +# Allow custom makefile to add more excluded packages +CORE_EXCLUDED_PACKAGES += \ + java.awt.dnd.peer \ + java.awt.peer \ + javax.smartcardio \ + org.jcp.xml.dsig.internal% \ + org.w3c.dom.css \ + org.w3c.dom.html \ + org.w3c.dom.stylesheets \ + org.w3c.dom.xpath \ + # + +CORE_PACKAGES := $(filter-out $(CORE_EXCLUDED_PACKAGES), \ + $(JAVA_PACKAGES) $(JAVAX_PACKAGES) $(ORG_PACKAGES)) + +CORE_PACKAGES_LIST_DIR := $(SUPPORT_OUTPUTDIR)/docs/core-packages +CORE_PACKAGES_LIST_FILE := $(CORE_PACKAGES_LIST_DIR)/package-list + +CORE_PACKAGES_VARDEPS_FILE := $(call DependOnVariable, CORE_PACKAGES, \ + $(CORE_PACKAGES_LIST_FILE).vardeps) + +$(CORE_PACKAGES_LIST_FILE): $(CORE_PACKAGES_VARDEPS_FILE) + $(call MakeDir, $(@D)) + $(eval $(call ListPathsSafely, CORE_PACKAGES, $@)) + ################################################################################ # Support functions for SetupJavadocGeneration -# Print an option line to the target file -# Arguments: -# arg 1: the option name -# arg 2-3: optional arguments to the option -define AddOption - $(PRINTF) "%s$(if $(strip $2), '%s',)$(if $(strip $3), '%s',)\n" \ - "$(strip $1)"$(if $(strip $2), '$(strip $2)',)$(if $(strip $3), \ - '$(strip $3)',) >> $@ -endef - -# This function goes to great pains to exactly mimic the old behavior -# in all details, including whitespace. +# Generate the text used in the -bottom argument. # Note that COPYRIGHT_YEAR is the current year (from spec.gmk) # Arguments: # arg 1: first copyright year @@ -131,6 +156,34 @@ endef # Speed up finding by filling cache $(eval $(call FillCacheFind, $(wildcard $(JAVADOC_SOURCE_DIRS)))) +# In order to get a specific ordering it's necessary to specify the total +# ordering of tags as the tags are otherwise ordered in order of definition. +DEFAULT_JAVADOC_TAGS := \ + -tag beaninfo:X \ + -tag revised:X \ + -tag since.unbundled:X \ + -tag spec:X \ + -tag specdefault:X \ + -tag Note:X \ + -tag ToDo:X \ + -tag 'apiNote:a:API Note:' \ + -tag 'implSpec:a:Implementation Requirements:' \ + -tag 'implNote:a:Implementation Note:' \ + -tag param \ + -tag return \ + -tag throws \ + -tag since \ + -tag version \ + -tag serialData \ + -tag factory \ + -tag see \ + -tag 'jvms:a:See The Java™ Virtual Machine Specification:' \ + -tag 'jls:a:See The Java™ Language Specification:' \ + # + +DEFAULT_JAVADOC_OPTIONS := -XDignore.symbol.file=true -use -keywords -notimestamp \ + -serialwarn -encoding ISO-8859-1 -breakiterator --system none + ################################################################################ # Setup make rules for running javadoc. # @@ -171,151 +224,100 @@ define SetupJavadocGenerationBody # The non-core api javadocs need to be able to access the root of the core # api directory, so for jdk/api or jre/api to get to the core api/ # directory we would use this - $1_RELATIVE_CORE_DIR := $$(strip $$(subst $$(call DirToDotDot, \ - $$(JAVADOC_OUTPUTDIR))/,, $$(call DirToDotDot, \ - $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)))) + $1_RELATIVE_CORE_DIR := $$(call DirToDotDot, $$($1_OUTPUT_DIRNAME))/api - $1_DEPS += $(CORE_INDEX_FILE) + # We need to tell javadoc the directory in which to find the core package-list + $1_OPTIONS += -linkoffline $$($1_RELATIVE_CORE_DIR) $$(CORE_PACKAGES_LIST_DIR) + + $1_DEPS += $(CORE_PACKAGES_LIST_FILE) endif - ifneq ($$($1_OVERVIEW), ) - $1_DEPS += $$($1_OVERVIEW) + $1_OPTIONS += --add-modules $$(call CommaList, $$($1_MODULES)) + + ifneq ($$(LOG_LEVEL), trace) + $1_OPTIONS += -quiet endif - ifeq ($$($1_DISABLED_DOCLINT), ) - $1_DOCLINT := all - else - # Create a string like "all,-syntax,-html" - $1_DOCLINT := all,$$(call CommaList, $$(addprefix -, $$($1_DISABLED_DOCLINT))) + ifneq ($$($1_DISABLED_DOCLINT), ) + # Create a string like ",-syntax,-html" + $1_DOCLINT_EXCEPTIONS := ,$$(call CommaList, $$(addprefix -, $$($1_DISABLED_DOCLINT))) + endif + $1_OPTIONS += -Xdoclint:all$$($1_DOCLINT_EXCEPTIONS) + + ifneq ($$($1_DOCLINT_PACKAGES), ) + $1_OPTIONS += -Xdoclint/package:$$(call CommaList, $$($1_DOCLINT_PACKAGES)) endif ifeq ($$($1_DOC_TITLE), ) $1_DOC_TITLE := $$($1_TITLE) endif + $1_OPTIONS += -doctitle '$$($1_DOC_TITLE)' ifeq ($$($1_WINDOW_TITLE), ) $1_WINDOW_TITLE := $$(strip $$(subst ™,, $$($1_TITLE))) endif + $1_OPTIONS += -windowtitle '$$($1_WINDOW_TITLE)$$(DRAFT_WINDOW_TITLE_MARKER)' ifeq ($$($1_HEADER_TITLE), ) $1_HEADER_TITLE := $$(strip $$(subst ™,, $$($1_TITLE))) endif - $1_HEADER := $$($1_HEADER_TITLE) + $1_OPTIONS += -header '$$($1_HEADER_TITLE)$$(DRAFT_MARKER)' + + ifneq ($$($1_EXTRA_TOP), ) + $1_OPTIONS += -top '$$($1_EXTRA_TOP)' + endif ifeq ($$($1_BOTTOM_TEXT), ) $1_BOTTOM_TEXT := $(COMMON_BOTTOM_TEXT) endif - $1_BOTTOM := $$(call GenerateBottom, $$($1_FIRST_COPYRIGHT_YEAR), \ $$($1_BOTTOM_COPYRIGHT_URL), $$($1_BOTTOM_TEXT)) + $1_OPTIONS += -bottom '$$($1_BOTTOM)$$(DRAFT_MARKER)' - # The index.html, options, and packages files - $1_INDEX_FILE := $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)/index.html - $1_OPTIONS_FILE := $$(SUPPORT_OUTPUTDIR)/docs/$1.options - $1_PACKAGES_FILE := $$(SUPPORT_OUTPUTDIR)/docs/$1.packages + ifneq ($$($1_OVERVIEW), ) + $1_OPTIONS += -overview $$($1_OVERVIEW) + $1_DEPS += $$($1_OVERVIEW) + endif - $1_PACKAGES_VARDEPS := $$($1_PACKAGES) - $1_PACKAGES_VARDEPS_FILE := $$(call DependOnVariable, $1_PACKAGES_VARDEPS, \ - $$($1_PACKAGES_FILE).vardeps) + ifneq ($$($1_SPLIT_INDEX), ) + $1_OPTIONS += -splitIndex + endif - # Rule for creating a file with the package names in it - $$($1_PACKAGES_FILE): $$($1_PACKAGES_VARDEPS_FILE) - $$(call LogInfo, Creating Javadoc package file for $1) - $$(call MakeDir, $$(@D)) - $$(ECHO) $$($1_PACKAGES) | $$(TR) ' ' '\n' > $$@ + ifneq ($$($DOCROOTPARENT_FLAG), ) + $1_OPTIONS += -Xdocrootparent $(JAVADOC_BASE_URL) + endif - $1_OPTIONS_VARDEPS := $$($1_EXTRA_TOP) \ - $$($DOCROOTPARENT_FLAG) $$(JAVADOC_BASE_URL) $$($1_DISABLED_DOCLINT) \ - $$($1_DOCLINT_PACKAGES) $$(JAVADOC_SOURCE_DIRS) $$($1_MODULES) \ - $$($1_SPLIT_INDEX) $$($1_OVERVIEW) $$($1_DOC_TITLE) $$($1_WINDOW_TITLE) \ - $$(DRAFT_WINTITLE) $$($1_HEADER) $$(DRAFT_HEADER) $$($1_BOTTOM) \ - $$(DRAFT_BOTTOM)) $$($1_RELATIVE_CORE_DIR) $$(JAVADOC_OUTPUTDIR) - $1_OPTIONS_VARDEPS_FILE := $$(call DependOnVariable, $1_OPTIONS_VARDEPS, \ - $$($1_OPTIONS_FILE).vardeps) - - # Rule for creating a file with javadoc options in it - $$($1_OPTIONS_FILE): $$($1_OPTIONS_VARDEPS_FILE) - $$(call LogInfo, Creating Javadoc options file for $1) - $$(call MakeDir, $$(@D)) - $$(RM) $$@ - $$(call AddOption, -XDignore.symbol.file=true) - ifneq ($$(LOG_LEVEL), trace) - $$(call AddOption, -quiet) - endif - $$(call AddOption, -use) - $$(call AddOption, -keywords) - ifneq ($$($DOCROOTPARENT_FLAG), ) - $$(call AddOption, -Xdocrootparent, $(JAVADOC_BASE_URL)) - endif - # In order to get a specific ordering it's necessary to specify the total - # ordering of tags as the tags are otherwise ordered in order of definition. - $$(call AddOption, -tag, beaninfo:X) - $$(call AddOption, -tag, revised:X) - $$(call AddOption, -tag, since.unbundled:X) - $$(call AddOption, -tag, spec:X) - $$(call AddOption, -tag, specdefault:X) - $$(call AddOption, -tag, Note:X) - $$(call AddOption, -tag, ToDo:X) - $$(call AddOption, -tag, apiNote:a:API Note:) - $$(call AddOption, -tag, implSpec:a:Implementation Requirements:) - $$(call AddOption, -tag, implNote:a:Implementation Note:) - $$(call AddOption, -tag, param) - $$(call AddOption, -tag, return) - $$(call AddOption, -tag, throws) - $$(call AddOption, -tag, since) - $$(call AddOption, -tag, version) - $$(call AddOption, -tag, serialData) - $$(call AddOption, -tag, factory) - $$(call AddOption, -tag, see) - $$(call AddOption, -tag, \ - jvms:a:See The Java™ Virtual Machine Specification:) - $$(call AddOption, -tag, \ - jls:a:See The Java™ Language Specification:) - $$(call AddOption, -Xdoclint:$$($1_DOCLINT)) - ifneq ($$($1_DOCLINT_PACKAGES), ) - $$(call AddOption, -Xdoclint/package:$$(call CommaList, $$($1_DOCLINT_PACKAGES))) - endif - $$(call AddOption, --system, none) - $$(call AddOption, --module-source-path, $$(subst ",, $$(call PathList, $$(JAVADOC_SOURCE_DIRS)))) - $$(call AddOption, --add-modules, $$(call CommaList, $$($1_MODULES))) - $$(call AddOption, -encoding, ISO-8859-1) - $$(call AddOption, -breakiterator) - $$(call AddOption, -serialwarn) - $$(call AddOption, -notimestamp) - ifneq ($$($1_SPLIT_INDEX), ) - $$(call AddOption, -splitIndex) - endif - ifneq ($$($1_OVERVIEW), ) - $$(call AddOption, -overview, $$($1_OVERVIEW)) - endif - $$(call AddOption, -doctitle, $$($1_DOC_TITLE)) - $$(call AddOption, -windowtitle, $$($1_WINDOW_TITLE) $$(DRAFT_WINTITLE)) - $$(call AddOption, -header, $$($1_HEADER)$$(DRAFT_HEADER)) - $$(call AddOption, -bottom, $$($1_BOTTOM)$$(DRAFT_BOTTOM)) - ifneq ($$($1_RELATIVE_CORE_DIR), ) - $$(call AddOption, -linkoffline, $$($1_RELATIVE_CORE_DIR)/api, $$(JAVADOC_OUTPUTDIR)/api/) - endif - ifneq ($$($1_EXTRA_TOP), ) - $$(call AddOption, -top, $$($1_EXTRA_TOP)) - endif + $1_VARDEPS := $$($1_OPTIONS) $$($1_PACKAGES) + $1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, \ + $$(SUPPORT_OUTPUTDIR)/docs/$1.vardeps) $1_PACKAGE_DEPS := $$(call CacheFind, $$(wildcard $$(foreach p, \ $$(subst .,/,$$(strip $$($1_PACKAGES))), \ $$(addsuffix /$$p, $$(wildcard $$(JAVADOC_SOURCE_DIRS)))))) + # If there are many packages, use an @-file... + ifneq ($$(word 17, $$($1_PACKAGES)), ) + $1_PACKAGES_FILE := $$(SUPPORT_OUTPUTDIR)/docs/$1.packages + $1_PACKAGES_ARG := @$$($1_PACKAGES_FILE) + else + $1_PACKAGES_ARG := $$($1_PACKAGES) + endif + + # The index.html which is a marker for all the output from javadoc. + $1_INDEX_FILE := $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)/index.html + # Rule for actually running javadoc - $$($1_INDEX_FILE): $$($1_OPTIONS_FILE) $$($1_PACKAGES_FILE) \ - $$($1_PACKAGE_DEPS) $$($1_DEPS) - $$(call LogWarn, Generating Javadoc for $$($1_OUTPUT_DIRNAME)) + $$($1_INDEX_FILE): $$($1_VARDEPS_FILE) $$($1_PACKAGE_DEPS) $$($1_DEPS) + $$(call LogWarn, Generating Javadoc from $$(words $$($1_PACKAGES)) package(s) for $$($1_OUTPUT_DIRNAME)) $$(call MakeDir, $$(@D)) - ifneq ($$(findstring $$(LOG_LEVEL), debug trace),) - $$(ECHO) "Contents of $$($1_OPTIONS_FILE):" `$$(CAT) $$($1_OPTIONS_FILE)` - $$(ECHO) "Contents of $$($1_PACKAGES_FILE):" `$$(CAT) $$($1_PACKAGES_FILE)` + ifneq ($$($1_PACKAGES_FILE), ) + $$(eval $$(call ListPathsSafely, $1_PACKAGES, $$($1_PACKAGES_FILE))) endif $$(call ExecuteWithLog, $$(SUPPORT_OUTPUTDIR)/docs/$1.javadoc, \ $$($1_JAVA) -Djava.awt.headless=true $(NEW_JAVADOC) -d $$(@D) \ - @$$($1_OPTIONS_FILE) @$$($1_PACKAGES_FILE)) - $$(TOUCH) $$($1_INDEX_FILE) + $$(DEFAULT_JAVADOC_TAGS) $$(DEFAULT_JAVADOC_OPTIONS) \ + --module-source-path $$(call PathList, $$(JAVADOC_SOURCE_DIRS)) \ + $$($1_OPTIONS) $$($1_PACKAGES_ARG)) # The output returned will be the index.html file $1 := $$($1_INDEX_FILE) @@ -323,35 +325,6 @@ endef ################################################################################ -# Core packages are all packages beginning with java, javax or org, except a few -# excludes. - -ALL_PKG_DIRS := $(dir $(filter %.java, $(call CacheFind, \ - $(wildcard $(JAVADOC_SOURCE_DIRS))))) -ALL_SRC_PREFIXES := $(addsuffix /%, $(wildcard $(JAVADOC_SOURCE_DIRS))) -ALL_PKG_DIRNAMES := $(foreach prefix, $(ALL_SRC_PREFIXES), \ - $(patsubst $(prefix),%, $(filter $(prefix), $(ALL_PKG_DIRS)))) -ALL_PACKAGES := $(sort $(subst /,., $(patsubst %/, %, $(ALL_PKG_DIRNAMES)))) - -JAVA_PACKAGES := $(filter java.%, $(ALL_PACKAGES)) -JAVAX_PACKAGES := $(filter javax.%, $(ALL_PACKAGES)) -ORG_PACKAGES := $(filter org.%, $(ALL_PACKAGES)) - -# Allow custom makefile to add more excluded packages -CORE_EXCLUDED_PACKAGES += \ - java.awt.dnd.peer \ - java.awt.peer \ - javax.smartcardio \ - org.jcp.xml.dsig.internal% \ - org.w3c.dom.css \ - org.w3c.dom.html \ - org.w3c.dom.stylesheets \ - org.w3c.dom.xpath \ - # - -CORE_PACKAGES := $(filter-out $(CORE_EXCLUDED_PACKAGES), \ - $(JAVA_PACKAGES) $(JAVAX_PACKAGES) $(ORG_PACKAGES)) - $(eval $(call SetupJavadocGeneration, coredocs, \ MODULES := java.se.ee, \ PACKAGES := $(CORE_PACKAGES), \ @@ -367,7 +340,7 @@ $(eval $(call SetupJavadocGeneration, coredocs, \ SPLIT_INDEX := TRUE, \ BOTTOM_COPYRIGHT_URL := $(CORE_BOTTOM_COPYRIGHT_URL), \ BOTTOM_TEXT := $(CORE_BOTTOM_TEXT), \ - EXTRA_TOP := $(CORE_TOP_EARLYACCESS), \ + EXTRA_TOP := $(EARLYACCESS_TOP), \ )) TARGETS += $(coredocs) @@ -733,19 +706,13 @@ COPY_TARGETS += $(COPY_JVMTI_HTML) ################################################################################ # Optional target which bundles all generated javadocs into a zip archive. -# The dependency on docs is handled in Main.gmk. - -# Add the core docs as prerequisite to the archive to trigger a rebuild -# if the core docs were rebuilt. Ideally any doc rebuild should trigger -# this, but the way prerequisites are currently setup in this file, that -# is hard to achieve. JAVADOC_ARCHIVE_NAME := jdk-$(VERSION_STRING)-docs.zip JAVADOC_ARCHIVE_ASSEMBLY_DIR := $(SUPPORT_OUTPUTDIR)/docs/zip-docs JAVADOC_ARCHIVE_DIR := $(OUTPUT_ROOT)/bundles JAVADOC_ARCHIVE := $(JAVADOC_ARCHIVE_DIR)/$(JAVADOC_ARCHIVE_NAME) -$(JAVADOC_ARCHIVE): $(CORE_INDEX_FILE) +$(JAVADOC_ARCHIVE): $(TARGETS) $(COPY_TARGETS) $(call LogInfo, Compressing javadoc to single $(JAVADOC_ARCHIVE_NAME)) $(MKDIR) -p $(JAVADOC_ARCHIVE_DIR) $(RM) -r $(JAVADOC_ARCHIVE_ASSEMBLY_DIR) From 3da21ba32eab3aa9ca7bf8dea0a67f5fc86fee71 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 14:47:52 +0100 Subject: [PATCH 160/402] 8168037: Use ZIPEXE instead of ZIP to avoid clash with options for zip Reviewed-by: erikj --- common/autoconf/basics.m4 | 4 +- common/autoconf/generated-configure.sh | 106 +++++++++++++------------ common/autoconf/spec.gmk.in | 3 +- make/Bundles.gmk | 4 +- make/Javadoc.gmk | 2 +- make/Jprt.gmk | 6 +- make/common/JarArchive.gmk | 2 +- make/common/NativeCompilation.gmk | 2 +- make/common/ZipArchive.gmk | 2 +- 9 files changed, 67 insertions(+), 64 deletions(-) diff --git a/common/autoconf/basics.m4 b/common/autoconf/basics.m4 index 7f8c42f6b98..9d5789e37ca 100644 --- a/common/autoconf/basics.m4 +++ b/common/autoconf/basics.m4 @@ -1048,7 +1048,9 @@ AC_DEFUN_ONCE([BASIC_SETUP_COMPLEX_TOOLS], # These tools might not be installed by default, # need hint on how to install them. BASIC_REQUIRE_PROGS(UNZIP, unzip) - BASIC_REQUIRE_PROGS(ZIP, zip) + # Since zip uses "ZIP" as a environment variable for passing options, we need + # to name our variable differently, hence ZIPEXE. + BASIC_REQUIRE_PROGS(ZIPEXE, zip) # Non-required basic tools diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 238387046d6..55e9e3f4eca 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -945,7 +945,7 @@ HG READELF OTOOL LDD -ZIP +ZIPEXE UNZIP TAR_SUPPORTS_TRANSFORM TAR_INCLUDE_PARAM @@ -1292,7 +1292,7 @@ CPIO NICE MAKE UNZIP -ZIP +ZIPEXE LDD OTOOL READELF @@ -2236,7 +2236,7 @@ Some influential environment variables: NICE Override default value for NICE MAKE Override default value for MAKE UNZIP Override default value for UNZIP - ZIP Override default value for ZIP + ZIPEXE Override default value for ZIPEXE LDD Override default value for LDD OTOOL Override default value for OTOOL READELF Override default value for READELF @@ -5093,7 +5093,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1479120453 +DATE_WHEN_GENERATED=1479822431 ############################################################################### # @@ -21373,13 +21373,15 @@ $as_echo "$tool_specified" >&6; } fi + # Since zip uses "ZIP" as a environment variable for passing options, we need + # to name our variable differently, hence ZIPEXE. # Publish this variable in the help. - if [ -z "${ZIP+x}" ]; then + if [ -z "${ZIPEXE+x}" ]; then # The variable is not set by user, try to locate tool using the code snippet for ac_prog in zip do @@ -21387,12 +21389,12 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : +if ${ac_cv_path_ZIPEXE+:} false; then : $as_echo_n "(cached) " >&6 else - case $ZIP in + case $ZIPEXE in [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -21402,7 +21404,7 @@ do test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi @@ -21413,30 +21415,30 @@ IFS=$as_save_IFS ;; esac fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - test -n "$ZIP" && break + test -n "$ZIPEXE" && break done else # The variable is set, but is it from the command line or the environment? - # Try to remove the string !ZIP! from our list. - try_remove_var=${CONFIGURE_OVERRIDDEN_VARIABLES//!ZIP!/} + # Try to remove the string !ZIPEXE! from our list. + try_remove_var=${CONFIGURE_OVERRIDDEN_VARIABLES//!ZIPEXE!/} if test "x$try_remove_var" = "x$CONFIGURE_OVERRIDDEN_VARIABLES"; then # If it failed, the variable was not from the command line. Ignore it, # but warn the user (except for BASH, which is always set by the calling BASH). - if test "xZIP" != xBASH; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Ignoring value of ZIP from the environment. Use command line variables instead." >&5 -$as_echo "$as_me: WARNING: Ignoring value of ZIP from the environment. Use command line variables instead." >&2;} + if test "xZIPEXE" != xBASH; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Ignoring value of ZIPEXE from the environment. Use command line variables instead." >&5 +$as_echo "$as_me: WARNING: Ignoring value of ZIPEXE from the environment. Use command line variables instead." >&2;} fi # Try to locate tool using the code snippet for ac_prog in zip @@ -21445,12 +21447,12 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : +if ${ac_cv_path_ZIPEXE+:} false; then : $as_echo_n "(cached) " >&6 else - case $ZIP in + case $ZIPEXE in [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -21460,7 +21462,7 @@ do test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi @@ -21471,17 +21473,17 @@ IFS=$as_save_IFS ;; esac fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - test -n "$ZIP" && break + test -n "$ZIPEXE" && break done else @@ -21493,31 +21495,31 @@ done CONFIGURE_OVERRIDDEN_VARIABLES="$try_remove_var" # Check if we try to supply an empty value - if test "x$ZIP" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Setting user supplied tool ZIP= (no value)" >&5 -$as_echo "$as_me: Setting user supplied tool ZIP= (no value)" >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIP" >&5 -$as_echo_n "checking for ZIP... " >&6; } + if test "x$ZIPEXE" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: Setting user supplied tool ZIPEXE= (no value)" >&5 +$as_echo "$as_me: Setting user supplied tool ZIPEXE= (no value)" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIPEXE" >&5 +$as_echo_n "checking for ZIPEXE... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 $as_echo "disabled" >&6; } else # Check if the provided tool contains a complete path. - tool_specified="$ZIP" + tool_specified="$ZIPEXE" tool_basename="${tool_specified##*/}" if test "x$tool_basename" = "x$tool_specified"; then # A command without a complete path is provided, search $PATH. - { $as_echo "$as_me:${as_lineno-$LINENO}: Will search for user supplied tool ZIP=$tool_basename" >&5 -$as_echo "$as_me: Will search for user supplied tool ZIP=$tool_basename" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Will search for user supplied tool ZIPEXE=$tool_basename" >&5 +$as_echo "$as_me: Will search for user supplied tool ZIPEXE=$tool_basename" >&6;} # Extract the first word of "$tool_basename", so it can be a program name with args. set dummy $tool_basename; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : +if ${ac_cv_path_ZIPEXE+:} false; then : $as_echo_n "(cached) " >&6 else - case $ZIP in + case $ZIPEXE in [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -21527,7 +21529,7 @@ do test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi @@ -21538,29 +21540,29 @@ IFS=$as_save_IFS ;; esac fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - if test "x$ZIP" = x; then + if test "x$ZIPEXE" = x; then as_fn_error $? "User supplied tool $tool_basename could not be found" "$LINENO" 5 fi else # Otherwise we believe it is a complete path. Use it as it is. - { $as_echo "$as_me:${as_lineno-$LINENO}: Will use user supplied tool ZIP=$tool_specified" >&5 -$as_echo "$as_me: Will use user supplied tool ZIP=$tool_specified" >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIP" >&5 -$as_echo_n "checking for ZIP... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: Will use user supplied tool ZIPEXE=$tool_specified" >&5 +$as_echo "$as_me: Will use user supplied tool ZIPEXE=$tool_specified" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIPEXE" >&5 +$as_echo_n "checking for ZIPEXE... " >&6; } if test ! -x "$tool_specified"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 $as_echo "not found" >&6; } - as_fn_error $? "User supplied tool ZIP=$tool_specified does not exist or is not executable" "$LINENO" 5 + as_fn_error $? "User supplied tool ZIPEXE=$tool_specified does not exist or is not executable" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tool_specified" >&5 $as_echo "$tool_specified" >&6; } @@ -21572,8 +21574,8 @@ $as_echo "$tool_specified" >&6; } - if test "x$ZIP" = x; then - as_fn_error $? "Could not find required tool for ZIP" "$LINENO" 5 + if test "x$ZIPEXE" = x; then + as_fn_error $? "Could not find required tool for ZIPEXE" "$LINENO" 5 fi diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in index e2d7be936f6..1d7cdf263ed 100644 --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in @@ -657,8 +657,7 @@ TOUCH:=@TOUCH@ UNIQ:=@UNIQ@ WC:=@WC@ XARGS:=@XARGS@ -ZIPEXE:=@ZIP@ -ZIP:=@ZIP@ +ZIPEXE:=@ZIPEXE@ UNZIP:=@UNZIP@ MT:=@FIXPATH@ @MT@ RC:=@FIXPATH@ @RC@ diff --git a/make/Bundles.gmk b/make/Bundles.gmk index 989eb4aae69..5fa35e1ac6f 100644 --- a/make/Bundles.gmk +++ b/make/Bundles.gmk @@ -101,7 +101,7 @@ define SetupBundleFileBody ( $(TAR) cf - $(TAR_CREATE_EXTRA_PARAM) $$($1_SUBDIR) $(TAR_IGNORE_EXIT_VALUE) ) \ | $(GZIP) > $$@ else ifeq ($$($1_TYPE), zip) - $(CD) $(SUPPORT_OUTPUTDIR)/bundles/$1 && $(ZIP) -qr $$@ . + $(CD) $(SUPPORT_OUTPUTDIR)/bundles/$1 && $(ZIPEXE) -qr $$@ . endif endif else @@ -113,7 +113,7 @@ define SetupBundleFileBody | $(GZIP) > $$@ else ifeq ($$($1_TYPE), zip) $(CD) $$($1_BASE_DIR) \ - && $(ZIP) -qr $$@ . -i@$(SUPPORT_OUTPUTDIR)/bundles/_$1_files + && $(ZIPEXE) -qr $$@ . -i@$(SUPPORT_OUTPUTDIR)/bundles/_$1_files endif endif diff --git a/make/Javadoc.gmk b/make/Javadoc.gmk index 807fafb6092..b8c4da332dc 100644 --- a/make/Javadoc.gmk +++ b/make/Javadoc.gmk @@ -724,7 +724,7 @@ $(JAVADOC_ARCHIVE): $(TARGETS) $(COPY_TARGETS) name=`$(ECHO) $${target_dir} | $(SED) "s;/spec;;" | $(SED) "s;.*/;;"`; \ $(LN) -s $${target_dir} $${name}; \ done; \ - $(ZIP) -q -r $(JAVADOC_ARCHIVE) * ; \ + $(ZIPEXE) -q -r $(JAVADOC_ARCHIVE) * ; \ popd ; ZIP_TARGETS += $(JAVADOC_ARCHIVE) diff --git a/make/Jprt.gmk b/make/Jprt.gmk index 411525a143b..d42f361e1c9 100644 --- a/make/Jprt.gmk +++ b/make/Jprt.gmk @@ -71,11 +71,11 @@ ifeq ($(JPRT_TARGET), $(DEFAULT_MAKE_TARGET)) # This target must be called in the context of a SPEC file $(JPRT_ARCHIVE_BUNDLE): product-images $(call MakeDir, $(@D)) - $(CD) $(SRC_JDK_IMAGE_DIR) && $(ZIP) -y -q -r $@ . + $(CD) $(SRC_JDK_IMAGE_DIR) && $(ZIPEXE) -y -q -r $@ . $(JPRT_ARCHIVE_TEST_BUNDLE): test-image $(call MakeDir, $(@D)) - $(CD) $(SRC_TEST_IMAGE_DIR) && $(ZIP) -y -q -r $@ . + $(CD) $(SRC_TEST_IMAGE_DIR) && $(ZIPEXE) -y -q -r $@ . ############################################################################## # Optional symbols bundle @@ -85,7 +85,7 @@ ifeq ($(JPRT_TARGET), $(DEFAULT_MAKE_TARGET)) $(JPRT_ARCHIVE_SYMBOLS_BUNDLE): product-images $(call MakeDir, $(@D)) - $(CD) $(SYMBOLS_IMAGE_DIR) && $(ZIP) -y -q -r $@ . + $(CD) $(SYMBOLS_IMAGE_DIR) && $(ZIPEXE) -y -q -r $@ . endif diff --git a/make/common/JarArchive.gmk b/make/common/JarArchive.gmk index 4ca2af1a413..1d6d45531f2 100644 --- a/make/common/JarArchive.gmk +++ b/make/common/JarArchive.gmk @@ -264,7 +264,7 @@ define SetupJarArchiveBody $(CAT) $$($1_DELETES_FILE) > $$($1_DELETESS_FILE) $$(NEWLINE) \ if [ -s $$($1_DELETESS_FILE) ]; then \ $(ECHO) " deleting" `$(WC) -l $$($1_DELETESS_FILE) | $(AWK) '{ print $$$$1 }'` files && \ - $(ZIP) -q -d $$@ `$(CAT) $$($1_DELETESS_FILE)` ; \ + $(ZIPEXE) -q -d $$@ `$(CAT) $$($1_DELETESS_FILE)` ; \ fi $$(NEWLINE) \ $$($1_UPDATE_CONTENTS) true $$(NEWLINE) \ $$($1_JARINDEX) && true ) diff --git a/make/common/NativeCompilation.gmk b/make/common/NativeCompilation.gmk index e94ea5e479e..36e0381facc 100644 --- a/make/common/NativeCompilation.gmk +++ b/make/common/NativeCompilation.gmk @@ -875,7 +875,7 @@ define SetupNativeCompilationBody # to be rebuilt properly. $$($1_DEBUGINFO_ZIP): $$($1_DEBUGINFO_FILES) $$($1_TARGET) $(CD) $$($1_OUTPUT_DIR) && \ - $(ZIP) -q -r $$@ $$(subst $$($1_OUTPUT_DIR)/,, $$($1_DEBUGINFO_FILES)) + $(ZIPEXE) -q -r $$@ $$(subst $$($1_OUTPUT_DIR)/,, $$($1_DEBUGINFO_FILES)) endif endif # !STATIC_LIBRARY diff --git a/make/common/ZipArchive.gmk b/make/common/ZipArchive.gmk index 80fb28f48fe..79806dee0c9 100644 --- a/make/common/ZipArchive.gmk +++ b/make/common/ZipArchive.gmk @@ -107,7 +107,7 @@ define SetupZipArchiveBody $$($1_ZIP) : $$($1_ALL_SRCS) $$($1_EXTRA_DEPS) $(MKDIR) -p $$(@D) $(ECHO) Updating $$($1_NAME) - $$(foreach i,$$($1_SRC),(cd $$i && $(ZIP) -qru $$($1_ZIP_OPTIONS) $$@ . $$($1_ZIP_INCLUDES) \ + $$(foreach i,$$($1_SRC),(cd $$i && $(ZIPEXE) -qru $$($1_ZIP_OPTIONS) $$@ . $$($1_ZIP_INCLUDES) \ $$($1_ZIP_EXCLUDES) -x \*_the.\* \ $$(addprefix -x$(SPACE), $$(patsubst $$i/%,%, $$($1_EXCLUDE_FILES))) \ || test "$$$$?" = "12" )$$(NEWLINE)) true From 5ef25cb29eef52069bad5b740d0699eeb7949344 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 14:48:16 +0100 Subject: [PATCH 161/402] 8168037: Use ZIPEXE instead of ZIP to avoid clash with options for zip Reviewed-by: erikj --- hotspot/make/lib/CompileLibjsig.gmk | 2 +- hotspot/test/Makefile | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hotspot/make/lib/CompileLibjsig.gmk b/hotspot/make/lib/CompileLibjsig.gmk index 52c2896b190..bc26ae4362c 100644 --- a/hotspot/make/lib/CompileLibjsig.gmk +++ b/hotspot/make/lib/CompileLibjsig.gmk @@ -129,7 +129,7 @@ ifneq ($(OPENJDK_TARGET_OS), windows) ifeq ($(ZIP_EXTERNAL_DEBUG_SYMBOLS), true) $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig.diz: \ $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig$(DEBUG_INFO_SUFFIX) - $(CD) $$(@D) && $(ZIP) -q -y $$@ $$(basename $$(@F))$(DEBUG_INFO_SUFFIX) + $(CD) $$(@D) && $(ZIPEXE) -q -y $$@ $$(basename $$(@F))$(DEBUG_INFO_SUFFIX) TARGETS += $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig.diz endif diff --git a/hotspot/test/Makefile b/hotspot/test/Makefile index b852714c906..6e38234f52d 100644 --- a/hotspot/test/Makefile +++ b/hotspot/test/Makefile @@ -50,7 +50,7 @@ TEE = tee UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip define NEWLINE @@ -213,7 +213,7 @@ endif ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") @@ -327,7 +327,7 @@ ifdef NUM_CORES else ifeq ($(shell expr $(CONCURRENCY) \> 12), 1) CONCURRENCY := 12 endif -else +else CONCURRENCY := 1 endif JTREG_BASIC_OPTIONS += -concurrency:$(CONCURRENCY) From 895d5ab5ab1f2dc7be1f33d70d6b91331dd24764 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 14:48:16 +0100 Subject: [PATCH 162/402] 8168037: Use ZIPEXE instead of ZIP to avoid clash with options for zip Reviewed-by: erikj --- jdk/test/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/test/Makefile b/jdk/test/Makefile index 6a979a4175e..d417600da79 100644 --- a/jdk/test/Makefile +++ b/jdk/test/Makefile @@ -55,7 +55,7 @@ TEE = tee UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip # Get OS name from uname (Cygwin inexplicably adds _NT-5.1) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) @@ -162,7 +162,7 @@ endif ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") From 5ae350661c48357389eebcb919627ac498994849 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 14:48:16 +0100 Subject: [PATCH 163/402] 8168037: Use ZIPEXE instead of ZIP to avoid clash with options for zip Reviewed-by: erikj --- jaxp/test/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jaxp/test/Makefile b/jaxp/test/Makefile index 63f19044ef9..7bb73544de6 100644 --- a/jaxp/test/Makefile +++ b/jaxp/test/Makefile @@ -55,7 +55,7 @@ TEE = tee UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip # Get OS name from uname (Cygwin inexplicably adds _NT-5.1) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) @@ -130,7 +130,7 @@ endif ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") From 1f035a5b937ff79926b5d6e643c6b7e3c4823c1a Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 14:48:16 +0100 Subject: [PATCH 164/402] 8168037: Use ZIPEXE instead of ZIP to avoid clash with options for zip Reviewed-by: erikj --- nashorn/test/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nashorn/test/Makefile b/nashorn/test/Makefile index 6d6eb008577..d4fec83ae78 100644 --- a/nashorn/test/Makefile +++ b/nashorn/test/Makefile @@ -55,7 +55,7 @@ TEE = tee UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip # Get OS name from uname (Cygwin inexplicably adds _NT-5.1) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) @@ -149,7 +149,7 @@ endif ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") From 0915733851347f30fb179ffa7d5cab9a5aa08460 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 22 Nov 2016 15:04:19 +0100 Subject: [PATCH 165/402] 8170184: Remove incorrect comments about generated jvmt.h Reviewed-by: alanb, erikj --- hotspot/make/gensrc/GensrcJvmti.gmk | 2 -- 1 file changed, 2 deletions(-) diff --git a/hotspot/make/gensrc/GensrcJvmti.gmk b/hotspot/make/gensrc/GensrcJvmti.gmk index b834eae5673..d91c2b6346f 100644 --- a/hotspot/make/gensrc/GensrcJvmti.gmk +++ b/hotspot/make/gensrc/GensrcJvmti.gmk @@ -130,8 +130,6 @@ $(JVMTI_OUTPUTDIR)/jvmtiEnvRecommended.cpp: $(JVMTI_SRCDIR)/jvmtiEnv.cpp \ TARGETS += $(JVMTI_OUTPUTDIR)/jvmtiEnvRecommended.cpp ################################################################################ -# Disable copy of jvmti.h from hotspot until this has been cleared up. The file -# is currently being copied from the jdk repository. See JDK-8167078. # Copy jvmti.h to include dir # The file is the same regardless of jvm variant. Only let one do the copy. From fe1b93aeabc350eeea63e92769cd7a8b55c235e4 Mon Sep 17 00:00:00 2001 From: Frank Yuan Date: Tue, 22 Nov 2016 07:04:43 -0800 Subject: [PATCH 166/402] 8170170: Problem list ExternalEditorTest.java on all platforms Reviewed-by: darcy --- langtools/test/ProblemList.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/langtools/test/ProblemList.txt b/langtools/test/ProblemList.txt index 2977850c748..d4a9a494913 100644 --- a/langtools/test/ProblemList.txt +++ b/langtools/test/ProblemList.txt @@ -38,7 +38,7 @@ jdk/javadoc/doclet/testIOException/TestIOException.java jdk/jshell/EditorPadTest.java 8161276 windows-all Test set-up cannot press buttons jdk/jshell/ToolBasicTest.java 8139873 generic-all JShell tests failing -jdk/jshell/ExternalEditorTest.java 8170108 windows-all +jdk/jshell/ExternalEditorTest.java 8170108 generic-all ########################################################################### # From 9341d6fc604a8b3a861a883175c63e0fb134ed1d Mon Sep 17 00:00:00 2001 From: Phil Race Date: Tue, 22 Nov 2016 10:43:49 -0800 Subject: [PATCH 167/402] 8169887: javax/swing/JEditorPane/8080972/TestJEditor.java, javax/swing/text/View/8080972/TestObjectView.java are failing Reviewed-by: serb, alexsch --- .../macosx/classes/com/apple/laf/AquaUtils.java | 3 ++- .../com/sun/beans/decoder/DocumentHandler.java | 3 ++- .../classes/com/sun/beans/finder/InstanceFinder.java | 3 ++- .../com/sun/java/swing/plaf/gtk/GTKStyle.java | 3 ++- .../com/sun/media/sound/JARSoundbankReader.java | 3 ++- .../com/sun/media/sound/ModelAbstractOscillator.java | 3 ++- .../share/classes/java/beans/Introspector.java | 3 ++- .../share/classes/java/beans/MetaData.java | 4 ++-- .../share/classes/java/beans/PropertyDescriptor.java | 5 +++-- .../share/classes/javax/swing/JEditorPane.java | 3 ++- .../share/classes/javax/swing/UIManager.java | 12 ++++++++---- .../classes/javax/swing/text/html/ObjectView.java | 5 +++-- .../javax/swing/JEditorPane/8080972/TestJEditor.java | 2 +- .../swing/text/View/8080972/TestObjectView.java | 2 +- 14 files changed, 34 insertions(+), 20 deletions(-) diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java index 1ebbc4b7ddb..306d6deae43 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java @@ -176,10 +176,11 @@ final class AquaUtils { } @Override + @SuppressWarnings("deprecation") T getInstance() { try { ReflectUtil.checkPackageAccess(clazz); - return clazz.getDeclaredConstructor().newInstance(); + return clazz.newInstance(); } catch (ReflectiveOperationException ignored) { } return null; diff --git a/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java b/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java index 4289911b0da..6c9607e7ea9 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java @@ -277,11 +277,12 @@ public final class DocumentHandler extends DefaultHandler { * @param attributes the attributes attached to the element */ @Override + @SuppressWarnings("deprecation") public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ElementHandler parent = this.handler; try { this.handler = - getElementHandler(qName).getDeclaredConstructor().newInstance(); + getElementHandler(qName).newInstance(); this.handler.setOwner(this); this.handler.setParent(parent); } diff --git a/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java b/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java index 1080cbcaef7..3c78494a462 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java @@ -86,6 +86,7 @@ class InstanceFinder { return null; } + @SuppressWarnings("deprecation") protected T instantiate(Class type, String name) { if (type != null) { try { @@ -94,7 +95,7 @@ class InstanceFinder { } if (this.type.isAssignableFrom(type)) { @SuppressWarnings("unchecked") - T tmp = (T) type.getDeclaredConstructor().newInstance(); + T tmp = (T) type.newInstance(); return tmp; } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java index 14f08601a25..23c3f872fb6 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java @@ -1125,13 +1125,14 @@ class GTKStyle extends SynthStyle implements GTKConstants { this.methodName = methodName; } + @SuppressWarnings("deprecation") public Object createValue(UIDefaults table) { try { Class c = Class.forName(className, true,Thread.currentThread(). getContextClassLoader()); if (methodName == null) { - return c.getDeclaredConstructor().newInstance(); + return c.newInstance(); } Method m = c.getMethod(methodName, (Class[])null); diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java index a5bb2b789ee..e01bc10cf39 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java @@ -70,6 +70,7 @@ public final class JARSoundbankReader extends SoundbankReader { } @Override + @SuppressWarnings("deprecation") public Soundbank getSoundbank(URL url) throws InvalidMidiDataException, IOException { if (!isZIP(url)) @@ -90,7 +91,7 @@ public final class JARSoundbankReader extends SoundbankReader { Class c = Class.forName(line.trim(), false, ucl); if (Soundbank.class.isAssignableFrom(c)) { ReflectUtil.checkPackageAccess(c); - Object o = c.getDeclaredConstructor().newInstance(); + Object o = c.newInstance(); soundbanks.add((Soundbank) o); } } catch (ReflectiveOperationException ignored) { diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java index 599e59e5f72..ea71352c6ff 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java @@ -134,10 +134,11 @@ public abstract class ModelAbstractOscillator } @Override + @SuppressWarnings("deprecation") public ModelOscillatorStream open(float samplerate) { ModelAbstractOscillator oscs; try { - oscs = this.getClass().getDeclaredConstructor().newInstance(); + oscs = this.getClass().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); } diff --git a/jdk/src/java.desktop/share/classes/java/beans/Introspector.java b/jdk/src/java.desktop/share/classes/java/beans/Introspector.java index 4bab862d5ff..4a9a8ba43bc 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/Introspector.java +++ b/jdk/src/java.desktop/share/classes/java/beans/Introspector.java @@ -1279,6 +1279,7 @@ public class Introspector { * First try the classloader of "sibling", then try the system * classloader then the class loader of the current Thread. */ + @SuppressWarnings("deprecation") static Object instantiate(Class sibling, String className) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, @@ -1286,7 +1287,7 @@ public class Introspector { // First check with sibling's classloader (if any). ClassLoader cl = sibling.getClassLoader(); Class cls = ClassFinder.findClass(className, cl); - return cls.getDeclaredConstructor().newInstance(); + return cls.newInstance(); } } // end class Introspector diff --git a/jdk/src/java.desktop/share/classes/java/beans/MetaData.java b/jdk/src/java.desktop/share/classes/java/beans/MetaData.java index c5adc1cf912..42a935475fc 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/MetaData.java +++ b/jdk/src/java.desktop/share/classes/java/beans/MetaData.java @@ -1219,7 +1219,7 @@ static final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Pe internalPersistenceDelegates.put("java.sql.Time", new java_util_Date_PersistenceDelegate()); } - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "deprecation"}) public static synchronized PersistenceDelegate getPersistenceDelegate(Class type) { if (type == null) { return nullPersistenceDelegate; @@ -1263,7 +1263,7 @@ static final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Pe String name = type.getName(); Class c = Class.forName("java.beans.MetaData$" + name.replace('.', '_') + "_PersistenceDelegate"); - pd = (PersistenceDelegate)c.getDeclaredConstructor().newInstance(); + pd = (PersistenceDelegate)c.newInstance(); internalPersistenceDelegates.put(typeName, pd); } catch (ClassNotFoundException e) { diff --git a/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java b/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java index 3d142b8baf9..5eb7a3c0c57 100644 --- a/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java +++ b/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java @@ -461,6 +461,7 @@ public class PropertyDescriptor extends FeatureDescriptor { * not been defined or cannot be created * @since 1.5 */ + @SuppressWarnings("deprecation") public PropertyEditor createPropertyEditor(Object bean) { Object editor = null; @@ -470,14 +471,14 @@ public class PropertyDescriptor extends FeatureDescriptor { Constructor ctor = null; if (bean != null) { try { - ctor = cls.getDeclaredConstructor(new Class[] { Object.class }); + ctor = cls.getConstructor(new Class[] { Object.class }); } catch (Exception ex) { // Fall through } } try { if (ctor == null) { - editor = cls.getDeclaredConstructor().newInstance(); + editor = cls.newInstance(); } else { editor = ctor.newInstance(new Object[] { bean }); } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java index 5f1056ef4d5..9fdafb65e0a 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java @@ -1180,6 +1180,7 @@ public class JEditorPane extends JTextComponent { * @return the editor kit, or null if there is nothing * registered for the given type */ + @SuppressWarnings("deprecation") public static EditorKit createEditorKitForContentType(String type) { Hashtable kitRegistry = getKitRegisty(); EditorKit k = kitRegistry.get(type); @@ -1197,7 +1198,7 @@ public class JEditorPane extends JTextComponent { // registerEditorKitForContentType(type, class, null). c = SwingUtilities.loadSystemClass(classname); } - k = (EditorKit) c.getDeclaredConstructor().newInstance(); + k = (EditorKit) c.newInstance(); kitRegistry.put(type, k); } catch (Throwable e) { k = null; diff --git a/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java b/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java index 33e4a4c27c1..9b9cad72d67 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java @@ -513,6 +513,7 @@ public class UIManager implements Serializable * * @since 9 */ + @SuppressWarnings("deprecation") public static LookAndFeel createLookAndFeel(String name) throws UnsupportedLookAndFeelException { Objects.requireNonNull(name); @@ -527,7 +528,7 @@ public class UIManager implements Serializable Class cls = Class.forName(UIManager.class.getModule(), info.getClassName()); LookAndFeel laf = - (LookAndFeel) cls.getDeclaredConstructor().newInstance(); + (LookAndFeel) cls.newInstance(); if (!laf.isSupportedLookAndFeel()) { break; } @@ -615,6 +616,7 @@ public class UIManager implements Serializable * @throws ClassCastException if {@code className} does not identify * a class that extends {@code LookAndFeel} */ + @SuppressWarnings("deprecation") public static void setLookAndFeel(String className) throws ClassNotFoundException, InstantiationException, @@ -629,7 +631,7 @@ public class UIManager implements Serializable Class lnfClass = SwingUtilities.loadSystemClass(className); try { LookAndFeel laf = - (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); + (LookAndFeel)lnfClass.newInstance(); setLookAndFeel(laf); } catch (ReflectiveOperationException | IllegalArgumentException e) { InstantiationException ex = @@ -1097,6 +1099,7 @@ public class UIManager implements Serializable /** * Finds the Multiplexing LookAndFeel. */ + @SuppressWarnings("deprecation") private static LookAndFeel getMultiLookAndFeel() { LookAndFeel multiLookAndFeel = getLAFState().multiLookAndFeel; if (multiLookAndFeel == null) { @@ -1105,7 +1108,7 @@ public class UIManager implements Serializable try { Class lnfClass = SwingUtilities.loadSystemClass(className); multiLookAndFeel = - (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); + (LookAndFeel)lnfClass.newInstance(); } catch (Exception exc) { System.err.println("UIManager: failed loading " + className); } @@ -1420,6 +1423,7 @@ public class UIManager implements Serializable } + @SuppressWarnings("deprecation") private static void initializeAuxiliaryLAFs(Properties swingProps) { String auxLookAndFeelNames = swingProps.getProperty(auxiliaryLAFsKey); @@ -1440,7 +1444,7 @@ public class UIManager implements Serializable try { Class lnfClass = SwingUtilities.loadSystemClass(className); LookAndFeel newLAF = - (LookAndFeel)lnfClass.getDeclaredConstructor().newInstance(); + (LookAndFeel)lnfClass.newInstance(); newLAF.initialize(); auxLookAndFeels.addElement(newLAF); } diff --git a/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java b/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java index f1f7e4f4f50..ad3b844451c 100644 --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java @@ -46,7 +46,7 @@ import sun.reflect.misc.ReflectUtil; *

      * If the class can successfully be loaded, an attempt will * be made to create an instance of it by calling - * Class.getDeclaredConstructor().newInstance. An attempt will be made + * Class.newInstance. An attempt will be made * to narrow the instance to type java.awt.Component * to display the object. *

      @@ -85,6 +85,7 @@ public class ObjectView extends ComponentView { * as a specification of the classname, which * we try to load. */ + @SuppressWarnings("deprecation") protected Component createComponent() { AttributeSet attr = getElement().getAttributes(); String classname = (String) attr.getAttribute(HTML.Attribute.CLASSID); @@ -92,7 +93,7 @@ public class ObjectView extends ComponentView { ReflectUtil.checkPackageAccess(classname); Class c = Class.forName(classname, true,Thread.currentThread(). getContextClassLoader()); - Object o = c.getDeclaredConstructor().newInstance(); + Object o = c.newInstance(); if (o instanceof Component) { Component comp = (Component) o; setParameters(comp, attr); diff --git a/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java b/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java index 7e12100ff00..c69af1bb7eb 100644 --- a/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java +++ b/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java @@ -36,7 +36,7 @@ import javax.swing.text.ViewFactory; /* * @test - * @bug 8080972 + * @bug 8080972 8169887 * @summary Audit Core Reflection in module java.desktop for places that will * require changes to work with modules * @author Alexander Scherbatiy diff --git a/jdk/test/javax/swing/text/View/8080972/TestObjectView.java b/jdk/test/javax/swing/text/View/8080972/TestObjectView.java index 772447ed250..a0a52f05a27 100644 --- a/jdk/test/javax/swing/text/View/8080972/TestObjectView.java +++ b/jdk/test/javax/swing/text/View/8080972/TestObjectView.java @@ -32,7 +32,7 @@ import javax.swing.text.html.HTML; import javax.swing.text.html.ObjectView; /* * @test - * @bug 8080972 + * @bug 8080972 8169887 * @summary Audit Core Reflection in module java.desktop for places that will * require changes to work with modules * @author Alexander Scherbatiy From 6e31f6440f1f396b3467224fc859d9f9613d3a91 Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Tue, 22 Nov 2016 15:57:32 -0800 Subject: [PATCH 168/402] 8164590: javac --inherit-runtime-environment fails with "cannot find modules: ALL-DEFAULT" Reviewed-by: mchung --- .../com/sun/tools/javac/main/Arguments.java | 5 +- .../com/sun/tools/javac/main/Option.java | 23 ++++- .../tools/javac/resources/compiler.properties | 4 + .../test/jdk/javadoc/tool/BadOptionsTest.java | 4 +- .../examples/BadNameForOption_Error.java | 28 ++++++ ...ion.java => BadNameForOption_Warning.java} | 0 .../tools/javac/modules/AddModulesTest.java | 4 +- .../tools/javac/modules/AllDefaultTest.java | 86 +++++++++++++++++++ .../tools/javac/modules/LimitModulesTest.java | 4 +- .../test/tools/javadoc/BadOptionsTest.java | 4 +- 10 files changed, 150 insertions(+), 12 deletions(-) create mode 100644 langtools/test/tools/javac/diags/examples/BadNameForOption_Error.java rename langtools/test/tools/javac/diags/examples/{BadNameForOption.java => BadNameForOption_Warning.java} (100%) create mode 100644 langtools/test/tools/javac/modules/AllDefaultTest.java diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java index 4855da3fa7c..007eeacfcf9 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java @@ -707,7 +707,6 @@ public class Arguments { for (String moduleName : addModules.split(",")) { switch (moduleName) { case "": - case "ALL-DEFAULT": case "ALL-SYSTEM": case "ALL-MODULE-PATH": break; @@ -715,7 +714,7 @@ public class Arguments { default: if (!SourceVersion.isName(moduleName, sv)) { // syntactically invalid module name: e.g. --add-modules m1,m! - log.warning(Warnings.BadNameForOption(Option.ADD_MODULES, moduleName)); + log.error(Errors.BadNameForOption(Option.ADD_MODULES, moduleName)); } break; } @@ -739,7 +738,7 @@ public class Arguments { default: if (!SourceVersion.isName(moduleName, sv)) { // syntactically invalid module name: e.g. --limit-modules m1,m! - log.warning(Warnings.BadNameForOption(Option.LIMIT_MODULES, moduleName)); + log.error(Errors.BadNameForOption(Option.LIMIT_MODULES, moduleName)); } break; } diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java index d30be4ca038..8d58c0abe74 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java @@ -682,11 +682,32 @@ public enum Option { Class.forName(JDK9Wrappers.VMHelper.VM_CLASSNAME); String[] runtimeArgs = JDK9Wrappers.VMHelper.getRuntimeArguments(); for (String arg : runtimeArgs) { + System.err.println("runtime arg: " + arg); // Handle any supported runtime options; ignore all others. // The runtime arguments always use the single token form, e.g. "--name=value". for (Option o : getSupportedRuntimeOptions()) { if (o.matches(arg)) { - o.handleOption(helper, arg, Collections.emptyIterator()); + switch (o) { + case ADD_MODULES: + int eq = arg.indexOf('='); + Assert.check(eq > 0, () -> ("invalid runtime option:" + arg)); + // --add-modules=ALL-DEFAULT is not supported at compile-time + // so remove it from list, and only process the rest + // if the set is non-empty. + // Note that --add-modules=ALL-DEFAULT is automatically added + // by the standard javac launcher. + String mods = Arrays.stream(arg.substring(eq + 1).split(",")) + .filter(s -> !s.isEmpty() && !s.equals("ALL-DEFAULT")) + .collect(Collectors.joining(",")); + if (!mods.isEmpty()) { + String updatedArg = arg.substring(0, eq + 1) + mods; + o.handleOption(helper, updatedArg, Collections.emptyIterator()); + } + break; + default: + o.handleOption(helper, arg, Collections.emptyIterator()); + break; + } break; } } diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties index 0e173fc133d..2dd58448592 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties @@ -2848,6 +2848,10 @@ compiler.err.duplicate.module.on.path=\ compiler.warn.bad.name.for.option=\ bad name in value for {0} option: ''{1}'' +# 0: option name, 1: string +compiler.err.bad.name.for.option=\ + bad name in value for {0} option: ''{1}'' + # 0: option name, 1: symbol compiler.warn.module.for.option.not.found=\ module name in {0} option not found: {1} diff --git a/langtools/test/jdk/javadoc/tool/BadOptionsTest.java b/langtools/test/jdk/javadoc/tool/BadOptionsTest.java index c816fa4ba9b..28ddf3b4257 100644 --- a/langtools/test/jdk/javadoc/tool/BadOptionsTest.java +++ b/langtools/test/jdk/javadoc/tool/BadOptionsTest.java @@ -103,10 +103,10 @@ public class BadOptionsTest extends TestRunner { .options("-quiet", "--add-modules", "123") .files(src.resolve("C.java")) - .run() + .run(Task.Expect.FAIL) .writeAll(); checkFound(result.getOutput(Task.OutputKind.DIRECT), - "warning: bad name in value for --add-modules option: '123'"); + "error: bad name in value for --add-modules option: '123'"); checkNotFound(result, "Exception", "at jdk.javadoc/"); } diff --git a/langtools/test/tools/javac/diags/examples/BadNameForOption_Error.java b/langtools/test/tools/javac/diags/examples/BadNameForOption_Error.java new file mode 100644 index 00000000000..5fa5cd9f2cc --- /dev/null +++ b/langtools/test/tools/javac/diags/examples/BadNameForOption_Error.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// key: compiler.err.bad.name.for.option +// options: --add-modules Bad!Name + +class BadNameForOption { } + diff --git a/langtools/test/tools/javac/diags/examples/BadNameForOption.java b/langtools/test/tools/javac/diags/examples/BadNameForOption_Warning.java similarity index 100% rename from langtools/test/tools/javac/diags/examples/BadNameForOption.java rename to langtools/test/tools/javac/diags/examples/BadNameForOption_Warning.java diff --git a/langtools/test/tools/javac/modules/AddModulesTest.java b/langtools/test/tools/javac/modules/AddModulesTest.java index 326d43ca4ef..9e89edaf855 100644 --- a/langtools/test/tools/javac/modules/AddModulesTest.java +++ b/langtools/test/tools/javac/modules/AddModulesTest.java @@ -126,12 +126,12 @@ public class AddModulesTest extends ModuleTestBase { "--add-modules", "BadModule!") .outdir(classes) .files(findJavaFiles(src)) - .run() + .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); checkOutputContains(log, - "- compiler.warn.bad.name.for.option: --add-modules, BadModule!"); + "- compiler.err.bad.name.for.option: --add-modules, BadModule!"); } @Test diff --git a/langtools/test/tools/javac/modules/AllDefaultTest.java b/langtools/test/tools/javac/modules/AllDefaultTest.java new file mode 100644 index 00000000000..f78b0f19209 --- /dev/null +++ b/langtools/test/tools/javac/modules/AllDefaultTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 0000000 + * @summary Test use of ALL-DEFAULT token + * @library /tools/lib + * @modules + * jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask toolbox.JavaTask ModuleTestBase + * @run main AllDefaultTest + */ + +import java.nio.file.Path; + +import toolbox.JavacTask; +import toolbox.Task; + +public class AllDefaultTest extends ModuleTestBase { + public static void main(String... args) throws Exception { + AllDefaultTest t = new AllDefaultTest(); + t.runTests(); + } + + @Test + public void testCompileTime_notAllowed(Path base) throws Exception { + tb.writeJavaFiles(base, "class C { }"); + String out = new JavacTask(tb) + .options("-XDrawDiagnostics", + "--add-modules=ALL-DEFAULT") + .files(tb.findJavaFiles(base)) + .run(Task.Expect.FAIL) + .writeAll() + .getOutput(Task.OutputKind.DIRECT); + + if (!out.contains("- compiler.err.bad.name.for.option: --add-modules, ALL-DEFAULT")) { + error("expected text not found"); + } + } + + @Test + public void testRuntimeTime_ignored_1(Path base) throws Exception { + tb.writeJavaFiles(base, "class C { }"); + new JavacTask(tb, Task.Mode.EXEC) + .options("-XDrawDiagnostics", + "-J--add-modules=ALL-DEFAULT", + "--inherit-runtime-environment") + .files(tb.findJavaFiles(base)) + .run() + .writeAll(); + } + + @Test + public void testRuntimeTime_ignored_2(Path base) throws Exception { + tb.writeJavaFiles(base, "class C { }"); + new JavacTask(tb, Task.Mode.EXEC) + .options("-XDrawDiagnostics", + "-J--add-modules=jdk.compiler", + "--inherit-runtime-environment") + .files(tb.findJavaFiles(base)) + .run() + .writeAll(); + } +} diff --git a/langtools/test/tools/javac/modules/LimitModulesTest.java b/langtools/test/tools/javac/modules/LimitModulesTest.java index cc489c962c5..3ed381196c3 100644 --- a/langtools/test/tools/javac/modules/LimitModulesTest.java +++ b/langtools/test/tools/javac/modules/LimitModulesTest.java @@ -144,11 +144,11 @@ public class LimitModulesTest extends ModuleTestBase { "--limit-modules", "BadModule!") .outdir(classes) .files(findJavaFiles(src)) - .run() + .run(Task.Expect.FAIL) .writeAll() .getOutput(Task.OutputKind.DIRECT); - if (!log.contains("- compiler.warn.bad.name.for.option: --limit-modules, BadModule!")) + if (!log.contains("- compiler.err.bad.name.for.option: --limit-modules, BadModule!")) throw new Exception("expected output not found"); } diff --git a/langtools/test/tools/javadoc/BadOptionsTest.java b/langtools/test/tools/javadoc/BadOptionsTest.java index 60c3be04c3c..4a3bb47f1ee 100644 --- a/langtools/test/tools/javadoc/BadOptionsTest.java +++ b/langtools/test/tools/javadoc/BadOptionsTest.java @@ -104,10 +104,10 @@ public class BadOptionsTest extends TestRunner { .options("-Xold", "-quiet", "--add-modules", "123") .files(src.resolve("C.java")) - .run() + .run(Task.Expect.FAIL) .writeAll(); checkFound(result.getOutput(Task.OutputKind.DIRECT), - "warning: bad name in value for --add-modules option: '123'"); + "error: bad name in value for --add-modules option: '123'"); checkNotFound(result, "Exception", "at jdk.javadoc/"); } From 2d7092c7acaffe529d6c4e3b7ae92dcfad3f83aa Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Tue, 22 Nov 2016 16:29:24 -0800 Subject: [PATCH 169/402] 8155765: javax.tools.ToolProvider::getSystemToolClassLoader returns app class loader even if no tool is available Reviewed-by: mchung --- .../classes/javax/tools/ToolProvider.java | 23 +++++++++++-------- .../test/tools/javac/6410653/T6410653.java | 5 ++-- .../api/ToolProvider/ToolProviderTest.java | 4 +++- .../options/release/ReleaseOptionClashes.java | 4 ++-- 4 files changed, 21 insertions(+), 15 deletions(-) diff --git a/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java b/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java index d861837c82e..a77f161aa81 100644 --- a/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java +++ b/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java @@ -57,7 +57,7 @@ public class ToolProvider { * {@code null} if no compiler is provided * @implNote This implementation returns the compiler provided * by the {@code jdk.compiler} module if that module is available, - * and null otherwise. + * and {@code null} otherwise. */ public static JavaCompiler getSystemJavaCompiler() { return getSystemTool(JavaCompiler.class, @@ -78,7 +78,7 @@ public class ToolProvider { * {@code null} if no documentation tool is provided * @implNote This implementation returns the tool provided * by the {@code jdk.javadoc} module if that module is available, - * and null otherwise. + * and {@code null} otherwise. */ public static DocumentationTool getSystemDocumentationTool() { return getSystemTool(DocumentationTool.class, @@ -86,16 +86,19 @@ public class ToolProvider { } /** - * Returns the class loader for tools provided with this platform. - * This does not include user-installed tools. Use the - * {@linkplain java.util.ServiceLoader service provider mechanism} - * for locating user installed tools. - * - * @return the class loader for tools provided with this platform - * or {@code null} if no tools are provided + * Returns a class loader that may be used to load system tools, + * or {@code null} if no such special loader is provided. + * @implSpec This implementation always returns {@code null}. + * @deprecated This method is subject to removal in a future version of + * Java SE. + * Use the {@link java.util.spi.ToolProvider system tool provider} or + * {@link java.util.ServiceLoader service loader} mechanisms to + * locate system tools as well as user-installed tools. + * @return a class loader, or {@code null} */ + @Deprecated public static ClassLoader getSystemToolClassLoader() { - return ClassLoader.getSystemClassLoader(); + return null; } private static final boolean useLegacy; diff --git a/langtools/test/tools/javac/6410653/T6410653.java b/langtools/test/tools/javac/6410653/T6410653.java index ff0d89a60e6..d2ee3a49b4c 100644 --- a/langtools/test/tools/javac/6410653/T6410653.java +++ b/langtools/test/tools/javac/6410653/T6410653.java @@ -31,6 +31,7 @@ */ import java.lang.reflect.Field; +import java.lang.reflect.Module; import java.io.File; import java.io.ByteArrayOutputStream; import javax.tools.*; @@ -39,9 +40,9 @@ public class T6410653 { public static void main(String... args) throws Exception { File testSrc = new File(System.getProperty("test.src")); String source = new File(testSrc, "T6410653.java").getPath(); - ClassLoader cl = ToolProvider.getSystemToolClassLoader(); Tool compiler = ToolProvider.getSystemJavaCompiler(); - Class log = Class.forName("com.sun.tools.javac.util.Log", true, cl); + Module compilerModule = compiler.getClass().getModule(); + Class log = Class.forName(compilerModule, "com.sun.tools.javac.util.Log"); Field useRawMessages = log.getDeclaredField("useRawMessages"); useRawMessages.setAccessible(true); useRawMessages.setBoolean(null, true); diff --git a/langtools/test/tools/javac/api/ToolProvider/ToolProviderTest.java b/langtools/test/tools/javac/api/ToolProvider/ToolProviderTest.java index c9000e72d39..85b5d3b28b1 100644 --- a/langtools/test/tools/javac/api/ToolProvider/ToolProviderTest.java +++ b/langtools/test/tools/javac/api/ToolProvider/ToolProviderTest.java @@ -55,6 +55,8 @@ public class ToolProviderTest { Objects.requireNonNull(ToolProvider.getSystemDocumentationTool()); Objects.requireNonNull(ToolProvider.getSystemJavaCompiler()); - Objects.requireNonNull(ToolProvider.getSystemToolClassLoader()); + if (ToolProvider.getSystemToolClassLoader() != null) { + throw new AssertionError("unexpected value for getSystemToolClassLoader"); + } } } diff --git a/langtools/test/tools/javac/options/release/ReleaseOptionClashes.java b/langtools/test/tools/javac/options/release/ReleaseOptionClashes.java index 80c8f6c4d8d..1fb6820834d 100644 --- a/langtools/test/tools/javac/options/release/ReleaseOptionClashes.java +++ b/langtools/test/tools/javac/options/release/ReleaseOptionClashes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,6 +82,6 @@ public class ReleaseOptionClashes { compiler.run(null, null, System.out, options.toArray(new String[0])); } - ClassLoader cl = ToolProvider.getSystemToolClassLoader(); Tool compiler = ToolProvider.getSystemJavaCompiler(); + ClassLoader cl = compiler.getClass().getClassLoader(); } From 3b349e495bd6dfd3f11a721b07819d25761eb0e0 Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Wed, 23 Nov 2016 10:12:01 +0800 Subject: [PATCH 170/402] 8170158: Remove ClassLoader/platformClassLoader/DefinePlatformClass.java from ProblemList Reviewed-by: dfuchs --- jdk/test/ProblemList.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index b252d116521..91e2c4b4f30 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -124,7 +124,6 @@ java/beans/Introspector/8132566/OverrideUserDefPropertyInfoTest.java 8132565 gen # jdk_lang java/lang/StringCoding/CheckEncodings.sh 7008363 generic-all -java/lang/ClassLoader/platformClassLoader/DefinePlatformClass.java 8169639 windows-all ############################################################################ From 85eded356224463365312e7e8d4d87876a66c045 Mon Sep 17 00:00:00 2001 From: Robert Field Date: Tue, 22 Nov 2016 19:24:02 -0800 Subject: [PATCH 171/402] 8169519: JShell: Handle start-up failures and hangs gracefully 8166581: JShell: locks forever if -R options is wrong 8169234: JShell: hangs on startup on some computers caused by hostname Reviewed-by: jlahoda --- .../share/classes/jdk/jshell/Eval.java | 9 +- .../share/classes/jdk/jshell/JShell.java | 42 +++++---- .../execution/JdiDefaultExecutionControl.java | 62 ++++++++++--- .../jdk/jshell/execution/JdiInitiator.java | 87 +++++++++++++++---- .../test/jdk/jshell/DyingRemoteAgent.java | 49 +++++++++++ ...ilOverExecutionControlDyingLaunchTest.java | 54 ++++++++++++ ...OverExecutionControlHangingLaunchTest.java | 54 ++++++++++++ ...OverExecutionControlHangingListenTest.java | 56 ++++++++++++ .../test/jdk/jshell/HangingRemoteAgent.java | 62 +++++++++++++ ...diBadOptionLaunchExecutionControlTest.java | 56 ++++++++++++ ...diBadOptionListenExecutionControlTest.java | 56 ++++++++++++ ...diBogusHostListenExecutionControlTest.java | 55 ++++++++++++ .../JdiFailingLaunchExecutionControlTest.java | 52 +++++++++++ .../JdiFailingListenExecutionControlTest.java | 52 +++++++++++ .../JdiHangingLaunchExecutionControlTest.java | 53 +++++++++++ .../JdiHangingListenExecutionControlTest.java | 53 +++++++++++ .../test/jdk/jshell/StartOptionTest.java | 14 ++- .../jdk/jshell/UserJdiUserRemoteTest.java | 7 +- 18 files changed, 822 insertions(+), 51 deletions(-) create mode 100644 langtools/test/jdk/jshell/DyingRemoteAgent.java create mode 100644 langtools/test/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java create mode 100644 langtools/test/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java create mode 100644 langtools/test/jdk/jshell/FailOverExecutionControlHangingListenTest.java create mode 100644 langtools/test/jdk/jshell/HangingRemoteAgent.java create mode 100644 langtools/test/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiBadOptionListenExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiBogusHostListenExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiFailingLaunchExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiFailingListenExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiHangingLaunchExecutionControlTest.java create mode 100644 langtools/test/jdk/jshell/JdiHangingListenExecutionControlTest.java diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java index 205e9b837af..21ba179c580 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/Eval.java @@ -719,11 +719,11 @@ class Eval { /** * If there are classes to load, loads by calling the execution engine. - * @param classbytecoes names of the classes to load. + * @param classbytecodes names of the classes to load. */ - private void load(Collection classbytecoes) { - if (!classbytecoes.isEmpty()) { - ClassBytecodes[] cbcs = classbytecoes.toArray(new ClassBytecodes[classbytecoes.size()]); + private void load(Collection classbytecodes) { + if (!classbytecodes.isEmpty()) { + ClassBytecodes[] cbcs = classbytecodes.toArray(new ClassBytecodes[classbytecodes.size()]); try { state.executionControl().load(cbcs); state.classTracker.markLoaded(cbcs); @@ -731,6 +731,7 @@ class Eval { state.classTracker.markLoaded(cbcs, ex.installed()); } catch (NotImplementedException ex) { state.debug(ex, "Seriously?!? load not implemented"); + state.closeDown(); } catch (EngineTerminationException ex) { state.closeDown(); } diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java index 145ace61827..73134e3e3af 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java @@ -30,6 +30,7 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.PrintStream; +import java.net.InetAddress; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; @@ -92,7 +93,6 @@ public class JShell implements AutoCloseable { final BiFunction idGenerator; final List extraRemoteVMOptions; final List extraCompilerOptions; - final ExecutionControl.Generator executionControlGenerator; private int nextKeyIndex = 1; @@ -102,13 +102,13 @@ public class JShell implements AutoCloseable { private final Map> keyStatusListeners = new HashMap<>(); private boolean closed = false; - private ExecutionControl executionControl = null; + private final ExecutionControl executionControl; private SourceCodeAnalysisImpl sourceCodeAnalysis = null; private static final String L10N_RB_NAME = "jdk.jshell.resources.l10n"; private static ResourceBundle outputRB = null; - JShell(Builder b) { + JShell(Builder b) throws IllegalStateException { this.in = b.in; this.out = b.out; this.err = b.err; @@ -116,11 +116,18 @@ public class JShell implements AutoCloseable { this.idGenerator = b.idGenerator; this.extraRemoteVMOptions = b.extraRemoteVMOptions; this.extraCompilerOptions = b.extraCompilerOptions; - this.executionControlGenerator = b.executionControlGenerator==null - ? failOverExecutionControlGenerator(JdiDefaultExecutionControl.launch(), - JdiDefaultExecutionControl.listen("localhost"), - JdiDefaultExecutionControl.listen(null)) + ExecutionControl.Generator executionControlGenerator = b.executionControlGenerator==null + ? failOverExecutionControlGenerator( + JdiDefaultExecutionControl.listen(InetAddress.getLoopbackAddress().getHostAddress()), + JdiDefaultExecutionControl.launch(), + JdiDefaultExecutionControl.listen(null) + ) : b.executionControlGenerator; + try { + executionControl = executionControlGenerator.generate(new ExecutionEnvImpl()); + } catch (Throwable ex) { + throw new IllegalStateException("Launching JShell execution engine threw: " + ex.getMessage(), ex); + } this.maps = new SnippetMaps(this); this.keyMap = new KeyMap(this); @@ -331,9 +338,10 @@ public class JShell implements AutoCloseable { * functionality. This creates a remote process for execution. It is * thus important to close the returned instance. * + * @throws IllegalStateException if the {@code JShell} instance could not be created. * @return the state engine */ - public JShell build() { + public JShell build() throws IllegalStateException { return new JShell(this); } } @@ -345,9 +353,10 @@ public class JShell implements AutoCloseable { * That is, create an instance of {@code JShell}. *

      * Equivalent to {@link JShell#builder() JShell.builder()}{@link JShell.Builder#build() .build()}. + * @throws IllegalStateException if the {@code JShell} instance could not be created. * @return an instance of {@code JShell}. */ - public static JShell create() { + public static JShell create() throws IllegalStateException { return builder().build(); } @@ -458,6 +467,7 @@ public class JShell implements AutoCloseable { * Note that the unnamed package is not accessible from the package in which * {@link JShell#eval(String)} code is placed. * @param path the path to add to the classpath. + * @throws IllegalStateException if this {@code JShell} instance is closed. */ public void addToClasspath(String path) { // Compiler @@ -504,7 +514,11 @@ public class JShell implements AutoCloseable { public void close() { if (!closed) { closeDown(); - executionControl().close(); + try { + executionControl().close(); + } catch (Throwable ex) { + // don't care about exceptions on close + } if (sourceCodeAnalysis != null) { sourceCodeAnalysis.close(); } @@ -733,14 +747,8 @@ public class JShell implements AutoCloseable { } // --- private / package-private implementation support --- + ExecutionControl executionControl() { - if (executionControl == null) { - try { - executionControl = executionControlGenerator.generate(new ExecutionEnvImpl()); - } catch (Throwable ex) { - throw new InternalError("Launching execution engine threw: " + ex.getMessage(), ex); - } - } return executionControl; } diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java index ee266a30c17..5dfc1b12d7d 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java @@ -63,7 +63,10 @@ import static jdk.jshell.execution.Util.remoteInputOutput; */ public class JdiDefaultExecutionControl extends JdiExecutionControl { - private static final String REMOTE_AGENT = RemoteExecutionControl.class.getName(); + /** + * Default time-out expressed in milliseconds. + */ + private static final int DEFAULT_TIMEOUT = 5000; private VirtualMachine vm; private Process process; @@ -73,24 +76,60 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { /** * Creates an ExecutionControl instance based on a JDI - * {@code LaunchingConnector}. + * {@code LaunchingConnector}. Same as + * {@code JdiDefaultExecutionControl.create(defaultRemoteAgent(), true, null, defaultTimeout())}. * * @return the generator */ public static ExecutionControl.Generator launch() { - return env -> create(env, true, null); + return create(defaultRemoteAgent(), true, null, defaultTimeout()); } /** * Creates an ExecutionControl instance based on a JDI - * {@code ListeningConnector}. + * {@code ListeningConnector}. Same as + * {@code JdiDefaultExecutionControl.create(defaultRemoteAgent(), false, host, defaultTimeout())}. * * @param host explicit hostname to use, if null use discovered * hostname, applies to listening only (!isLaunch) * @return the generator */ public static ExecutionControl.Generator listen(String host) { - return env -> create(env, false, host); + return create(defaultRemoteAgent(), false, host, defaultTimeout()); + } + + /** + * Creates a JDI based ExecutionControl instance. + * + * @param remoteAgent the remote agent to launch + * @param isLaunch does JDI do the launch? That is, LaunchingConnector, + * otherwise we start explicitly and use ListeningConnector + * @param host explicit hostname to use, if null use discovered + * hostname, applies to listening only (!isLaunch) + * @param timeout the start-up time-out in milliseconds + * @return the generator + */ + public static ExecutionControl.Generator create(String remoteAgent, + boolean isLaunch, String host, int timeout) { + return env -> create(env, remoteAgent, isLaunch, host, timeout); + } + + /** + * Default remote agent. + * + * @return the name of the standard remote agent + */ + public static String defaultRemoteAgent() { + return RemoteExecutionControl.class.getName(); + } + + /** + * Default remote connection time-out + * + * @return time to wait for connection before failing, expressed in milliseconds. + */ + public static int defaultTimeout() { + return DEFAULT_TIMEOUT; } /** @@ -103,6 +142,7 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { * * @param env the context passed by * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) } + * @param remoteAgent the remote agent to launch * @param isLaunch does JDI do the launch? That is, LaunchingConnector, * otherwise we start explicitly and use ListeningConnector * @param host explicit hostname to use, if null use discovered @@ -110,16 +150,16 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { * @return the channel * @throws IOException if there are errors in set-up */ - private static ExecutionControl create(ExecutionEnv env, - boolean isLaunch, String host) throws IOException { + private static ExecutionControl create(ExecutionEnv env, String remoteAgent, + boolean isLaunch, String host, int timeout) throws IOException { try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { - // timeout after 60 seconds - listener.setSoTimeout(60000); + // timeout on I/O-socket + listener.setSoTimeout(timeout); int port = listener.getLocalPort(); // Set-up the JDI connection JdiInitiator jdii = new JdiInitiator(port, - env.extraRemoteVMOptions(), REMOTE_AGENT, isLaunch, host); + env.extraRemoteVMOptions(), remoteAgent, isLaunch, host, timeout); VirtualMachine vm = jdii.vm(); Process process = jdii.process(); @@ -197,7 +237,7 @@ public class JdiDefaultExecutionControl extends JdiExecutionControl { for (ThreadReference thread : vm().allThreads()) { // could also tag the thread (e.g. using name), to find it easier for (StackFrame frame : thread.frames()) { - if (REMOTE_AGENT.equals(frame.location().declaringType().name()) && + if (defaultRemoteAgent().equals(frame.location().declaringType().name()) && ( "invoke".equals(frame.location().method().name()) || "varValue".equals(frame.location().method().name()))) { ObjectReference thiz = frame.thisObject(); diff --git a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java index 68ebc23717d..127b332a776 100644 --- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java +++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java @@ -25,6 +25,7 @@ package jdk.jshell.execution; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -35,6 +36,13 @@ import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.LaunchingConnector; import com.sun.jdi.connect.ListeningConnector; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import com.sun.jdi.connect.IllegalConnectorArgumentsException; /** * Sets up a JDI connection, providing the resulting JDI {@link VirtualMachine} @@ -42,6 +50,12 @@ import com.sun.jdi.connect.ListeningConnector; */ public class JdiInitiator { + // factor for the timeout on all of connect + private static final double CONNECT_TIMEOUT_FACTOR = 1.5; + + // Over-all connect time-out + private final int connectTimeout; + private VirtualMachine vm; private Process process = null; private final Connector connector; @@ -58,10 +72,12 @@ public class JdiInitiator { * otherwise we start explicitly and use ListeningConnector * @param host explicit hostname to use, if null use discovered * hostname, applies to listening only (!isLaunch) + * @param timeout the start-up time-out in milliseconds */ public JdiInitiator(int port, List remoteVMOptions, String remoteAgent, - boolean isLaunch, String host) { + boolean isLaunch, String host, int timeout) { this.remoteAgent = remoteAgent; + this.connectTimeout = (int) (timeout * CONNECT_TIMEOUT_FACTOR); String connectorName = isLaunch ? "com.sun.jdi.CommandLineLaunch" @@ -74,8 +90,11 @@ public class JdiInitiator { = isLaunch ? launchArgs(port, String.join(" ", remoteVMOptions)) : new HashMap<>(); - if (host != null && !isLaunch) { - argumentName2Value.put("localAddress", host); + if (!isLaunch) { + argumentName2Value.put("timeout", ""+timeout); + if (host != null && !isLaunch) { + argumentName2Value.put("localAddress", host); + } } this.connectorArgs = mergeConnectorArgs(connector, argumentName2Value); this.vm = isLaunch @@ -106,13 +125,12 @@ public class JdiInitiator { private VirtualMachine launchTarget() { LaunchingConnector launcher = (LaunchingConnector) connector; try { - VirtualMachine new_vm = launcher.launch(connectorArgs); + VirtualMachine new_vm = timedVirtualMachineCreation(() -> launcher.launch(connectorArgs), null); process = new_vm.process(); return new_vm; - } catch (Exception ex) { - reportLaunchFail(ex, "launch"); + } catch (Throwable ex) { + throw reportLaunchFail(ex, "launch"); } - return null; } /** @@ -140,15 +158,52 @@ public class JdiInitiator { ProcessBuilder pb = new ProcessBuilder(args); process = pb.start(); - // Forward out, err, and in // Accept the connection from the remote agent - vm = listener.accept(connectorArgs); - listener.stopListening(connectorArgs); + vm = timedVirtualMachineCreation(() -> listener.accept(connectorArgs), + () -> process.waitFor()); return vm; - } catch (Exception ex) { - reportLaunchFail(ex, "listen"); + } catch (Throwable ex) { + if (process != null) { + process.destroyForcibly(); + } + throw reportLaunchFail(ex, "listen"); + } finally { + try { + listener.stopListening(connectorArgs); + } catch (IOException | IllegalConnectorArgumentsException ex) { + // ignore + } } - return null; + } + + VirtualMachine timedVirtualMachineCreation(Callable creator, + Callable processComplete) throws Exception { + VirtualMachine result; + ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = Executors.defaultThreadFactory().newThread(runnable); + thread.setDaemon(true); + return thread; + }); + try { + Future future = executor.submit(creator); + if (processComplete != null) { + executor.submit(() -> { + Integer i = processComplete.call(); + future.cancel(true); + return i; + }); + } + + try { + result = future.get(connectTimeout, TimeUnit.MILLISECONDS); + } catch (TimeoutException ex) { + future.cancel(true); + throw ex; + } + } finally { + executor.shutdownNow(); + } + return result; } private Connector findConnector(String name) { @@ -194,8 +249,10 @@ public class JdiInitiator { return argumentName2Value; } - private void reportLaunchFail(Exception ex, String context) { - throw new InternalError("Failed remote " + context + ": " + connector + + private InternalError reportLaunchFail(Throwable ex, String context) { + return new InternalError("Failed remote " + context + ": " + + ex.toString() + + " @ " + connector + " -- " + connectorArgs, ex); } diff --git a/langtools/test/jdk/jshell/DyingRemoteAgent.java b/langtools/test/jdk/jshell/DyingRemoteAgent.java new file mode 100644 index 00000000000..9e75104b873 --- /dev/null +++ b/langtools/test/jdk/jshell/DyingRemoteAgent.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.jshell.JShell; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import jdk.jshell.execution.RemoteExecutionControl; +import static jdk.jshell.execution.JdiDefaultExecutionControl.defaultTimeout; + +class DyingRemoteAgent extends RemoteExecutionControl { + + static final boolean INFRA_VERIFY = false; + + public static void main(String[] args) throws Exception { + if (INFRA_VERIFY) { + RemoteExecutionControl.main(args); + } else { + System.exit(1); + } + } + + static JShell state(boolean isLaunch, String host) { + return JShell.builder().executionEngine( + JdiDefaultExecutionControl.create( + DyingRemoteAgent.class.getName(), + isLaunch, + host, + defaultTimeout())).build(); + } +} diff --git a/langtools/test/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java b/langtools/test/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java new file mode 100644 index 00000000000..5db8fe5fac2 --- /dev/null +++ b/langtools/test/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8131029 8160127 8159935 8169519 + * @summary Test that fail-over works for fail-over ExecutionControl generators. + * @modules jdk.jshell/jdk.jshell.execution + * jdk.jshell/jdk.jshell.spi + * @build KullaTesting ExecutionControlTestBase + * @run testng FailOverExecutionControlDyingLaunchTest + */ + +import org.testng.annotations.Test; +import org.testng.annotations.BeforeMethod; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static jdk.jshell.execution.JdiDefaultExecutionControl.defaultTimeout; +import static jdk.jshell.execution.Util.failOverExecutionControlGenerator; + +@Test +public class FailOverExecutionControlDyingLaunchTest extends ExecutionControlTestBase { + + @BeforeMethod + @Override + public void setUp() { + setUp(builder -> builder.executionEngine(failOverExecutionControlGenerator( + JdiDefaultExecutionControl.create( + DyingRemoteAgent.class.getName(), + true, + null, + defaultTimeout()), + JdiDefaultExecutionControl.launch()))); + } +} diff --git a/langtools/test/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java b/langtools/test/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java new file mode 100644 index 00000000000..1f15370776e --- /dev/null +++ b/langtools/test/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8131029 8160127 8159935 8169519 + * @summary Test that fail-over works for fail-over ExecutionControl generators. + * @modules jdk.jshell/jdk.jshell.execution + * jdk.jshell/jdk.jshell.spi + * @build KullaTesting ExecutionControlTestBase + * @run testng FailOverExecutionControlHangingLaunchTest + */ + +import org.testng.annotations.Test; +import org.testng.annotations.BeforeMethod; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static jdk.jshell.execution.JdiDefaultExecutionControl.defaultTimeout; +import static jdk.jshell.execution.Util.failOverExecutionControlGenerator; + +@Test +public class FailOverExecutionControlHangingLaunchTest extends ExecutionControlTestBase { + + @BeforeMethod + @Override + public void setUp() { + setUp(builder -> builder.executionEngine(failOverExecutionControlGenerator( + JdiDefaultExecutionControl.create( + HangingRemoteAgent.class.getName(), + true, + null, + defaultTimeout()), + JdiDefaultExecutionControl.launch()))); + } +} diff --git a/langtools/test/jdk/jshell/FailOverExecutionControlHangingListenTest.java b/langtools/test/jdk/jshell/FailOverExecutionControlHangingListenTest.java new file mode 100644 index 00000000000..6da67e4855b --- /dev/null +++ b/langtools/test/jdk/jshell/FailOverExecutionControlHangingListenTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8131029 8160127 8159935 8169519 + * @summary Test that fail-over works for fail-over ExecutionControl generators. + * @modules jdk.jshell/jdk.jshell.execution + * jdk.jshell/jdk.jshell.spi + * @build KullaTesting ExecutionControlTestBase + * @run testng FailOverExecutionControlHangingListenTest + */ + +import java.net.InetAddress; +import org.testng.annotations.Test; +import org.testng.annotations.BeforeMethod; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static jdk.jshell.execution.JdiDefaultExecutionControl.defaultTimeout; +import static jdk.jshell.execution.Util.failOverExecutionControlGenerator; + +@Test +public class FailOverExecutionControlHangingListenTest extends ExecutionControlTestBase { + + @BeforeMethod + @Override + public void setUp() { + String loopback = InetAddress.getLoopbackAddress().getHostAddress(); + setUp(builder -> builder.executionEngine(failOverExecutionControlGenerator( + JdiDefaultExecutionControl.create( + HangingRemoteAgent.class.getName(), + false, + loopback, + defaultTimeout()), + JdiDefaultExecutionControl.listen(loopback)))); + } +} diff --git a/langtools/test/jdk/jshell/HangingRemoteAgent.java b/langtools/test/jdk/jshell/HangingRemoteAgent.java new file mode 100644 index 00000000000..bfd08487bb4 --- /dev/null +++ b/langtools/test/jdk/jshell/HangingRemoteAgent.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.jshell.JShell; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import jdk.jshell.execution.RemoteExecutionControl; + +/** + * Hang for three minutes (long enough to cause a timeout). + */ +class HangingRemoteAgent extends RemoteExecutionControl { + + private static final long DELAY = 4000L; + private static final int TIMEOUT = 2000; + private static final boolean INFRA_VERIFY = false; + + public static void main(String[] args) throws Exception { + if (INFRA_VERIFY) { + RemoteExecutionControl.main(args); + } else { + long end = System.currentTimeMillis() + DELAY; + long remaining; + while ((remaining = end - System.currentTimeMillis()) > 0L) { + try { + Thread.sleep(remaining); + } catch (InterruptedException ex) { + // loop again + } + } + } + } + + static JShell state(boolean isLaunch, String host) { + return JShell.builder().executionEngine( + JdiDefaultExecutionControl.create( + HangingRemoteAgent.class.getName(), + isLaunch, + host, + TIMEOUT)).build(); + } + +} diff --git a/langtools/test/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java b/langtools/test/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java new file mode 100644 index 00000000000..0674f2ba61a --- /dev/null +++ b/langtools/test/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 8166581 + * @summary Tests for JDI connector failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @run testng JdiBadOptionLaunchExecutionControlTest + */ + +import org.testng.annotations.Test; +import jdk.jshell.JShell; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiBadOptionLaunchExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Failed remote launch: java.util.concurrent.ExecutionException: com.sun.jdi.connect.VMStartException: VM initialization failed"; + + public void badOptionLaunchTest() { + try { + JShell.builder() + .executionEngine(JdiDefaultExecutionControl.launch()) + .remoteVMOptions("-BadBadOption") + .build(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiBadOptionListenExecutionControlTest.java b/langtools/test/jdk/jshell/JdiBadOptionListenExecutionControlTest.java new file mode 100644 index 00000000000..a419bdefe13 --- /dev/null +++ b/langtools/test/jdk/jshell/JdiBadOptionListenExecutionControlTest.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 8166581 + * @summary Tests for JDI connector failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @run testng JdiBadOptionListenExecutionControlTest + */ + +import org.testng.annotations.Test; +import jdk.jshell.JShell; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiBadOptionListenExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Failed remote listen:"; + + public void badOptionListenTest() { + try { + JShell.builder() + .executionEngine(JdiDefaultExecutionControl.listen(null)) + .remoteVMOptions("-BadBadOption") + .build(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiBogusHostListenExecutionControlTest.java b/langtools/test/jdk/jshell/JdiBogusHostListenExecutionControlTest.java new file mode 100644 index 00000000000..4e4b6f8ea5b --- /dev/null +++ b/langtools/test/jdk/jshell/JdiBogusHostListenExecutionControlTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 + * @summary Tests for JDI connector failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @run testng JdiBogusHostListenExecutionControlTest + */ + +import org.testng.annotations.Test; +import jdk.jshell.JShell; +import jdk.jshell.execution.JdiDefaultExecutionControl; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiBogusHostListenExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Failed remote listen: java.net.SocketException: Unresolved address @ com.sun.jdi.SocketListe"; + + public void badOptionListenTest() { + try { + JShell.builder() + .executionEngine(JdiDefaultExecutionControl.listen("BattyRumbleBuckets-Snurfle-99-Blip")) + .build(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiFailingLaunchExecutionControlTest.java b/langtools/test/jdk/jshell/JdiFailingLaunchExecutionControlTest.java new file mode 100644 index 00000000000..288983a05e5 --- /dev/null +++ b/langtools/test/jdk/jshell/JdiFailingLaunchExecutionControlTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 + * @summary Tests for JDI connector failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @build DyingRemoteAgent + * @run testng JdiFailingLaunchExecutionControlTest + */ + +import org.testng.annotations.Test; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiFailingLaunchExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Accept timed out"; + + public void failLaunchTest() { + try { + System.err.printf("Unexpected return value: %s\n", DyingRemoteAgent.state(true, null).eval("33;")); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiFailingListenExecutionControlTest.java b/langtools/test/jdk/jshell/JdiFailingListenExecutionControlTest.java new file mode 100644 index 00000000000..aaa3357a754 --- /dev/null +++ b/langtools/test/jdk/jshell/JdiFailingListenExecutionControlTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 + * @summary Tests for JDI connector failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @build DyingRemoteAgent + * @run testng JdiFailingListenExecutionControlTest + */ + +import org.testng.annotations.Test; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiFailingListenExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Accept timed out"; + + public void failListenTest() { + try { + System.err.printf("Unexpected return value: %s\n", DyingRemoteAgent.state(true, null).eval("33;")); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiHangingLaunchExecutionControlTest.java b/langtools/test/jdk/jshell/JdiHangingLaunchExecutionControlTest.java new file mode 100644 index 00000000000..44354c57433 --- /dev/null +++ b/langtools/test/jdk/jshell/JdiHangingLaunchExecutionControlTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 + * @summary Tests for JDI connector timeout failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @build HangingRemoteAgent + * @run testng JdiHangingLaunchExecutionControlTest + */ + +import org.testng.annotations.Test; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiHangingLaunchExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Accept timed out"; + + public void hangLaunchTimeoutTest() { + try { + System.err.printf("Unexpected return value: %s\n", + HangingRemoteAgent.state(true, null).eval("33;")); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/JdiHangingListenExecutionControlTest.java b/langtools/test/jdk/jshell/JdiHangingListenExecutionControlTest.java new file mode 100644 index 00000000000..d305577a70c --- /dev/null +++ b/langtools/test/jdk/jshell/JdiHangingListenExecutionControlTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169519 + * @summary Tests for JDI connector timeout failure + * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution + * @build HangingRemoteAgent + * @run testng JdiHangingListenExecutionControlTest + */ + +import org.testng.annotations.Test; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +@Test +public class JdiHangingListenExecutionControlTest { + + private static final String EXPECTED_ERROR = + "Launching JShell execution engine threw: Accept timed out"; + + public void hangListenTimeoutTest() { + try { + System.err.printf("Unexpected return value: %s\n", + HangingRemoteAgent.state(false, null).eval("33;")); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage()); + return; + } + fail("Expected IllegalStateException"); + } +} diff --git a/langtools/test/jdk/jshell/StartOptionTest.java b/langtools/test/jdk/jshell/StartOptionTest.java index e2f65328f80..727064c6891 100644 --- a/langtools/test/jdk/jshell/StartOptionTest.java +++ b/langtools/test/jdk/jshell/StartOptionTest.java @@ -22,7 +22,7 @@ */ /* - * @test 8151754 8080883 8160089 + * @test 8151754 8080883 8160089 8166581 * @summary Testing start-up options. * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main @@ -48,6 +48,7 @@ import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; @Test public class StartOptionTest { @@ -135,6 +136,17 @@ public class StartOptionTest { start("", "Argument to startup missing.", "--no-startup", "--startup"); } + public void testStartupFailedOption() throws Exception { + try { + start("", "", "-R-hoge-foo-bar"); + } catch (IllegalStateException ex) { + String s = ex.getMessage(); + assertTrue(s.startsWith("Launching JShell execution engine threw: Failed remote"), s); + return; + } + fail("Expected IllegalStateException"); + } + public void testStartupUnknown() throws Exception { start("", "File 'UNKNOWN' for '--startup' is not found.", "--startup", "UNKNOWN"); } diff --git a/langtools/test/jdk/jshell/UserJdiUserRemoteTest.java b/langtools/test/jdk/jshell/UserJdiUserRemoteTest.java index b8d575362c0..1b074a046c8 100644 --- a/langtools/test/jdk/jshell/UserJdiUserRemoteTest.java +++ b/langtools/test/jdk/jshell/UserJdiUserRemoteTest.java @@ -118,6 +118,7 @@ public class UserJdiUserRemoteTest extends ExecutionControlTestBase { class MyExecutionControl extends JdiExecutionControl { private static final String REMOTE_AGENT = MyRemoteExecutionControl.class.getName(); + private static final int TIMEOUT = 2000; private VirtualMachine vm; private Process process; @@ -147,8 +148,8 @@ class MyExecutionControl extends JdiExecutionControl { */ static ExecutionControl make(ExecutionEnv env, UserJdiUserRemoteTest test) throws IOException { try (final ServerSocket listener = new ServerSocket(0)) { - // timeout after 60 seconds - listener.setSoTimeout(60000); + // timeout for socket + listener.setSoTimeout(TIMEOUT); int port = listener.getLocalPort(); // Set-up the JDI connection @@ -158,7 +159,7 @@ class MyExecutionControl extends JdiExecutionControl { + System.getProperty("path.separator") + System.getProperty("user.dir")); JdiInitiator jdii = new JdiInitiator(port, - opts, REMOTE_AGENT, true, null); + opts, REMOTE_AGENT, true, null, TIMEOUT); VirtualMachine vm = jdii.vm(); Process process = jdii.process(); From c5cbc99fd12b40c12b57d81da37f6244b51bba40 Mon Sep 17 00:00:00 2001 From: Felix Yang Date: Tue, 22 Nov 2016 20:27:42 -0800 Subject: [PATCH 172/402] 8170249: Problem list 2 jdk/jshell tests Reviewed-by: darcy --- langtools/test/ProblemList.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/langtools/test/ProblemList.txt b/langtools/test/ProblemList.txt index d4a9a494913..b01381f7a7d 100644 --- a/langtools/test/ProblemList.txt +++ b/langtools/test/ProblemList.txt @@ -39,6 +39,8 @@ jdk/javadoc/doclet/testIOException/TestIOException.java jdk/jshell/EditorPadTest.java 8161276 windows-all Test set-up cannot press buttons jdk/jshell/ToolBasicTest.java 8139873 generic-all JShell tests failing jdk/jshell/ExternalEditorTest.java 8170108 generic-all +jdk/jshell/ToolFormatTest.java 8170216 solaris-sparcv9 +jdk/jshell/ReplaceTest.java 8170216 solaris-sparcv9 ########################################################################### # From a4e5122d64c0d09ffc0ea228695e27f1d46ff3b4 Mon Sep 17 00:00:00 2001 From: Jamil Nimeh Date: Tue, 22 Nov 2016 20:54:32 -0800 Subject: [PATCH 173/402] 8170035: When determining the ciphersuite lists, there is no debug output for disabled suites Provide extra debugging output for JSSE that displays disabled cipher suites Reviewed-by: vinnie, wetmore --- .../share/classes/sun/security/ssl/SSLContextImpl.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java index 86727b91997..24dd7e0df14 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java @@ -403,6 +403,13 @@ public abstract class SSLContextImpl extends SSLContextSpi { EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) { suites.add(suite); + } else { + if (debug != null && Debug.isOn("sslctx") && + Debug.isOn("verbose")) { + System.out.println( + "Ignoring disabled cipher suite: " + + suite.name); + } } } else if (debug != null && Debug.isOn("sslctx") && Debug.isOn("verbose")) { From 086115b97509c3d6936fd5c7e1a81d380066f939 Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Wed, 23 Nov 2016 10:20:05 -0500 Subject: [PATCH 174/402] 8169416: SSLSessionImpl finalize overhead Reviewed-by: xuelei, bpb --- .../sun/security/ssl/SSLSessionImpl.java | 11 - .../ssl/finalize/SSLSessionFinalizeTest.java | 355 ++++++++++++++++++ .../javax/net/ssl/finalize/security.policy | 13 + 3 files changed, 368 insertions(+), 11 deletions(-) create mode 100644 jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java create mode 100644 jdk/test/javax/net/ssl/finalize/security.policy diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java index b566b892eb9..59472f18b84 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java @@ -960,17 +960,6 @@ final class SSLSessionImpl extends ExtendedSSLSession { + "]"; } - /** - * When SSL sessions are finalized, all values bound to - * them are removed. - */ - @Override - protected void finalize() throws Throwable { - String[] names = getValueNames(); - for (int i = 0; i < names.length; i++) { - removeValue(names[i]); - } - } } diff --git a/jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java b/jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java new file mode 100644 index 00000000000..69611763e32 --- /dev/null +++ b/jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Test behavior related to finalize + * @run main/othervm SSLSessionFinalizeTest + * @run main/othervm/policy=security.policy SSLSessionFinalizeTest + */ + +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.concurrent.ArrayBlockingQueue; + +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSessionBindingEvent; +import javax.net.ssl.SSLSessionBindingListener; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +public class SSLSessionFinalizeTest { + + /* + * ============================================================= + * Set the various variables needed for the tests, then + * specify what tests to run on each side. + */ + + /* + * Should we run the client or server in a separate thread? + * Both sides can throw exceptions, but do you have a preference + * as to which side should be the main thread. + */ + static boolean separateServerThread = true; + + /* + * Where do we find the keystores? + */ + static String pathToStores = "../etc"; + static String keyStoreFile = "keystore"; + static String trustStoreFile = "truststore"; + static String passwd = "passphrase"; + + /* + * Is the server ready to serve? + */ + volatile static boolean serverReady = false; + + /* + * Turn on SSL debugging? + */ + static boolean debug = false; + + /* + * If the client or server is doing some kind of object creation + * that the other side depends on, and that thread prematurely + * exits, you may experience a hang. The test harness will + * terminate all hung threads after its timeout has expired, + * currently 3 minutes by default, but you might try to be + * smart about it.... + */ + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLServerSocketFactory sslssf = + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslssf.createServerSocket(serverPort); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal Client, we're ready for his connect. + */ + serverReady = true; + + while (serverReady) { + SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); +// System.out.printf(" accept: %s%n", sslSocket); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslIS.read(); + sslOS.write(85); + sslOS.flush(); + + sslSocket.close(); + } + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + SBListener doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + while (!serverReady) { + Thread.sleep(50); + } + + SSLSocketFactory sslsf = + (SSLSocketFactory) SSLSocketFactory.getDefault(); + + try { + SSLSocket sslSocket = (SSLSocket) + sslsf.createSocket("localhost", serverPort); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslOS.write(280); + sslOS.flush(); + sslIS.read(); + + sslOS.close(); + sslIS.close(); + + SSLSession sslSession = sslSocket.getSession(); + System.out.printf(" sslSession: %s %n %s%n", sslSession, sslSession.getClass()); + SBListener sbListener = new SBListener(sslSession); + + sslSession.putValue("x", sbListener); + + sslSession.invalidate(); + + sslSocket.close(); + + sslOS = null; + sslIS = null; + sslSession = null; + sslSocket = null; + Reference.reachabilityFence(sslOS); + Reference.reachabilityFence(sslIS); + Reference.reachabilityFence(sslSession); + Reference.reachabilityFence(sslSocket); + + return sbListener; + } catch (Exception ex) { + ex.printStackTrace(); + throw ex; + } + } + + /* + * ============================================================= + * The remainder is just support stuff + */ + + // use any free port by default + volatile int serverPort = 0; + + volatile Exception serverException = null; + volatile Exception clientException = null; + + public static void main(String[] args) throws Exception { + String keyFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + keyStoreFile; + String trustFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + trustStoreFile; + + System.setProperty("javax.net.ssl.keyStore", keyFilename); + System.setProperty("javax.net.ssl.keyStorePassword", passwd); + System.setProperty("javax.net.ssl.trustStore", trustFilename); + System.setProperty("javax.net.ssl.trustStorePassword", passwd); + + if (debug) + System.setProperty("javax.net.debug", "all"); + + /* + * Start the tests. + */ + new SSLSessionFinalizeTest(); + } + + ArrayBlockingQueue threads = new ArrayBlockingQueue(100); + + ArrayBlockingQueue sbListeners = new ArrayBlockingQueue<>(100); + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + SSLSessionFinalizeTest() throws Exception { + final int count = 1; + if (separateServerThread) { + startServer(true); + startClients(true, count); + } else { + startClients(true, count); + startServer(true); + } + + /* + * Wait for other side to close down. + */ + Thread t; + while ((t = threads.take()) != Thread.currentThread()) { + System.out.printf(" joining: %s%n", t); + t.join(1000L); + } + serverReady = false; + System.gc(); + System.gc(); + + + SBListener listener = null; + while ((listener = sbListeners.poll()) != null) { + if (!listener.check()) { + System.out.printf(" sbListener not called on finalize: %s%n", + listener); + } + } + + /* + * When we get here, the test is pretty much over. + * + * If the main thread excepted, that propagates back + * immediately. If the other thread threw an exception, we + * should report back. + */ + if (serverException != null) { + System.out.print("Server Exception:"); + throw serverException; + } + if (clientException != null) { + System.out.print("Client Exception:"); + throw clientException; + } + } + + void startServer(boolean newThread) throws Exception { + if (newThread) { + Thread t = new Thread("Server") { + public void run() { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Release the client, if not active already... + */ + System.err.println("Server died..." + e); + serverReady = true; + serverException = e; + } + } + }; + threads.add(t); + t.setDaemon(true); + t.start(); + } else { + doServerSide(); + } + } + + void startClients(boolean newThread, int count) throws Exception { + for (int i = 0; i < count; i++) { + System.out.printf(" newClient: %d%n", i); + startClient(newThread); + } + serverReady = false; + + threads.add(Thread.currentThread()); // add ourselves at the 'end' + } + void startClient(boolean newThread) throws Exception { + if (newThread) { + Thread t = new Thread("Client") { + public void run() { + try { + sbListeners.add(doClientSide()); + } catch (Exception e) { + /* + * Our client thread just died. + */ + System.err.println("Client died..." + e); + clientException = e; + } + } + }; + System.out.printf(" starting: %s%n", t); + threads.add(t); + t.start(); + } else { + sbListeners.add(doClientSide()); + } + } + + + static class SBListener implements SSLSessionBindingListener { + private volatile int unboundNotified; + private final WeakReference session; + + SBListener(SSLSession session) { + this.unboundNotified = 0; + this.session = new WeakReference(session); + } + + boolean check() { + System.out.printf(" check: %s%n", this); + return unboundNotified > 0 && session.get() == null; + } + + @Override + public void valueBound(SSLSessionBindingEvent event) { + System.out.printf(" valueBound: %s%n", event.getName()); + } + + @Override + public void valueUnbound(SSLSessionBindingEvent event) { + System.out.printf(" valueUnbound: %s%n", event.getName()); + unboundNotified++; + } + + public String toString() { + return "count: " + unboundNotified + + ", ref: " + session.get(); + } + } +} diff --git a/jdk/test/javax/net/ssl/finalize/security.policy b/jdk/test/javax/net/ssl/finalize/security.policy new file mode 100644 index 00000000000..cec086d6031 --- /dev/null +++ b/jdk/test/javax/net/ssl/finalize/security.policy @@ -0,0 +1,13 @@ +/* + * + */ +grant { + + // used by TestLibrary to determine test environment + permission java.util.PropertyPermission "test.*", "read"; + permission java.util.PropertyPermission "user.dir", "read"; + permission java.util.PropertyPermission "java.home", "read"; + permission java.util.PropertyPermission "javax.net.ssl.*", "write"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.security.ssl"; + permission java.security.AllPermission; +}; From 305d7765812d5bc3db3da6f7b67f46abb018802e Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Wed, 23 Nov 2016 11:47:29 -0500 Subject: [PATCH 175/402] 8169645: ObjectInputFilter Config spec is ambiguous regarding overriding the filter via System properties Reviewed-by: bpb --- .../share/classes/java/io/ObjectInputFilter.java | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java b/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java index 9707725854a..e222f47c41a 100644 --- a/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java +++ b/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java @@ -194,11 +194,17 @@ public interface ObjectInputFilter { * When setting the filter, it should be stateless and idempotent, * reporting the same result when passed the same arguments. *

      - * The filter is configured using the {@link java.security.Security} - * property {@code jdk.serialFilter} and can be overridden by - * the System property {@code jdk.serialFilter}. - * - * The syntax is the same as for the {@link #createFilter(String) createFilter} method. + * The filter is configured during the initialization of the {@code ObjectInputFilter.Config} + * class. For example, by calling {@link #getSerialFilter() Config.getSerialFilter}. + * If the system property {@code jdk.serialFilter} is defined, it is used + * to configure the filter. + * If the system property is not defined, and the {@link java.security.Security} + * property {@code jdk.serialFilter} is defined then it is used to configure the filter. + * Otherwise, the filter is not configured during initialization. + * The syntax for each property is the same as for the + * {@link #createFilter(String) createFilter} method. + * If a filter is not configured, it can be set with + * {@link #setSerialFilter(ObjectInputFilter) Config.setSerialFilter}. * * @since 9 */ From 36ffe056e19e458c900ff72034d5241954c8fc47 Mon Sep 17 00:00:00 2001 From: Brent Christian Date: Wed, 23 Nov 2016 10:34:10 -0800 Subject: [PATCH 176/402] 8169435: ClassLoader.isParallelCapable is final and conflicting method may get VerifyError Reviewed-by: acorn, dholmes, mchung --- .../share/classes/java/lang/ClassLoader.java | 15 ++++++++------- .../java/lang/ClassLoader/IsParallelCapable.java | 12 ++++++------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java index 73fe154586d..843fd3c3601 100644 --- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java @@ -104,9 +104,9 @@ import sun.security.util.SecurityConstants; * class or resource itself. * *

      Class loaders that support concurrent loading of classes are known as - * {@linkplain #isParallelCapable() parallel capable} class loaders and - * are required to register themselves at their class initialization time by - * invoking the {@link + * {@linkplain #isRegisteredAsParallelCapable() parallel capable} class + * loaders and are required to register themselves at their class initialization + * time by invoking the {@link * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} * method. Note that the ClassLoader class is registered as parallel * capable by default. However, its subclasses still need to register themselves @@ -1495,7 +1495,8 @@ public abstract class ClassLoader { } /** - * Registers the caller as {@linkplain #isParallelCapable() parallel capable}. + * Registers the caller as + * {@linkplain #isRegisteredAsParallelCapable() parallel capable}. * The registration succeeds if and only if all of the following * conditions are met: *

        @@ -1509,7 +1510,7 @@ public abstract class ClassLoader { * @return {@code true} if the caller is successfully registered as * parallel capable and {@code false} if otherwise. * - * @see #isParallelCapable() + * @see #isRegisteredAsParallelCapable() * * @since 1.7 */ @@ -1521,7 +1522,7 @@ public abstract class ClassLoader { } /** - * Returns {@code true} if this class loader is + * Returns {@code true} if this class loader is registered as * {@linkplain #registerAsParallelCapable parallel capable}, otherwise * {@code false}. * @@ -1532,7 +1533,7 @@ public abstract class ClassLoader { * * @since 9 */ - public final boolean isParallelCapable() { + public final boolean isRegisteredAsParallelCapable() { return ParallelLoaders.isRegistered(this.getClass()); } diff --git a/jdk/test/java/lang/ClassLoader/IsParallelCapable.java b/jdk/test/java/lang/ClassLoader/IsParallelCapable.java index 14432488b20..dacee8ad679 100644 --- a/jdk/test/java/lang/ClassLoader/IsParallelCapable.java +++ b/jdk/test/java/lang/ClassLoader/IsParallelCapable.java @@ -23,8 +23,8 @@ /* * @test - * @bug 8165793 - * @summary Test ClassLoader.isParallelCapable() method + * @bug 8165793 8169435 + * @summary Test ClassLoader.isRegisteredAsParallelCapable() method * @run main IsParallelCapable */ @@ -85,7 +85,7 @@ public class IsParallelCapable { } public static void main(String[] args) throws Exception { - if (!ClassLoader.getSystemClassLoader().isParallelCapable()) { + if (!ClassLoader.getSystemClassLoader().isRegisteredAsParallelCapable()) { throw new RuntimeException("System classloader not parallel capable!?"); } @@ -100,10 +100,10 @@ public class IsParallelCapable { private static void testClassLoaderClass(Class klazz) { try { TestCL cl = (TestCL)klazz.newInstance(); - if (cl.expectCapable() != cl.isParallelCapable()) { + if (cl.expectCapable() != cl.isRegisteredAsParallelCapable()) { throw new RuntimeException(klazz + " expectCapable: " + - cl.expectCapable() + ", isParallelCapable: " + - cl.isParallelCapable()); + cl.expectCapable() + ", isRegisteredAsParallelCapable: " + + cl.isRegisteredAsParallelCapable()); } else { System.out.println(klazz + " passed"); } From 11b92f7ddb6e87f1dadfb57fe6e6602372bc6589 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 23 Nov 2016 10:35:43 -0800 Subject: [PATCH 177/402] 8169808: Stream returning methods should specify if they are late binding Reviewed-by: martin --- .../share/classes/java/lang/CharSequence.java | 14 ++++++++++---- .../java.base/share/classes/java/util/BitSet.java | 7 ++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/CharSequence.java b/jdk/src/java.base/share/classes/java/lang/CharSequence.java index 32b98fc4449..2972f10079f 100644 --- a/jdk/src/java.base/share/classes/java/lang/CharSequence.java +++ b/jdk/src/java.base/share/classes/java/lang/CharSequence.java @@ -121,8 +121,11 @@ public interface CharSequence { * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code * point is passed through uninterpreted. * - *

        If the sequence is mutated while the stream is being read, the - * result is undefined. + *

        The stream binds to this sequence when the terminal stream operation + * commences (specifically, for mutable sequences the spliterator for the + * stream is late-binding). + * If the sequence is modified during that operation then the result is + * undefined. * * @return an IntStream of char values from this sequence * @since 1.8 @@ -168,8 +171,11 @@ public interface CharSequence { * unpaired surrogates, and undefined code units, are zero-extended to * {@code int} values which are then passed to the stream. * - *

        If the sequence is mutated while the stream is being read, the result - * is undefined. + *

        The stream binds to this sequence when the terminal stream operation + * commences (specifically, for mutable sequences the spliterator for the + * stream is late-binding). + * If the sequence is modified during that operation then the result is + * undefined. * * @return an IntStream of Unicode code points from this sequence * @since 1.8 diff --git a/jdk/src/java.base/share/classes/java/util/BitSet.java b/jdk/src/java.base/share/classes/java/util/BitSet.java index 4e35b34ae9f..f453965f672 100644 --- a/jdk/src/java.base/share/classes/java/util/BitSet.java +++ b/jdk/src/java.base/share/classes/java/util/BitSet.java @@ -1210,9 +1210,10 @@ public class BitSet implements Cloneable, java.io.Serializable { * is the number of bits in the set state, equal to the value * returned by the {@link #cardinality()} method. * - *

        The bit set must remain constant during the execution of the - * terminal stream operation. Otherwise, the result of the terminal - * stream operation is undefined. + *

        The stream binds to this bit set when the terminal stream operation + * commences (specifically, the spliterator for the stream is + * late-binding). If the + * bit set is modified during that operation then the result is undefined. * * @return a stream of integers representing set indices * @since 1.8 From f5f1fcb803a559fdcc1512485d4953e06ce79a81 Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Wed, 23 Nov 2016 10:35:44 -0800 Subject: [PATCH 178/402] 8132964: Spliterator documentation on Priority(Blocking)Queue Reviewed-by: martin, dl, chegar --- .../java.base/share/classes/java/util/PriorityQueue.java | 6 ++++-- .../classes/java/util/concurrent/PriorityBlockingQueue.java | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/PriorityQueue.java b/jdk/src/java.base/share/classes/java/util/PriorityQueue.java index 89bc2141e3d..7a99a39e369 100644 --- a/jdk/src/java.base/share/classes/java/util/PriorityQueue.java +++ b/jdk/src/java.base/share/classes/java/util/PriorityQueue.java @@ -54,7 +54,8 @@ import java.util.function.Consumer; *

        This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link - * #iterator()} is not guaranteed to traverse the elements of + * #iterator()} and the Spliterator provided in method {@link #spliterator()} + * are not guaranteed to traverse the elements of * the priority queue in any particular order. If you need ordered * traversal, consider using {@code Arrays.sort(pq.toArray())}. * @@ -799,7 +800,8 @@ public class PriorityQueue extends AbstractQueue /** * Creates a late-binding * and fail-fast {@link Spliterator} over the elements in this - * queue. + * queue. The spliterator does not traverse elements in any particular order + * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported). * *

        The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}. diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java b/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java index 36f5a47e3f9..11d6339a3c8 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java @@ -65,7 +65,8 @@ import java.util.function.Consumer; *

        This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link - * #iterator()} is not guaranteed to traverse the elements of + * #iterator()} and the Spliterator provided in method {@link #spliterator()} + * are not guaranteed to traverse the elements of * the PriorityBlockingQueue in any particular order. If you need * ordered traversal, consider using * {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo} @@ -994,6 +995,8 @@ public class PriorityBlockingQueue extends AbstractQueue /** * Returns a {@link Spliterator} over the elements in this queue. + * The spliterator does not traverse elements in any particular order + * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported). * *

        The returned spliterator is * weakly consistent. From 20c0c1d9d0b24319d980044be00b244d63e9b94c Mon Sep 17 00:00:00 2001 From: Brent Christian Date: Wed, 23 Nov 2016 10:41:25 -0800 Subject: [PATCH 179/402] 8136831: Undefined null behavior in ClassLoader.getResourceXXXX() Reviewed-by: alanb, mchung, psandoz --- .../share/classes/java/lang/ClassLoader.java | 9 ++ .../classes/java/net/URLClassLoader.java | 4 + .../lang/ClassLoader/GetResourceNullArg.java | 96 +++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 jdk/test/java/lang/ClassLoader/GetResourceNullArg.java diff --git a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java index 843fd3c3601..adffac17c78 100644 --- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java @@ -1335,10 +1335,12 @@ public abstract class ClassLoader { * @return A URL object for reading the resource, or * null if the resource could not be found or the invoker * doesn't have adequate privileges to get the resource. + * @throws NullPointerException If {@code name} is {@code null} * * @since 1.1 */ public URL getResource(String name) { + Objects.requireNonNull(name); URL url; if (parent != null) { url = parent.getResource(name); @@ -1382,12 +1384,14 @@ public abstract class ClassLoader { * * @throws IOException * If I/O errors occur + * @throws NullPointerException If {@code name} is {@code null} * * @see #findResources(String) * * @since 1.2 */ public Enumeration getResources(String name) throws IOException { + Objects.requireNonNull(name); @SuppressWarnings("unchecked") Enumeration[] tmp = (Enumeration[]) new Enumeration[2]; if (parent != null) { @@ -1434,11 +1438,14 @@ public abstract class ClassLoader { * that the class loader doesn't have access to will not be in the * stream. * + * @throws NullPointerException If {@code name} is {@code null} + * * @see #findResources(String) * * @since 9 */ public Stream resources(String name) { + Objects.requireNonNull(name); int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE; Supplier> si = () -> { try { @@ -1600,10 +1607,12 @@ public abstract class ClassLoader { * * @return An input stream for reading the resource, or null * if the resource could not be found + * @throws NullPointerException If {@code name} is {@code null} * * @since 1.1 */ public InputStream getResourceAsStream(String name) { + Objects.requireNonNull(name); URL url = getResource(name); try { return url != null ? url.openStream() : null; diff --git a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java index ef166dcdc23..602f9d7f61a 100644 --- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java @@ -42,6 +42,7 @@ import java.security.SecureClassLoader; import java.util.Enumeration; import java.util.List; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Set; import java.util.WeakHashMap; import java.util.jar.Attributes; @@ -301,9 +302,12 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { * @return An input stream for reading the resource, or {@code null} * if the resource could not be found * + * @throws NullPointerException If {@code name} is {@code null} + * * @since 1.7 */ public InputStream getResourceAsStream(String name) { + Objects.requireNonNull(name); URL url = getResource(name); try { if (url == null) { diff --git a/jdk/test/java/lang/ClassLoader/GetResourceNullArg.java b/jdk/test/java/lang/ClassLoader/GetResourceNullArg.java new file mode 100644 index 00000000000..a8fca625cd4 --- /dev/null +++ b/jdk/test/java/lang/ClassLoader/GetResourceNullArg.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Paths; +import java.util.Enumeration; +import java.util.stream.Stream; +import org.testng.annotations.*; + +/* + * @test + * @bug 8136831 + * @summary Test null argument to ClassLoader.getResourceXXXX() + * @run testng GetResourceNullArg + */ + +public class GetResourceNullArg { + private static class MyClassLoader extends ClassLoader { + public MyClassLoader() { + super(null); + } + @Override + public Class findClass(String name) throws ClassNotFoundException { + throw new ClassNotFoundException("Why are you using this?"); + } + } + + @DataProvider + public static ClassLoader[][] provider() { + try { + return new ClassLoader[][] { + { ClassLoader.getSystemClassLoader() }, + { new MyClassLoader() }, + { new URLClassLoader(new URL[]{ Paths.get(".").toUri().toURL() }, + ClassLoader.getSystemClassLoader()) } + }; + } catch (MalformedURLException e) { throw new RuntimeException(e); } + } + + @Test(expectedExceptions = NullPointerException.class) + public void classGetResource() { + this.getClass().getResource(null); + } + + @Test(expectedExceptions = NullPointerException.class) + public void classGetResourceAsStream() { + this.getClass().getResourceAsStream(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public void loaderGetResource(ClassLoader cl) { + cl.getResource(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public static void loaderGetResources(ClassLoader cl) throws IOException { + Enumeration retVal = cl.getResources(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public static void loaderResources(ClassLoader cl) throws IOException { + Stream retVal = cl.resources(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public void loaderGetResourceAsStream(ClassLoader cl) { + cl.getResourceAsStream(null); + } +} From fc2f42262389825566ab46e062ec54b523386519 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 23 Nov 2016 11:05:10 -0800 Subject: [PATCH 180/402] 8169479: java.lang.reflect.Constructor class has wrong api documentation Reviewed-by: bpb, psandoz --- .../share/classes/java/lang/reflect/Constructor.java | 12 +++++++++--- .../share/classes/java/lang/reflect/Method.java | 9 +++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java b/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java index 03da16cb6ba..d086879a101 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java @@ -200,7 +200,8 @@ public final class Constructor extends Executable { } /** - * {@inheritDoc} + * Returns the {@code Class} object representing the class that + * declares the constructor represented by this object. */ @Override public Class getDeclaringClass() { @@ -321,6 +322,11 @@ public final class Constructor extends Executable { * public java.util.Hashtable(int,float) * } * + *

        If the constructor is declared to throw exceptions, the + * parameter list is followed by a space, followed by the word + * "{@code throws}" followed by a comma-separated list of the + * thrown exception types. + * *

        The only possible modifiers for constructors are the access * modifiers {@code public}, {@code protected} or * {@code private}. Only one of these may appear, or none if the @@ -357,13 +363,13 @@ public final class Constructor extends Executable { * "Type...". * * A space is used to separate access modifiers from one another - * and from the type parameters or return type. If there are no + * and from the type parameters or class name. If there are no * type parameters, the type parameter list is elided; if the type * parameter list is present, a space separates the list from the * class name. If the constructor is declared to throw * exceptions, the parameter list is followed by a space, followed * by the word "{@code throws}" followed by a - * comma-separated list of the thrown exception types. + * comma-separated list of the generic thrown exception types. * *

        The only possible modifiers for constructors are the access * modifiers {@code public}, {@code protected} or diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Method.java b/jdk/src/java.base/share/classes/java/lang/reflect/Method.java index 0cda872ffb1..54ef08ebe8a 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Method.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Method.java @@ -211,7 +211,8 @@ public final class Method extends Executable { } /** - * {@inheritDoc} + * Returns the {@code Class} object representing the class or interface + * that declares the method represented by this object. */ @Override public Class getDeclaringClass() { @@ -372,7 +373,7 @@ public final class Method extends Executable { * the method name, followed by a parenthesized, comma-separated * list of the method's formal parameter types. If the method * throws checked exceptions, the parameter list is followed by a - * space, followed by the word throws followed by a + * space, followed by the word "{@code throws}" followed by a * comma-separated list of the thrown exception types. * For example: *

        @@ -428,8 +429,8 @@ public final class Method extends Executable {
              * parameter list is present, a space separates the list from the
              * class name.  If the method is declared to throw exceptions, the
              * parameter list is followed by a space, followed by the word
        -     * throws followed by a comma-separated list of the generic thrown
        -     * exception types.
        +     * "{@code throws}" followed by a comma-separated list of the generic
        +     * thrown exception types.
              *
              * 

        The access modifiers are placed in canonical order as * specified by "The Java Language Specification". This is From 80cef0fcce6226204a72888547752e3b2a8dc42b Mon Sep 17 00:00:00 2001 From: Phil Race Date: Wed, 23 Nov 2016 11:53:40 -0800 Subject: [PATCH 181/402] 8170242: jdk.desktop needs package access to sun.awt Reviewed-by: ihse, mullan --- jdk/make/copy/Copy-java.base.gmk | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/make/copy/Copy-java.base.gmk b/jdk/make/copy/Copy-java.base.gmk index f736866e208..c9964cc1730 100644 --- a/jdk/make/copy/Copy-java.base.gmk +++ b/jdk/make/copy/Copy-java.base.gmk @@ -181,6 +181,7 @@ DEF_POLICY_SRC := $(JDK_TOPDIR)/src/java.base/share/lib/security/default.policy DEF_POLICY_DST := $(LIB_DST_DIR)/security/default.policy DEF_POLICY_SRC_LIST := $(DEF_POLICY_SRC) +DEF_POLICY_SRC_LIST += $(CUSTOM_POLICY_SRC_LIST) ifneq ($(filter $(OPENJDK_TARGET_OS), windows solaris), ) DEF_POLICY_SRC_LIST += $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS)/lib/security/default.policy From 819c6f5c780a486d9523ad837c6588b2b5ee0b1e Mon Sep 17 00:00:00 2001 From: Li Jiang Date: Tue, 22 Nov 2016 22:27:20 -0800 Subject: [PATCH 182/402] 8065555: Remove incorrect locale data for inexistent language German (Greece) Reviewed-by: naoto --- .../ext/CurrencyNames_de_GR.properties | 39 ------------------- .../sun/util/locale/provider/Bug8038436.java | 6 +-- 2 files changed, 3 insertions(+), 42 deletions(-) delete mode 100644 jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties diff --git a/jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties b/jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties deleted file mode 100644 index b44226143bb..00000000000 --- a/jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties +++ /dev/null @@ -1,39 +0,0 @@ -# -# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Oracle designates this -# particular file as subject to the "Classpath" exception as provided -# by Oracle in the LICENSE file that accompanied this code. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved -# (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved -# -# The original version of this source code and documentation -# is copyrighted and owned by Taligent, Inc., a wholly-owned -# subsidiary of IBM. These materials are provided under terms -# of a License Agreement between Taligent and Sun. This technology -# is protected by multiple US and International patents. -# -# This notice and attribution to Taligent may not be removed. -# Taligent is a registered trademark of Taligent, Inc. - -EUR=\u20AC -GRD=\u03B4\u03C1\u03C7 diff --git a/jdk/test/sun/util/locale/provider/Bug8038436.java b/jdk/test/sun/util/locale/provider/Bug8038436.java index 96287fca0ef..cc578410fb1 100644 --- a/jdk/test/sun/util/locale/provider/Bug8038436.java +++ b/jdk/test/sun/util/locale/provider/Bug8038436.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8038436 8158504 + * @bug 8038436 8158504 8065555 * @summary Test for changes in 8038436 * @modules java.base/sun.util.locale.provider * java.base/sun.util.spi @@ -136,7 +136,7 @@ public class Bug8038436 { static final String[] nfpLocs = ("ar, ar-AE, ar-BH, ar-DZ, ar-EG, ar-IQ, " + "ar-JO, ar-KW, ar-LB, ar-LY, ar-MA, ar-OM, ar-QA, ar-SA, ar-SD, ar-SY, " + "ar-TN, ar-YE, be, be-BY, bg, bg-BG, ca, ca-ES, cs, cs-CZ, da, da-DK, " + - "de, de-AT, de-CH, de-DE, de-GR, de-LU, el, el-CY, el-GR, en, en-AU, " + + "de, de-AT, de-CH, de-DE, de-LU, el, el-CY, el-GR, en, en-AU, " + "en-CA, en-GB, en-IE, en-IN, en-MT, en-NZ, en-PH, en-SG, en-US, en-ZA, " + "es, es-AR, es-BO, es-CL, es-CO, es-CR, es-CU, es-DO, es-EC, es-ES, " + "es-GT, es-HN, es-MX, es-NI, es-PA, es-PE, es-PR, es-PY, es-SV, es-US, " + @@ -154,7 +154,7 @@ public class Bug8038436 { static final String[] currencynpLocs = ("ar-AE, ar-BH, ar-DZ, ar-EG, ar-IQ, " + "ar-JO, ar-KW, ar-LB, ar-LY, ar-MA, ar-OM, ar-QA, ar-SA, ar-SD, ar-SY, " + "ar-TN, ar-YE, be-BY, bg-BG, ca-ES, cs-CZ, da-DK, de, de-AT, de-CH, " + - "de-DE, de-GR, de-LU, el-CY, el-GR, en-AU, en-CA, en-GB, en-IE, en-IN, " + + "de-DE, de-LU, el-CY, el-GR, en-AU, en-CA, en-GB, en-IE, en-IN, " + "en-MT, en-NZ, en-PH, en-SG, en-US, en-ZA, es, es-AR, es-BO, es-CL, " + "es-CO, es-CR, es-CU, es-DO, es-EC, es-ES, es-GT, es-HN, es-MX, es-NI, " + "es-PA, es-PE, es-PR, es-PY, es-SV, es-US, es-UY, es-VE, et-EE, fi-FI, " + From 75d947dcffc19836df745581919515e4d2c00809 Mon Sep 17 00:00:00 2001 From: Christoph Langer Date: Wed, 23 Nov 2016 08:58:15 +0100 Subject: [PATCH 183/402] 8169772: [JAXP] XALAN: Transformation of DOM with null valued text node causes NPE Reviewed-by: joehw --- .../internal/serializer/EmptySerializer.java | 366 ++++++----- .../internal/serializer/SerializerBase.java | 370 ++++------- .../xml/internal/serializer/ToSAXHandler.java | 130 ++-- .../xml/internal/serializer/ToStream.java | 582 +++++++----------- .../internal/serializer/ToUnknownStream.java | 439 +++++-------- .../serializer/XSLOutputAttributes.java | 62 +- .../unittest/transform/TransformerTest.java | 115 ++-- 7 files changed, 837 insertions(+), 1227 deletions(-) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java index 623db344ba6..c994b5f988d 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -17,9 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: EmptySerializer.java,v 1.2.4.1 2005/09/15 08:15:16 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; @@ -48,235 +46,224 @@ import org.xml.sax.SAXParseException; public class EmptySerializer implements SerializationHandler { protected static final String ERR = "EmptySerializer method not over-ridden"; - /** - * @see SerializationHandler#asContentHandler() - */ - protected void couldThrowIOException() throws IOException + protected void couldThrowIOException() throws IOException { + return; // don't do anything. + } + + protected void couldThrowSAXException() throws SAXException { + return; // don't do anything. + } + + protected void couldThrowSAXException(char[] chars, int off, int len) + throws SAXException { return; // don't do anything. } - protected void couldThrowSAXException() throws SAXException + protected void couldThrowSAXException(String elemQName) + throws SAXException { return; // don't do anything. } - protected void couldThrowSAXException(char[] chars, int off, int len) throws SAXException - { - return; // don't do anything. - } - - protected void couldThrowSAXException(String elemQName) throws SAXException - { - return; // don't do anything. - } - - void aMethodIsCalled() - { - + void aMethodIsCalled() { // throw new RuntimeException(err); return; } - /** * @see SerializationHandler#asContentHandler() */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { couldThrowIOException(); return null; } + /** * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) */ - public void setContentHandler(ContentHandler ch) - { + public void setContentHandler(ContentHandler ch) { aMethodIsCalled(); } + /** * @see SerializationHandler#close() */ - public void close() - { + public void close() { aMethodIsCalled(); } + /** * @see SerializationHandler#getOutputFormat() */ - public Properties getOutputFormat() - { + public Properties getOutputFormat() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#getOutputStream() */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#getWriter() */ - public Writer getWriter() - { + public Writer getWriter() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#reset() */ - public boolean reset() - { + public boolean reset() { aMethodIsCalled(); return false; } + /** * @see SerializationHandler#serialize(org.w3c.dom.Node) */ - public void serialize(Node node) throws IOException - { + public void serialize(Node node) throws IOException { couldThrowIOException(); } + /** * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { aMethodIsCalled(); } + /** * @see SerializationHandler#setEscaping(boolean) */ - public boolean setEscaping(boolean escape) throws SAXException - { + public boolean setEscaping(boolean escape) throws SAXException { couldThrowSAXException(); return false; } + /** * @see SerializationHandler#setIndent(boolean) */ - public void setIndent(boolean indent) - { + public void setIndent(boolean indent) { aMethodIsCalled(); } + /** * @see SerializationHandler#setIndentAmount(int) */ - public void setIndentAmount(int spaces) - { + public void setIndentAmount(int spaces) { aMethodIsCalled(); } + /** * @see SerializationHandler#setIsStandalone(boolean) */ - public void setIsStandalone(boolean isStandalone) - { + public void setIsStandalone(boolean isStandalone) { aMethodIsCalled(); } + /** * @see SerializationHandler#setOutputFormat(java.util.Properties) */ - public void setOutputFormat(Properties format) - { + public void setOutputFormat(Properties format) { aMethodIsCalled(); } + /** * @see SerializationHandler#setOutputStream(java.io.OutputStream) */ - public void setOutputStream(OutputStream output) - { + public void setOutputStream(OutputStream output) { aMethodIsCalled(); } + /** * @see SerializationHandler#setVersion(java.lang.String) */ - public void setVersion(String version) - { + public void setVersion(String version) { aMethodIsCalled(); } + /** * @see SerializationHandler#setWriter(java.io.Writer) */ - public void setWriter(Writer writer) - { + public void setWriter(Writer writer) { aMethodIsCalled(); } + /** * @see SerializationHandler#setTransformer(javax.xml.transform.Transformer) */ - public void setTransformer(Transformer transformer) - { + public void setTransformer(Transformer transformer) { aMethodIsCalled(); } + /** * @see SerializationHandler#getTransformer() */ - public Transformer getTransformer() - { + public Transformer getTransformer() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#flushPending() */ - public void flushPending() throws SAXException - { + public void flushPending() throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) */ - public void addAttributes(Attributes atts) throws SAXException - { + public void addAttributes(Attributes atts) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String) */ - public void addAttribute(String name, String value) - { + public void addAttribute(String name, String value) { aMethodIsCalled(); } /** * @see ExtendedContentHandler#characters(java.lang.String) */ - public void characters(String chars) throws SAXException - { + public void characters(String chars) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#endElement(java.lang.String) */ - public void endElement(String elemName) throws SAXException - { + public void endElement(String elemName) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#startDocument() */ - public void startDocument() throws SAXException - { + public void startDocument() throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String) */ @@ -285,13 +272,14 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(qName); } + /** * @see ExtendedContentHandler#startElement(java.lang.String) */ - public void startElement(String qName) throws SAXException - { + public void startElement(String qName) throws SAXException { couldThrowSAXException(qName); } + /** * @see ExtendedContentHandler#namespaceAfterStartElement(java.lang.String, java.lang.String) */ @@ -303,68 +291,67 @@ public class EmptySerializer implements SerializationHandler /** * @see ExtendedContentHandler#startPrefixMapping(java.lang.String, java.lang.String, boolean) */ - public boolean startPrefixMapping( - String prefix, - String uri, - boolean shouldFlush) + public boolean startPrefixMapping(String prefix, String uri, + boolean shouldFlush) throws SAXException { couldThrowSAXException(); return false; } + /** * @see ExtendedContentHandler#entityReference(java.lang.String) */ - public void entityReference(String entityName) throws SAXException - { + public void entityReference(String entityName) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getPrefix(java.lang.String) */ - public String getPrefix(String uri) - { + public String getPrefix(String uri) { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) */ - public String getNamespaceURI(String name, boolean isElement) - { + public String getNamespaceURI(String name, boolean isElement) { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getNamespaceURIFromPrefix(java.lang.String) */ - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { aMethodIsCalled(); return null; } + /** * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ - public void setDocumentLocator(Locator arg0) - { + public void setDocumentLocator(Locator arg0) { aMethodIsCalled(); } + /** * @see org.xml.sax.ContentHandler#endDocument() */ - public void endDocument() throws SAXException - { + public void endDocument() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ @@ -373,25 +360,24 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ - public void endPrefixMapping(String arg0) throws SAXException - { + public void endPrefixMapping(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ - public void startElement( - String arg0, - String arg1, - String arg2, - Attributes arg3) + public void startElement(String arg0, String arg1, String arg2, + Attributes arg3) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @@ -400,13 +386,14 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ - public void characters(char[] arg0, int arg1, int arg2) throws SAXException - { + public void characters(char[] arg0, int arg1, int arg2) throws SAXException { couldThrowSAXException(arg0, arg1, arg2); } + /** * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @@ -415,6 +402,7 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ @@ -423,20 +411,21 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ - public void skippedEntity(String arg0) throws SAXException - { + public void skippedEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedLexicalHandler#comment(java.lang.String) */ - public void comment(String comment) throws SAXException - { + public void comment(String comment) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ @@ -445,189 +434,187 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endDTD() */ - public void endDTD() throws SAXException - { + public void endDTD() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ - public void startEntity(String arg0) throws SAXException - { + public void startEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ - public void endEntity(String arg0) throws SAXException - { + public void endEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ - public void startCDATA() throws SAXException - { + public void startCDATA() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ - public void endCDATA() throws SAXException - { + public void endCDATA() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) */ - public void comment(char[] arg0, int arg1, int arg2) throws SAXException - { + public void comment(char[] arg0, int arg1, int arg2) throws SAXException { couldThrowSAXException(); } + /** * @see XSLOutputAttributes#getDoctypePublic() */ - public String getDoctypePublic() - { + public String getDoctypePublic() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getDoctypeSystem() */ - public String getDoctypeSystem() - { + public String getDoctypeSystem() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getEncoding() */ - public String getEncoding() - { + public String getEncoding() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getIndent() */ - public boolean getIndent() - { + public boolean getIndent() { aMethodIsCalled(); return false; } + /** * @see XSLOutputAttributes#getIndentAmount() */ - public int getIndentAmount() - { + public int getIndentAmount() { aMethodIsCalled(); return 0; } + /** * @see XSLOutputAttributes#getMediaType() */ - public String getMediaType() - { + public String getMediaType() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getOmitXMLDeclaration() */ - public boolean getOmitXMLDeclaration() - { + public boolean getOmitXMLDeclaration() { aMethodIsCalled(); return false; } + /** * @see XSLOutputAttributes#getStandalone() */ - public String getStandalone() - { + public String getStandalone() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getVersion() */ - public String getVersion() - { + public String getVersion() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#setDoctype(java.lang.String, java.lang.String) */ - public void setDoctype(String system, String pub) - { + public void setDoctype(String system, String pub) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setDoctypePublic(java.lang.String) */ - public void setDoctypePublic(String doctype) - { + public void setDoctypePublic(String doctype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setDoctypeSystem(java.lang.String) */ - public void setDoctypeSystem(String doctype) - { + public void setDoctypeSystem(String doctype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setEncoding(java.lang.String) */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setMediaType(java.lang.String) */ - public void setMediaType(String mediatype) - { + public void setMediaType(String mediatype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setStandalone(java.lang.String) */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { aMethodIsCalled(); } + /** * @see org.xml.sax.ext.DeclHandler#elementDecl(java.lang.String, java.lang.String) */ - public void elementDecl(String arg0, String arg1) throws SAXException - { + public void elementDecl(String arg0, String arg1) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void attributeDecl( - String arg0, - String arg1, - String arg2, - String arg3, - String arg4) + public void attributeDecl(String arg0, String arg1, String arg2, + String arg3, String arg4) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#internalEntityDecl(java.lang.String, java.lang.String) */ @@ -636,6 +623,7 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String) */ @@ -644,32 +632,32 @@ public class EmptySerializer implements SerializationHandler { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ - public void warning(SAXParseException arg0) throws SAXException - { + public void warning(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ - public void error(SAXParseException arg0) throws SAXException - { + public void error(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ - public void fatalError(SAXParseException arg0) throws SAXException - { + public void fatalError(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { couldThrowIOException(); return null; } @@ -684,8 +672,7 @@ public class EmptySerializer implements SerializationHandler /** * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { aMethodIsCalled(); } @@ -701,30 +688,30 @@ public class EmptySerializer implements SerializationHandler /** * @see ExtendedContentHandler#characters(org.w3c.dom.Node) */ - public void characters(Node node) throws SAXException - { + public void characters(Node node) throws SAXException { couldThrowSAXException(); } /** * @see ExtendedContentHandler#addXSLAttribute(java.lang.String, java.lang.String, java.lang.String) */ - public void addXSLAttribute(String qName, String value, String uri) - { + public void addXSLAttribute(String qName, String value, String uri) { aMethodIsCalled(); } /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException - { + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) */ - public void notationDecl(String arg0, String arg1, String arg2) throws SAXException + public void notationDecl(String arg0, String arg1, String arg2) + throws SAXException { couldThrowSAXException(); } @@ -732,12 +719,8 @@ public class EmptySerializer implements SerializationHandler /** * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void unparsedEntityDecl( - String arg0, - String arg1, - String arg2, - String arg3) - throws SAXException { + public void unparsedEntityDecl(String arg0, String arg1, String arg2, + String arg3) throws SAXException { couldThrowSAXException(); } @@ -746,10 +729,8 @@ public class EmptySerializer implements SerializationHandler */ public void setDTDEntityExpansion(boolean expand) { aMethodIsCalled(); - } - public String getOutputProperty(String name) { aMethodIsCalled(); return null; @@ -762,19 +743,16 @@ public class EmptySerializer implements SerializationHandler public void setOutputProperty(String name, String val) { aMethodIsCalled(); - } public void setOutputPropertyDefault(String name, String val) { aMethodIsCalled(); - } /** * @see org.apache.xml.serializer.Serializer#asDOM3Serializer() */ - public Object asDOM3Serializer() throws IOException - { + public Object asDOM3Serializer() throws IOException { couldThrowIOException(); return null; } diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java index 5d706e2f5ab..9d8e2c77961 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java @@ -1,15 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,22 +17,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: SerializerBase.java,v 1.5 2006/04/14 12:09:19 sunithareddy Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; +import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; +import com.sun.org.apache.xml.internal.serializer.utils.Utils; import java.io.IOException; import java.util.HashMap; import java.util.Set; import java.util.ArrayList; - import javax.xml.transform.OutputKeys; import javax.xml.transform.SourceLocator; import javax.xml.transform.Transformer; - -import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; -import com.sun.org.apache.xml.internal.serializer.utils.Utils; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; @@ -42,7 +36,6 @@ import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.Locator2; - /** * This class acts as a base class for the XML "serializers" * and the stream serializers. @@ -54,7 +47,6 @@ public abstract class SerializerBase implements SerializationHandler, SerializerConstants { - /** * To fire off the end element trace event * @param name Name of element @@ -62,8 +54,7 @@ public abstract class SerializerBase protected void fireEndElem(String name) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null); } @@ -78,8 +69,7 @@ public abstract class SerializerBase protected void fireCharEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); } @@ -87,7 +77,7 @@ public abstract class SerializerBase /** * true if we still need to call startDocumentInternal() - */ + */ protected boolean m_needToCallStartDocument = true; /** True if a trailing "]]>" still needs to be written to be @@ -150,6 +140,7 @@ public abstract class SerializerBase * Flag to tell if indenting (pretty-printing) is on. */ protected boolean m_doIndent = false; + /** * Amount to indent. */ @@ -186,7 +177,6 @@ public abstract class SerializerBase protected SourceLocator m_sourceLocator; - /** * The writer to send output to. This field is only used in the ToStream * serializers, but exists here just so that the fireStartDoc() and @@ -227,11 +217,9 @@ public abstract class SerializerBase * * @see ExtendedLexicalHandler#comment(String) */ - public void comment(String data) throws SAXException - { + public void comment(String data) throws SAXException { final int length = data.length(); - if (length > m_charsBuff.length) - { + if (length > m_charsBuff.length) { m_charsBuff = new char[length * 2 + 1]; } data.getChars(0, length, m_charsBuff, 0); @@ -248,10 +236,7 @@ public abstract class SerializerBase * XML file, it sometimes generates a NS prefix of the form "ns?" for * an attribute. */ - protected String patchName(String qname) - { - - + protected String patchName(String qname) { final int lastColon = qname.lastIndexOf(':'); if (lastColon > 0) { @@ -259,12 +244,11 @@ public abstract class SerializerBase final String prefix = qname.substring(0, firstColon); final String localName = qname.substring(lastColon + 1); - // If uri is "" then ignore prefix + // If uri is "" then ignore prefix final String uri = m_prefixMap.lookupNamespace(prefix); if (uri != null && uri.length() == 0) { return localName; - } - else if (firstColon != lastColon) { + } else if (firstColon != lastColon) { return prefix + ':' + localName; } } @@ -277,8 +261,7 @@ public abstract class SerializerBase * @param qname the qualified name * @return the name, but excluding any prefix and colon. */ - protected static String getLocalName(String qname) - { + protected static String getLocalName(String qname) { final int col = qname.lastIndexOf(':'); return (col > 0) ? qname.substring(col + 1) : qname; } @@ -309,8 +292,7 @@ public abstract class SerializerBase * during the invocation of the events in this interface. The * application should not attempt to use it at any other time.

        */ - public void setDocumentLocator(Locator locator) - { + public void setDocumentLocator(Locator locator) { m_locator = locator; } @@ -332,20 +314,13 @@ public abstract class SerializerBase * @param XSLAttribute true if this attribute is coming from an xsl:attriute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute); } - } /** @@ -362,51 +337,32 @@ public abstract class SerializerBase * @return true if the attribute was added, * false if an existing value was replaced. */ - public boolean addAttributeAlways( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public boolean addAttributeAlways(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) { boolean was_added; -// final int index = -// (localName == null || uri == null) ? -// m_attributes.getIndex(rawName):m_attributes.getIndex(uri, localName); - int index; -// if (localName == null || uri == null){ -// index = m_attributes.getIndex(rawName); -// } -// else { -// index = m_attributes.getIndex(uri, localName); -// } - - if (localName == null || uri == null || uri.length() == 0) - index = m_attributes.getIndex(rawName); - else { - index = m_attributes.getIndex(uri,localName); - } - if (index >= 0) - { - /* We've seen the attribute before. - * We may have a null uri or localName, but all - * we really want to re-set is the value anyway. - */ - m_attributes.setValue(index,value); - was_added = false; - } - else - { - // the attribute doesn't exist yet, create it - m_attributes.addAttribute(uri, localName, rawName, type, value); - was_added = true; - } - return was_added; + int index; + if (localName == null || uri == null || uri.length() == 0) + index = m_attributes.getIndex(rawName); + else { + index = m_attributes.getIndex(uri,localName); + } + if (index >= 0) { + /* We've seen the attribute before. + * We may have a null uri or localName, but all + * we really want to re-set is the value anyway. + */ + m_attributes.setValue(index,value); + was_added = false; + } else { + // the attribute doesn't exist yet, create it + m_attributes.addAttribute(uri, localName, rawName, type, value); + was_added = true; + } + return was_added; } - /** * Adds the given attribute to the set of collected attributes, * but only if there is a currently open element. @@ -414,16 +370,14 @@ public abstract class SerializerBase * @param name the attribute's qualified name * @param value the value of the attribute */ - public void addAttribute(String name, final String value) - { - if (m_elemContext.m_startTagOpen) - { + public void addAttribute(String name, final String value) { + if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); final String uri = getNamespaceURI(patchedName, false); addAttributeAlways(uri,localName, patchedName, "CDATA", value, false); - } + } } /** @@ -434,15 +388,13 @@ public abstract class SerializerBase * @param value the value of the attribute * @param uri the URI that the prefix of the name points to */ - public void addXSLAttribute(String name, final String value, final String uri) - { - if (m_elemContext.m_startTagOpen) - { + public void addXSLAttribute(String name, final String value, final String uri) { + if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); addAttributeAlways(uri,localName, patchedName, "CDATA", value, true); - } + } } /** @@ -451,12 +403,9 @@ public abstract class SerializerBase * is currently open. * @param atts List of attributes to add to this list */ - public void addAttributes(Attributes atts) throws SAXException - { - + public void addAttributes(Attributes atts) throws SAXException { int nAtts = atts.getLength(); - for (int i = 0; i < nAtts; i++) - { + for (int i = 0; i < nAtts; i++) { String uri = atts.getURI(i); if (null == uri) @@ -469,7 +418,6 @@ public abstract class SerializerBase atts.getType(i), atts.getValue(i), false); - } } @@ -482,8 +430,7 @@ public abstract class SerializerBase * or null if the serializer is not SAX 2 capable * @throws IOException An I/O exception occured */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { return this; } @@ -494,8 +441,7 @@ public abstract class SerializerBase * @throws org.xml.sax.SAXException The application may raise an exception. * @see #startEntity */ - public void endEntity(String name) throws org.xml.sax.SAXException - { + public void endEntity(String name) throws org.xml.sax.SAXException { if (name.equals("[dtd]")) m_inExternalDTD = false; m_inEntityRef = false; @@ -509,27 +455,24 @@ public abstract class SerializerBase * ToStream serializers, not ToSAXHandler serializers. * @see ToStream */ - public void close() - { + public void close() { // do nothing (base behavior) } /** * Initialize global variables */ - protected void initCDATA() - { + protected void initCDATA() { // CDATA stack - // _cdataStack = new Stack(); - // _cdataStack.push(new Integer(-1)); // push dummy value + // _cdataStack = new Stack(); + // _cdataStack.push(new Integer(-1)); // push dummy value } /** * Returns the character encoding to be used in the output document. * @return the character encoding to be used in the output document. */ - public String getEncoding() - { + public String getEncoding() { return getOutputProperty(OutputKeys.ENCODING); } @@ -537,8 +480,7 @@ public abstract class SerializerBase * Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * @param m_encoding the character encoding */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { setOutputProperty(OutputKeys.ENCODING,encoding); } @@ -547,19 +489,16 @@ public abstract class SerializerBase * @param b true if the XML declaration is to be omitted from the output * document. */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { String val = b ? "yes":"no"; setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,val); } - /** * @return true if the XML declaration is to be omitted from the output * document. */ - public boolean getOmitXMLDeclaration() - { + public boolean getOmitXMLDeclaration() { return m_shouldNotWriteXMLHeader; } @@ -625,8 +564,7 @@ public abstract class SerializerBase * document. This method remembers if the value was explicitly set using * this method, verses if the value is the default value. */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { setOutputProperty(OutputKeys.STANDALONE, standalone); } @@ -635,8 +573,7 @@ public abstract class SerializerBase * default or explicite setting. * @param standalone "yes" | "no" */ - protected void setStandaloneInternal(String standalone) - { + protected void setStandaloneInternal(String standalone) { if ("yes".equals(standalone)) m_standalone = "yes"; else @@ -650,8 +587,7 @@ public abstract class SerializerBase * be included in the output document. * @see XSLOutputAttributes#getStandalone() */ - public String getStandalone() - { + public String getStandalone() { return m_standalone; } @@ -659,8 +595,7 @@ public abstract class SerializerBase * @return true if the output document should be indented to visually * indicate its structure. */ - public boolean getIndent() - { + public boolean getIndent() { return m_doIndent; } /** @@ -669,8 +604,7 @@ public abstract class SerializerBase * @return the mediatype the media-type or MIME type associated with the * output document. */ - public String getMediaType() - { + public String getMediaType() { return m_mediatype; } @@ -678,8 +612,7 @@ public abstract class SerializerBase * Gets the version of the output format. * @return the version of the output format. */ - public String getVersion() - { + public String getVersion() { return m_version; } @@ -688,8 +621,7 @@ public abstract class SerializerBase * @param version the version of the output format. * @see SerializationHandler#setVersion(String) */ - public void setVersion(String version) - { + public void setVersion(String version) { setOutputProperty(OutputKeys.VERSION, version); } @@ -700,16 +632,14 @@ public abstract class SerializerBase * @see javax.xml.transform.OutputKeys#MEDIA_TYPE * @see SerializationHandler#setMediaType(String) */ - public void setMediaType(String mediaType) - { + public void setMediaType(String mediaType) { setOutputProperty(OutputKeys.MEDIA_TYPE,mediaType); } /** * @return the number of spaces to indent for each indentation level. */ - public int getIndentAmount() - { + public int getIndentAmount() { return m_indentAmount; } @@ -717,8 +647,7 @@ public abstract class SerializerBase * Sets the indentation amount. * @param m_indentAmount The m_indentAmount to set */ - public void setIndentAmount(int m_indentAmount) - { + public void setIndentAmount(int m_indentAmount) { this.m_indentAmount = m_indentAmount; } @@ -729,8 +658,7 @@ public abstract class SerializerBase * visually indicate its structure. * @see XSLOutputAttributes#setIndent(boolean) */ - public void setIndent(boolean doIndent) - { + public void setIndent(boolean doIndent) { String val = doIndent ? "yes":"no"; setOutputProperty(OutputKeys.INDENT,val); } @@ -740,8 +668,7 @@ public abstract class SerializerBase * @param isStandalone true if the ORACLE_IS_STANDALONE is set to yes * @see OutputPropertiesFactory ORACLE_IS_STANDALONE */ - public void setIsStandalone(boolean isStandalone) - { + public void setIsStandalone(boolean isStandalone) { m_isStandalone = isStandalone; } @@ -772,8 +699,7 @@ public abstract class SerializerBase * @throws IOException An I/O exception occured * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { return this; } @@ -785,8 +711,7 @@ public abstract class SerializerBase * * @return true if strings are equal. */ - private static final boolean subPartMatch(String p, String t) - { + private static final boolean subPartMatch(String p, String t) { return (p == t) || ((null != p) && (p.equals(t))); } @@ -799,8 +724,7 @@ public abstract class SerializerBase * @return returns the prefix of the qualified name, * or null if there is no prefix. */ - protected static final String getPrefixPart(String qname) - { + protected static final String getPrefixPart(String qname) { final int col = qname.indexOf(':'); return (col > 0) ? qname.substring(0, col) : null; //return (col > 0) ? qname.substring(0,col) : ""; @@ -811,8 +735,7 @@ public abstract class SerializerBase * @return the current namespace mappings (prefix/uri) * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { return m_prefixMap; } @@ -822,8 +745,7 @@ public abstract class SerializerBase * @return a prefix pointing to the given URI (if any). * @see ExtendedContentHandler#getPrefix(String) */ - public String getPrefix(String namespaceURI) - { + public String getPrefix(String namespaceURI) { String prefix = m_prefixMap.lookupPrefix(namespaceURI); return prefix; } @@ -836,19 +758,15 @@ public abstract class SerializerBase * an element. * @return returns the namespace URI associated with the qualified name. */ - public String getNamespaceURI(String qname, boolean isElement) - { + public String getNamespaceURI(String qname, boolean isElement) { String uri = EMPTYSTRING; int col = qname.lastIndexOf(':'); final String prefix = (col > 0) ? qname.substring(0, col) : EMPTYSTRING; - if (!EMPTYSTRING.equals(prefix) || isElement) - { - if (m_prefixMap != null) - { + if (!EMPTYSTRING.equals(prefix) || isElement) { + if (m_prefixMap != null) { uri = m_prefixMap.lookupNamespace(prefix); - if (uri == null && !prefix.equals(XMLNS_PREFIX)) - { + if (uri == null && !prefix.equals(XMLNS_PREFIX)) { throw new RuntimeException( Utils.messages.createMessage( MsgKey.ER_NAMESPACE_PREFIX, @@ -866,8 +784,7 @@ public abstract class SerializerBase * @return the namespace URI currently associated with the * prefix, null if the prefix is undefined. */ - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { String uri = null; if (m_prefixMap != null) uri = m_prefixMap.lookupNamespace(prefix); @@ -881,16 +798,14 @@ public abstract class SerializerBase * * @throws org.xml.sax.SAXException */ - public void entityReference(String name) throws org.xml.sax.SAXException - { - + public void entityReference(String name) throws org.xml.sax.SAXException { flushPending(); startEntity(name); endEntity(name); if (m_tracer != null) - fireEntityReference(name); + fireEntityReference(name); } /** @@ -898,8 +813,7 @@ public abstract class SerializerBase * @param t the transformer associated with this serializer. * @see SerializationHandler#setTransformer(Transformer) */ - public void setTransformer(Transformer t) - { + public void setTransformer(Transformer t) { m_transformer = t; // If this transformer object implements the SerializerTrace interface @@ -912,13 +826,13 @@ public abstract class SerializerBase m_tracer = null; } } + /** * Gets the transformer associated with this serializer * @return returns the transformer associated with this serializer. * @see SerializationHandler#getTransformer() */ - public Transformer getTransformer() - { + public Transformer getTransformer() { return m_transformer; } @@ -933,11 +847,9 @@ public abstract class SerializerBase { flushPending(); String data = node.getNodeValue(); - if (data != null) - { + if (data != null) { final int length = data.length(); - if (length > m_charsBuff.length) - { + if (length > m_charsBuff.length) { m_charsBuff = new char[length * 2 + 1]; } data.getChars(0, length, m_charsBuff, 0); @@ -956,16 +868,13 @@ public abstract class SerializerBase * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) */ public void fatalError(SAXParseException exc) throws SAXException { - - m_elemContext.m_startTagOpen = false; - + m_elemContext.m_startTagOpen = false; } /** * @see org.xml.sax.ErrorHandler#warning(SAXParseException) */ - public void warning(SAXParseException exc) throws SAXException - { + public void warning(SAXParseException exc) throws SAXException { } /** @@ -982,20 +891,6 @@ public abstract class SerializerBase } } - /** - * Report the characters event - * @param chars content of characters - * @param start starting index of characters to output - * @param length number of characters to output - */ -// protected void fireCharEvent(char[] chars, int start, int length) -// throws org.xml.sax.SAXException -// { -// if (m_tracer != null) -// m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); -// } -// - /** * This method is only used internally when flushing the writer from the * various fire...() trace events. Due to the writer being wrapped with @@ -1005,20 +900,15 @@ public abstract class SerializerBase * which trace the output written to the output stream. * */ - private void flushMyWriter() - { - if (m_writer != null) - { - try - { + private void flushMyWriter() { + if (m_writer != null) { + try { m_writer.flush(); - } - catch(IOException ioe) - { - + } catch(IOException ioe) { } } } + /** * Report the CDATA trace event * @param chars content of CDATA @@ -1028,10 +918,9 @@ public abstract class SerializerBase protected void fireCDATAEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); - m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length); + m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length); } } @@ -1044,10 +933,9 @@ public abstract class SerializerBase protected void fireCommentEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); - m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length)); + m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length)); } } @@ -1221,12 +1109,10 @@ public abstract class SerializerBase * * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { m_sourceLocator = locator; } - /** * Used only by TransformerSnapshotImpl to restore the serialization * to a previous state. @@ -1237,8 +1123,7 @@ public abstract class SerializerBase m_prefixMap = mappings; } - public boolean reset() - { + public boolean reset() { resetSerializerBase(); return true; } @@ -1247,8 +1132,7 @@ public abstract class SerializerBase * Reset all of the fields owned by SerializerBase * */ - private void resetSerializerBase() - { + private void resetSerializerBase() { this.m_attributes.clear(); this.m_StringOfCDATASections = null; this.m_elemContext = new ElemContext(); @@ -1280,13 +1164,12 @@ public abstract class SerializerBase * * This concept is made clear in the XSLT 2.0 draft. */ - final boolean inTemporaryOutputState() - { + final boolean inTemporaryOutputState() { /* This is a hack. We should really be letting the serializer know * that it is in temporary output state with an explicit call, but * from a pragmatic point of view (for now anyways) having no output - * encoding at all, not even the default UTF-8 indicates that the serializer - * is being used for temporary RTF. + * encoding at all, not even the default UTF-8 indicates that the + * serializer is being used for temporary RTF. */ return (getEncoding() == null); @@ -1295,36 +1178,38 @@ public abstract class SerializerBase /** * This method adds an attribute the the current element, * but should not be used for an xsl:attribute child. - * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { addAttributeAlways(uri, localName, rawName, type, value, false); } } /** - * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) + * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, + * java.lang.String, java.lang.String) */ public void notationDecl(String arg0, String arg1, String arg2) - throws SAXException { + throws SAXException + { // This method just provides a definition to satisfy the interface - // A particular sub-class of SerializerBase provides the implementation (if desired) + // A particular sub-class of SerializerBase provides the implementation + // (if desired) } /** - * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) */ - public void unparsedEntityDecl( - String arg0, - String arg1, - String arg2, - String arg3) - throws SAXException { + public void unparsedEntityDecl(String arg0, String arg1, String arg2, + String arg3) throws SAXException { // This method just provides a definition to satisfy the interface - // A particular sub-class of SerializerBase provides the implementation (if desired) + // A particular sub-class of SerializerBase provides the implementation + // (if desired) } /** @@ -1606,6 +1491,7 @@ public abstract class SerializerBase * map will have what that attribute maps to. */ private HashMap m_OutputProps; + /** * A mapping of keys to default values, for example if * the default value of the encoding is "UTF-8" then this @@ -1616,6 +1502,7 @@ public abstract class SerializerBase Set getOutputPropDefaultKeys() { return m_OutputPropsDefault.keySet(); } + Set getOutputPropKeys() { return m_OutputProps.keySet(); } @@ -1634,6 +1521,7 @@ public abstract class SerializerBase return val; } + /** * * @param name The name of the property, e.g. "{http://myprop}indent-tabs" or "indent". diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java index d488aeb60b8..4c5607edd58 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java @@ -1,13 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -17,13 +17,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToSAXHandler.java,v 1.2.4.1 2005/09/22 11:03:15 pvedula Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.util.ArrayList; - import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; @@ -39,23 +36,16 @@ import org.xml.sax.ext.LexicalHandler; * * @xsl.usage internal */ -public abstract class ToSAXHandler extends SerializerBase -{ - public ToSAXHandler() - { - } +public abstract class ToSAXHandler extends SerializerBase { + public ToSAXHandler() { } - public ToSAXHandler( - ContentHandler hdlr, - LexicalHandler lex, - String encoding) - { + public ToSAXHandler(ContentHandler hdlr, LexicalHandler lex, String encoding) { setContentHandler(hdlr); setLexHandler(lex); setEncoding(encoding); } - public ToSAXHandler(ContentHandler handler, String encoding) - { + + public ToSAXHandler(ContentHandler handler, String encoding) { setContentHandler(handler); setEncoding(encoding); } @@ -90,16 +80,14 @@ public abstract class ToSAXHandler extends SerializerBase /** * Pass callback to the SAX Handler */ - protected void startDocumentInternal() throws SAXException - { - if (m_needToCallStartDocument) - { + protected void startDocumentInternal() throws SAXException { + if (m_needToCallStartDocument) { super.startDocumentInternal(); - m_saxHandler.startDocument(); m_needToCallStartDocument = false; } } + /** * Do nothing. * @see org.xml.sax.ext.LexicalHandler#startDTD(String, String, String) @@ -113,20 +101,20 @@ public abstract class ToSAXHandler extends SerializerBase /** * Receive notification of character data. * - * @param characters The string of characters to process. + * @param chars The string of characters to process. * * @throws org.xml.sax.SAXException * * @see ExtendedContentHandler#characters(String) */ - public void characters(String characters) throws SAXException - { - final int len = characters.length(); - if (len > m_charsBuff.length) - { - m_charsBuff = new char[len*2 + 1]; + public void characters(String chars) throws SAXException { + final int len = (chars == null) ? 0 : chars.length(); + if (len > m_charsBuff.length) { + m_charsBuff = new char[len * 2 + 1]; + } + if (len > 0) { + chars.getChars(0, len, m_charsBuff, 0); } - characters.getChars(0,len, m_charsBuff, 0); characters(m_charsBuff, 0, len); } @@ -135,16 +123,13 @@ public abstract class ToSAXHandler extends SerializerBase * * @see ExtendedLexicalHandler#comment(String) */ - public void comment(String comment) throws SAXException - { + public void comment(String comment) throws SAXException { flushPending(); // Ignore if a lexical handler has not been set - if (m_lexHandler != null) - { + if (m_lexHandler != null) { final int len = comment.length(); - if (len > m_charsBuff.length) - { + if (len > m_charsBuff.length) { m_charsBuff = new char[len*2 + 1]; } comment.getChars(0,len, m_charsBuff, 0); @@ -153,7 +138,6 @@ public abstract class ToSAXHandler extends SerializerBase if (m_tracer != null) super.fireCommentEvent(m_charsBuff, 0, len); } - } /** @@ -167,12 +151,10 @@ public abstract class ToSAXHandler extends SerializerBase // Redefined in SAXXMLOutput } - protected void closeStartTag() throws SAXException - { + protected void closeStartTag() throws SAXException { } - protected void closeCDATA() throws SAXException - { + protected void closeCDATA() throws SAXException { // Redefined in SAXXMLOutput } @@ -191,12 +173,8 @@ public abstract class ToSAXHandler extends SerializerBase * * @see org.xml.sax.ContentHandler#startElement(String,String,String,Attributes) */ - public void startElement( - String arg0, - String arg1, - String arg2, - Attributes arg3) - throws SAXException + public void startElement(String arg0, String arg1, String arg2, + Attributes arg3) throws SAXException { if (m_state != null) { m_state.resetState(getTransformer()); @@ -211,8 +189,7 @@ public abstract class ToSAXHandler extends SerializerBase * Sets the LexicalHandler. * @param _lexHandler The LexicalHandler to set */ - public void setLexHandler(LexicalHandler _lexHandler) - { + public void setLexHandler(LexicalHandler _lexHandler) { this.m_lexHandler = _lexHandler; } @@ -220,11 +197,9 @@ public abstract class ToSAXHandler extends SerializerBase * Sets the SAX ContentHandler. * @param _saxHandler The ContentHandler to set */ - public void setContentHandler(ContentHandler _saxHandler) - { + public void setContentHandler(ContentHandler _saxHandler) { this.m_saxHandler = _saxHandler; - if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) - { + if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) { // we are not overwriting an existing LexicalHandler, and _saxHandler // is also implements LexicalHandler, so lets use it m_lexHandler = (LexicalHandler) _saxHandler; @@ -236,8 +211,7 @@ public abstract class ToSAXHandler extends SerializerBase * stream serializers. * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { // do nothing } @@ -247,8 +221,7 @@ public abstract class ToSAXHandler extends SerializerBase * @param doOutputNSAttr whether or not namespace declarations * should appear as attributes */ - public void setShouldOutputNSAttr(boolean doOutputNSAttr) - { + public void setShouldOutputNSAttr(boolean doOutputNSAttr) { m_shouldGenerateNSAttribute = doOutputNSAttr; } @@ -258,8 +231,7 @@ public abstract class ToSAXHandler extends SerializerBase * also be mirrored with self generated additional attributes of elements * that declare the namespace, for example the attribute xmlns:prefix1="uri1" */ - boolean getShouldOutputNSAttr() - { + boolean getShouldOutputNSAttr() { return m_shouldGenerateNSAttribute; } @@ -267,27 +239,21 @@ public abstract class ToSAXHandler extends SerializerBase * This method flushes any pending events, which can be startDocument() * closing the opening tag of an element, or closing an open CDATA section. */ - public void flushPending() throws SAXException - { - - if (m_needToCallStartDocument) - { + public void flushPending() throws SAXException { + if (m_needToCallStartDocument) { startDocumentInternal(); m_needToCallStartDocument = false; } - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { closeStartTag(); m_elemContext.m_startTagOpen = false; } - if (m_cdataTagOpen) - { + if (m_cdataTagOpen) { closeCDATA(); m_cdataTagOpen = false; } - } /** @@ -350,8 +316,7 @@ public abstract class ToSAXHandler extends SerializerBase throws org.xml.sax.SAXException { // remember the current node - if (m_state != null) - { + if (m_state != null) { m_state.setCurrentNode(node); } @@ -392,12 +357,10 @@ public abstract class ToSAXHandler extends SerializerBase */ public void warning(SAXParseException exc) throws SAXException { super.warning(exc); - if (m_saxHandler instanceof ErrorHandler) ((ErrorHandler)m_saxHandler).warning(exc); } - /** * Try's to reset the super class and reset this class for * re-use, so that you don't need to create a new serializer @@ -406,11 +369,9 @@ public abstract class ToSAXHandler extends SerializerBase * @return true if the class was successfuly reset. * @see Serializer#reset() */ - public boolean reset() - { + public boolean reset() { boolean wasReset = false; - if (super.reset()) - { + if (super.reset()) { resetToSAXHandler(); wasReset = true; } @@ -421,8 +382,7 @@ public abstract class ToSAXHandler extends SerializerBase * Reset all of the fields owned by ToSAXHandler class * */ - private void resetToSAXHandler() - { + private void resetToSAXHandler() { this.m_lexHandler = null; this.m_saxHandler = null; this.m_state = null; diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java index 0e0efe7c2e2..976b4955f45 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java @@ -1,15 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,12 +17,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToStream.java,v 1.4 2005/11/10 06:43:26 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import com.sun.org.apache.xalan.internal.utils.SecuritySupport; +import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; +import com.sun.org.apache.xml.internal.serializer.utils.Utils; +import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; @@ -36,30 +35,22 @@ import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.ArrayList; - import javax.xml.transform.ErrorListener; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; -import com.sun.org.apache.xml.internal.serializer.utils.Utils; -import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; -//import com.sun.media.sound.IESecurity; - /** * This abstract class is a base class for other stream * serializers (xml, html, text ...) that write output to a stream. * * @xsl.usage internal */ -abstract public class ToStream extends SerializerBase -{ +abstract public class ToStream extends SerializerBase { private static final String COMMENT_BEGIN = ""; @@ -67,7 +58,6 @@ abstract public class ToStream extends SerializerBase /** Stack to keep track of disabling output escaping. */ protected BoolStack m_disableOutputEscapingStates = new BoolStack(); - /** * The encoding information associated with this serializer. * Although initially there is no encoding, @@ -87,21 +77,17 @@ abstract public class ToStream extends SerializerBase */ java.lang.reflect.Method m_canConvertMeth; - - /** * Boolean that tells if we already tried to get the converter. */ boolean m_triedToGetConverter = false; - /** * Opaque reference to the sun.io.CharToByteConverter for this * encoding. */ Object m_charToByteConverter = null; - /** * Stack to keep track of whether or not we need to * preserve whitespace. @@ -139,7 +125,6 @@ abstract public class ToStream extends SerializerBase */ protected int m_maxCharacter = Encodings.getLastPrintable(); - /** * The system line separator for writing out line breaks. * The default value is from the system property, @@ -188,8 +173,8 @@ abstract public class ToStream extends SerializerBase protected boolean m_inDoctype = false; /** - * Flag to quickly tell if the encoding is UTF8. - */ + * Flag to quickly tell if the encoding is UTF8. + */ boolean m_isUTF8 = false; /** @@ -203,29 +188,23 @@ abstract public class ToStream extends SerializerBase */ private boolean m_expandDTDEntities = true; - /** * Default constructor */ - public ToStream() - { - } + public ToStream() { } /** * This helper method to writes out "]]>" when closing a CDATA section. * * @throws org.xml.sax.SAXException */ - protected void closeCDATA() throws org.xml.sax.SAXException - { - try - { + protected void closeCDATA() throws org.xml.sax.SAXException { + try { m_writer.write(CDATA_DELIMITER_CLOSE); // write out a CDATA section closing "]]>" m_cdataTagOpen = false; // Remember that we have done so. } - catch (IOException e) - { + catch (IOException e) { throw new SAXException(e); } } @@ -237,18 +216,11 @@ abstract public class ToStream extends SerializerBase * @param node Node to serialize. * @throws IOException An I/O exception occured while serializing */ - public void serialize(Node node) throws IOException - { - - try - { - TreeWalker walker = - new TreeWalker(this); - + public void serialize(Node node) throws IOException { + try { + TreeWalker walker = new TreeWalker(this); walker.traverse(node); - } - catch (org.xml.sax.SAXException se) - { + } catch (org.xml.sax.SAXException se) { throw new WrappedRuntimeException(se); } } @@ -260,8 +232,7 @@ abstract public class ToStream extends SerializerBase * * NEEDSDOC ($objectName$) @return */ - static final boolean isUTF16Surrogate(char c) - { + static final boolean isUTF16Surrogate(char c) { return (c & 0xFC00) == 0xD800; } @@ -275,49 +246,40 @@ abstract public class ToStream extends SerializerBase * * @throws org.xml.sax.SAXException */ - protected final void flushWriter() throws org.xml.sax.SAXException - { - final java.io.Writer writer = m_writer; - if (null != writer) - { - try - { - if (writer instanceof WriterToUTF8Buffered) - { + protected final void flushWriter() throws org.xml.sax.SAXException { + final Writer writer = m_writer; + if (null != writer) { + try { + if (writer instanceof WriterToUTF8Buffered) { if (m_shouldFlush) - ((WriterToUTF8Buffered) writer).flush(); + ((WriterToUTF8Buffered)writer).flush(); else - ((WriterToUTF8Buffered) writer).flushBuffer(); + ((WriterToUTF8Buffered)writer).flushBuffer(); } - if (writer instanceof WriterToASCI) - { + if (writer instanceof WriterToASCI) { if (m_shouldFlush) writer.flush(); - } - else - { + } else { // Flush always. // Not a great thing if the writer was created // by this class, but don't have a choice. writer.flush(); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new org.xml.sax.SAXException(ioe); } } } OutputStream m_outputStream; + /** * Get the output stream where the events will be serialized to. * * @return reference to the result stream, or null of only a writer was * set. */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { return m_outputStream; } @@ -341,9 +303,8 @@ abstract public class ToStream extends SerializerBase // Do not inline external DTD if (m_inExternalDTD) return; - try - { - final java.io.Writer writer = m_writer; + try { + final Writer writer = m_writer; DTDprolog(); writer.write(""); else @@ -2598,15 +2542,12 @@ abstract public class ToStream extends SerializerBase * OutputProperties. Eventually this method should go away and a call * to setCdataSectionElements(ArrayList v) should be made directly. */ - private void setCdataSectionElements(String key, Properties props) - { - + private void setCdataSectionElements(String key, Properties props) { String s = props.getProperty(key); - if (null != s) - { + if (null != s) { // ArrayList of URI/LocalName pairs - ArrayList v = new ArrayList<>(); + ArrayList al = new ArrayList<>(); int l = s.length(); boolean inCurly = false; StringBuilder buf = new StringBuilder(); @@ -2624,7 +2565,7 @@ abstract public class ToStream extends SerializerBase { if (buf.length() > 0) { - addCdataSectionElement(buf.toString(), v); + addCdataSectionElement(buf.toString(), al); buf.setLength(0); } continue; @@ -2640,11 +2581,11 @@ abstract public class ToStream extends SerializerBase if (buf.length() > 0) { - addCdataSectionElement(buf.toString(), v); + addCdataSectionElement(buf.toString(), al); buf.setLength(0); } // call the official, public method to set the collected names - setCdataSectionElements(v); + setCdataSectionElements(al); } } @@ -2656,25 +2597,19 @@ abstract public class ToStream extends SerializerBase * * @return a QName object */ - private void addCdataSectionElement(String URI_and_localName, ArrayList v) - { - - StringTokenizer tokenizer = - new StringTokenizer(URI_and_localName, "{}", false); + private void addCdataSectionElement(String URI_and_localName, ArrayList al) { + StringTokenizer tokenizer = new StringTokenizer(URI_and_localName, "{}", false); String s1 = tokenizer.nextToken(); String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; - if (null == s2) - { + if (null == s2) { // add null URI and the local name - v.add(null); - v.add(s1); - } - else - { + al.add(null); + al.add(s1); + } else { // add URI, then local name - v.add(s1); - v.add(s2); + al.add(s1); + al.add(s2); } } @@ -2685,25 +2620,20 @@ abstract public class ToStream extends SerializerBase * * @param URI_and_localNames an ArrayList of pairs of Strings (URI/local) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { // convert to the new way. - if (URI_and_localNames != null) - { + if (URI_and_localNames != null) { final int len = URI_and_localNames.size() - 1; - if (len > 0) - { + if (len > 0) { final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < len; i += 2) - { + for (int i = 0; i < len; i += 2) { // whitspace separated "{uri1}local1 {uri2}local2 ..." if (i != 0) sb.append(' '); final String uri = (String) URI_and_localNames.get(i); final String localName = (String) URI_and_localNames.get(i + 1); - if (uri != null) - { + if (uri != null) { // If there is no URI don't put this in, just the localName then. sb.append('{'); sb.append(uri); @@ -3007,25 +2937,19 @@ abstract public class ToStream extends SerializerBase * exist. This method should be called everytime an attribute is added, * or when an attribute value is changed, or an element is created. */ - - protected void firePseudoAttributes() - { - if (m_tracer != null) - { - try - { + protected void firePseudoAttributes() { + if (m_tracer != null) { + try { // flush out the " 0) - { + if (nAttrs > 0) { // make a writer that internally appends to the same // StringBuffer - java.io.Writer writer = - new ToStream.WritertoStringBuffer(sb); + Writer writer = new ToStream.WritertoStringBuffer(sb); processAttributes(writer, nAttrs); // Don't clear the attributes! @@ -3042,13 +2966,9 @@ abstract public class ToStream extends SerializerBase ch, 0, ch.length); - } - catch (IOException ioe) - { + } catch (IOException ioe) { // ignore ? - } - catch (SAXException se) - { + } catch (SAXException se) { // ignore ? } } @@ -3060,41 +2980,35 @@ abstract public class ToStream extends SerializerBase * In this manner trace events, and the real writing of attributes will use * the same code. */ - private class WritertoStringBuffer extends java.io.Writer - { + private class WritertoStringBuffer extends Writer { final private StringBuffer m_stringbuf; + /** * @see java.io.Writer#write(char[], int, int) */ - WritertoStringBuffer(StringBuffer sb) - { + WritertoStringBuffer(StringBuffer sb) { m_stringbuf = sb; } - public void write(char[] arg0, int arg1, int arg2) throws IOException - { + public void write(char[] arg0, int arg1, int arg2) throws IOException { m_stringbuf.append(arg0, arg1, arg2); } + /** * @see java.io.Writer#flush() */ - public void flush() throws IOException - { - } + public void flush() throws IOException {} + /** * @see java.io.Writer#close() */ - public void close() throws IOException - { - } + public void close() throws IOException {} - public void write(int i) - { + public void write(int i) { m_stringbuf.append((char) i); } - public void write(String s) - { + public void write(String s) { m_stringbuf.append(s); } } @@ -3104,12 +3018,11 @@ abstract public class ToStream extends SerializerBase */ public void setTransformer(Transformer transformer) { super.setTransformer(transformer); - if (m_tracer != null - && !(m_writer instanceof SerializerTraceWriter) ) + if (m_tracer != null && !(m_writer instanceof SerializerTraceWriter)) { m_writer = new SerializerTraceWriter(m_writer, m_tracer); - - + } } + /** * Try's to reset the super class and reset this class for * re-use, so that you don't need to create a new serializer @@ -3117,11 +3030,9 @@ abstract public class ToStream extends SerializerBase * * @return true if the class was successfuly reset. */ - public boolean reset() - { + public boolean reset() { boolean wasReset = false; - if (super.reset()) - { + if (super.reset()) { resetToStream(); wasReset = true; } @@ -3132,14 +3043,12 @@ abstract public class ToStream extends SerializerBase * Reset all of the fields owned by ToStream class * */ - private void resetToStream() - { + private void resetToStream() { this.m_cdataStartCalled = false; /* The stream is being reset. It is one of * ToXMLStream, ToHTMLStream ... and this type can't be changed * so neither should m_charInfo which is associated with the * type of Stream. Just leave m_charInfo as-is for the next re-use. - * */ // this.m_charInfo = null; // don't set to null @@ -3183,173 +3092,150 @@ abstract public class ToStream extends SerializerBase * * @xsl.usage internal */ - static final class BoolStack - { + static final class BoolStack { + /** Array of boolean values */ + private boolean m_values[]; - /** Array of boolean values */ - private boolean m_values[]; + /** Array size allocated */ + private int m_allocatedSize; - /** Array size allocated */ - private int m_allocatedSize; + /** Index into the array of booleans */ + private int m_index; - /** Index into the array of booleans */ - private int m_index; + /** + * Default constructor. Note that the default + * block size is very small, for small lists. + */ + public BoolStack() { + this(32); + } - /** - * Default constructor. Note that the default - * block size is very small, for small lists. - */ - public BoolStack() - { - this(32); - } + /** + * Construct a IntVector, using the given block size. + * + * @param size array size to allocate + */ + public BoolStack(int size) { + m_allocatedSize = size; + m_values = new boolean[size]; + m_index = -1; + } - /** - * Construct a IntVector, using the given block size. - * - * @param size array size to allocate - */ - public BoolStack(int size) - { + /** + * Get the length of the list. + * + * @return Current length of the list + */ + public final int size() { + return m_index + 1; + } - m_allocatedSize = size; - m_values = new boolean[size]; - m_index = -1; - } + /** + * Clears the stack. + * + */ + public final void clear() { + m_index = -1; + } - /** - * Get the length of the list. - * - * @return Current length of the list - */ - public final int size() - { - return m_index + 1; - } + /** + * Pushes an item onto the top of this stack. + * + * + * @param val the boolean to be pushed onto this stack. + * @return the item argument. + */ + public final boolean push(boolean val) { + if (m_index == m_allocatedSize - 1) + grow(); - /** - * Clears the stack. - * - */ - public final void clear() - { - m_index = -1; - } + return (m_values[++m_index] = val); + } - /** - * Pushes an item onto the top of this stack. - * - * - * @param val the boolean to be pushed onto this stack. - * @return the item argument. - */ - public final boolean push(boolean val) - { + /** + * Removes the object at the top of this stack and returns that + * object as the value of this function. + * + * @return The object at the top of this stack. + * @throws EmptyStackException if this stack is empty. + */ + public final boolean pop() { + return m_values[m_index--]; + } - if (m_index == m_allocatedSize - 1) - grow(); + /** + * Removes the object at the top of this stack and returns the + * next object at the top as the value of this function. + * + * + * @return Next object to the top or false if none there + */ + public final boolean popAndTop() { + m_index--; + return (m_index >= 0) ? m_values[m_index] : false; + } - return (m_values[++m_index] = val); - } + /** + * Set the item at the top of this stack + * + * + * @param b Object to set at the top of this stack + */ + public final void setTop(boolean b) { + m_values[m_index] = b; + } - /** - * Removes the object at the top of this stack and returns that - * object as the value of this function. - * - * @return The object at the top of this stack. - * @throws EmptyStackException if this stack is empty. - */ - public final boolean pop() - { - return m_values[m_index--]; - } + /** + * Looks at the object at the top of this stack without removing it + * from the stack. + * + * @return the object at the top of this stack. + * @throws EmptyStackException if this stack is empty. + */ + public final boolean peek() { + return m_values[m_index]; + } - /** - * Removes the object at the top of this stack and returns the - * next object at the top as the value of this function. - * - * - * @return Next object to the top or false if none there - */ - public final boolean popAndTop() - { + /** + * Looks at the object at the top of this stack without removing it + * from the stack. If the stack is empty, it returns false. + * + * @return the object at the top of this stack. + */ + public final boolean peekOrFalse() { + return (m_index > -1) ? m_values[m_index] : false; + } - m_index--; + /** + * Looks at the object at the top of this stack without removing it + * from the stack. If the stack is empty, it returns true. + * + * @return the object at the top of this stack. + */ + public final boolean peekOrTrue() { + return (m_index > -1) ? m_values[m_index] : true; + } - return (m_index >= 0) ? m_values[m_index] : false; - } + /** + * Tests if this stack is empty. + * + * @return true if this stack is empty; + * false otherwise. + */ + public boolean isEmpty() { + return (m_index == -1); + } - /** - * Set the item at the top of this stack - * - * - * @param b Object to set at the top of this stack - */ - public final void setTop(boolean b) - { - m_values[m_index] = b; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. - * - * @return the object at the top of this stack. - * @throws EmptyStackException if this stack is empty. - */ - public final boolean peek() - { - return m_values[m_index]; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. If the stack is empty, it returns false. - * - * @return the object at the top of this stack. - */ - public final boolean peekOrFalse() - { - return (m_index > -1) ? m_values[m_index] : false; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. If the stack is empty, it returns true. - * - * @return the object at the top of this stack. - */ - public final boolean peekOrTrue() - { - return (m_index > -1) ? m_values[m_index] : true; - } - - /** - * Tests if this stack is empty. - * - * @return true if this stack is empty; - * false otherwise. - */ - public boolean isEmpty() - { - return (m_index == -1); - } - - /** - * Grows the size of the stack - * - */ - private void grow() - { - - m_allocatedSize *= 2; - - boolean newVector[] = new boolean[m_allocatedSize]; - - System.arraycopy(m_values, 0, newVector, 0, m_index + 1); - - m_values = newVector; - } + /** + * Grows the size of the stack + * + */ + private void grow() { + m_allocatedSize *= 2; + boolean newVector[] = new boolean[m_allocatedSize]; + System.arraycopy(m_values, 0, newVector, 0, m_index + 1); + m_values = newVector; + } } // Implement DTDHandler @@ -3421,14 +3307,12 @@ abstract public class ToStream extends SerializerBase * @throws IOException */ private void DTDprolog() throws SAXException, IOException { - final java.io.Writer writer = m_writer; - if (m_needToOutputDocTypeDecl) - { + final Writer writer = m_writer; + if (m_needToOutputDocTypeDecl) { outputDocTypeDecl(m_elemContext.m_elementName, false); m_needToOutputDocTypeDecl = false; } - if (m_inDoctype) - { + if (m_inDoctype) { writer.write(" ["); writer.write(m_lineSep, 0, m_lineSepLen); m_inDoctype = false; diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java index 9583dd5d30f..f68f28e1831 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java @@ -1,13 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -17,9 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToUnknownStream.java,v 1.3 2005/09/28 13:49:08 pvedula Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; @@ -27,17 +25,14 @@ import java.io.OutputStream; import java.io.Writer; import java.util.Properties; import java.util.ArrayList; - import javax.xml.transform.SourceLocator; import javax.xml.transform.Transformer; - import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; - /** *This class wraps another SerializationHandler. The wrapped object will either * handler XML or HTML, which is not known until a little later when the first XML @@ -55,7 +50,6 @@ import org.xml.sax.SAXException; */ public final class ToUnknownStream extends SerializerBase { - /** * The wrapped handler, initially XML but possibly switched to HTML */ @@ -71,11 +65,11 @@ public final class ToUnknownStream extends SerializerBase */ private boolean m_wrapped_handler_not_initialized = false; - /** * the prefix of the very first tag in the document */ private String m_firstElementPrefix; + /** * the element name (including any prefix) of the very first tag in the document */ @@ -101,6 +95,7 @@ public final class ToUnknownStream extends SerializerBase * _namespacePrefix has the matching prefix for these URI's */ private ArrayList m_namespaceURI = null; + /** * A collection of namespace Prefix (only for first element) * _namespaceURI has the matching URIs for these prefix' @@ -112,34 +107,13 @@ public final class ToUnknownStream extends SerializerBase * was initialized */ private boolean m_needToCallStartDocument = false; - /** - * true if setVersion() was called before the underlying handler - * was initialized - */ - private boolean m_setVersion_called = false; - /** - * true if setDoctypeSystem() was called before the underlying handler - * was initialized - */ - private boolean m_setDoctypeSystem_called = false; - /** - * true if setDoctypePublic() was called before the underlying handler - * was initialized - */ - private boolean m_setDoctypePublic_called = false; - /** - * true if setMediaType() was called before the underlying handler - * was initialized - */ - private boolean m_setMediaType_called = false; /** * Default constructor. * Initially this object wraps an XML Stream object, so _handler is never null. * That may change later to an HTML Stream object. */ - public ToUnknownStream() - { + public ToUnknownStream() { m_handler = new ToXMLStream(); } @@ -147,8 +121,7 @@ public final class ToUnknownStream extends SerializerBase * @see Serializer#asContentHandler() * @return the wrapped XML or HTML handler */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { /* don't return the real handler ( m_handler ) because * that would expose the real handler to the outside. * Keep m_handler private so it can be internally swapped @@ -160,8 +133,7 @@ public final class ToUnknownStream extends SerializerBase /** * @see SerializationHandler#close() */ - public void close() - { + public void close() { m_handler.close(); } @@ -169,8 +141,7 @@ public final class ToUnknownStream extends SerializerBase * @see Serializer#getOutputFormat() * @return the properties of the underlying handler */ - public Properties getOutputFormat() - { + public Properties getOutputFormat() { return m_handler.getOutputFormat(); } @@ -178,8 +149,7 @@ public final class ToUnknownStream extends SerializerBase * @see Serializer#getOutputStream() * @return the OutputStream of the underlying XML or HTML handler */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { return m_handler.getOutputStream(); } @@ -187,8 +157,7 @@ public final class ToUnknownStream extends SerializerBase * @see Serializer#getWriter() * @return the Writer of the underlying XML or HTML handler */ - public Writer getWriter() - { + public Writer getWriter() { return m_handler.getWriter(); } @@ -197,8 +166,7 @@ public final class ToUnknownStream extends SerializerBase * @see Serializer#reset() * @return ??? */ - public boolean reset() - { + public boolean reset() { return m_handler.reset(); } @@ -208,10 +176,8 @@ public final class ToUnknownStream extends SerializerBase * @see DOMSerializer#serialize(Node) * */ - public void serialize(Node node) throws IOException - { - if (m_firstTagNotEmitted) - { + public void serialize(Node node) throws IOException { + if (m_firstTagNotEmitted) { flush(); } m_handler.serialize(node); @@ -220,8 +186,7 @@ public final class ToUnknownStream extends SerializerBase /** * @see SerializationHandler#setEscaping(boolean) */ - public boolean setEscaping(boolean escape) throws SAXException - { + public boolean setEscaping(boolean escape) throws SAXException { return m_handler.setEscaping(escape); } @@ -230,8 +195,7 @@ public final class ToUnknownStream extends SerializerBase * @param format the output properties to set * @see Serializer#setOutputFormat(Properties) */ - public void setOutputFormat(Properties format) - { + public void setOutputFormat(Properties format) { m_handler.setOutputFormat(format); } @@ -240,8 +204,7 @@ public final class ToUnknownStream extends SerializerBase * @param output the OutputStream to write to * @see Serializer#setOutputStream(OutputStream) */ - public void setOutputStream(OutputStream output) - { + public void setOutputStream(OutputStream output) { m_handler.setOutputStream(output); } @@ -250,8 +213,7 @@ public final class ToUnknownStream extends SerializerBase * @param writer the writer to write to * @see Serializer#setWriter(Writer) */ - public void setWriter(Writer writer) - { + public void setWriter(Writer writer) { m_handler.setWriter(writer); } @@ -265,12 +227,8 @@ public final class ToUnknownStream extends SerializerBase * @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value) + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { addAttribute(uri, localName, rawName, type, value, false); @@ -286,35 +244,27 @@ public final class ToUnknownStream extends SerializerBase * @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.addAttribute(uri, localName, rawName, type, value, XSLAttribute); } + /** * Adds an attribute to the currenly open tag * @param rawName the attribute name, with prefix (if any) * @param value the value of the parameter * @see ExtendedContentHandler#addAttribute(String, String) */ - public void addAttribute(String rawName, String value) - { - if (m_firstTagNotEmitted) - { + public void addAttribute(String rawName, String value) { + if (m_firstTagNotEmitted) { flush(); } m_handler.addAttribute(rawName, value); - } /** @@ -323,52 +273,50 @@ public final class ToUnknownStream extends SerializerBase public void addUniqueAttribute(String rawName, String value, int flags) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.addUniqueAttribute(rawName, value, flags); - } /** * Converts the String to a character array and calls the SAX method * characters(char[],int,int); * + * @param chars The string of characters to process. + * + * @throws org.xml.sax.SAXException + * * @see ExtendedContentHandler#characters(String) */ - public void characters(String chars) throws SAXException - { - final int length = chars.length(); - if (length > m_charsBuff.length) - { - m_charsBuff = new char[length*2 + 1]; + public void characters(String chars) throws SAXException { + final int len = (chars == null) ? 0 : chars.length(); + if (len > m_charsBuff.length) { + m_charsBuff = new char[len * 2 + 1]; } - chars.getChars(0, length, m_charsBuff, 0); - this.characters(m_charsBuff, 0, length); + if (len > 0) { + chars.getChars(0, len, m_charsBuff, 0); + } + this.characters(m_charsBuff, 0, len); } /** * Pass the call on to the underlying handler * @see ExtendedContentHandler#endElement(String) */ - public void endElement(String elementName) throws SAXException - { - if (m_firstTagNotEmitted) - { + public void endElement(String elementName) throws SAXException { + if (m_firstTagNotEmitted) { flush(); } m_handler.endElement(elementName); } - /** * @see org.xml.sax.ContentHandler#startPrefixMapping(String, String) * @param prefix The prefix that maps to the URI * @param uri The URI for the namespace */ - public void startPrefixMapping(String prefix, String uri) throws SAXException - { + public void startPrefixMapping(String prefix, String uri) throws SAXException { this.startPrefixMapping(prefix,uri, true); } @@ -387,11 +335,12 @@ public final class ToUnknownStream extends SerializerBase throws SAXException { // hack for XSLTC with finding URI for default namespace - if (m_firstTagNotEmitted && m_firstElementURI == null && m_firstElementName != null) + if (m_firstTagNotEmitted && + m_firstElementURI == null && + m_firstElementName != null) { String prefix1 = getPrefixPart(m_firstElementName); - if (prefix1 == null && EMPTYSTRING.equals(prefix)) - { + if (prefix1 == null && EMPTYSTRING.equals(prefix)) { // the elements URI is not known yet, and it // doesn't have a prefix, and we are currently // setting the uri for prefix "", so we have @@ -399,45 +348,36 @@ public final class ToUnknownStream extends SerializerBase m_firstElementURI = uri; } } - startPrefixMapping(prefix,uri, false); + startPrefixMapping(prefix, uri, false); } public boolean startPrefixMapping(String prefix, String uri, boolean shouldFlush) throws SAXException { boolean pushed = false; - if (m_firstTagNotEmitted) - { - if (m_firstElementName != null && shouldFlush) - { + if (m_firstTagNotEmitted) { + if (m_firstElementName != null && shouldFlush) { /* we've already seen a startElement, and this is a prefix mapping * for the up coming element, so flush the old element * then send this event on its way. */ flush(); pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); - } - else - { - if (m_namespacePrefix == null) - { + } else { + if (m_namespacePrefix == null) { m_namespacePrefix = new ArrayList<>(); m_namespaceURI = new ArrayList<>(); } m_namespacePrefix.add(prefix); m_namespaceURI.add(uri); - if (m_firstElementURI == null) - { + if (m_firstElementURI == null) { if (prefix.equals(m_firstElementPrefix)) m_firstElementURI = uri; } } - - } - else - { - pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); + } else { + pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); } return pushed; } @@ -446,54 +386,39 @@ public final class ToUnknownStream extends SerializerBase * This method cannot be cached because default is different in * HTML and XML (we need more than a boolean). */ - - public void setVersion(String version) - { + public void setVersion(String version) { m_handler.setVersion(version); - - // Cache call to setVersion() - // super.setVersion(version); - m_setVersion_called = true; } /** * @see org.xml.sax.ContentHandler#startDocument() */ - public void startDocument() throws SAXException - { + public void startDocument() throws SAXException { m_needToCallStartDocument = true; } - - - public void startElement(String qName) throws SAXException - { + public void startElement(String qName) throws SAXException { this.startElement(null, null, qName, null); } - public void startElement(String namespaceURI, String localName, String qName) throws SAXException - { + public void startElement(String namespaceURI, String localName, + String qName) throws SAXException { this.startElement(namespaceURI, localName, qName, null); } - public void startElement( - String namespaceURI, - String localName, - String elementName, - Attributes atts) throws SAXException + public void startElement(String namespaceURI, String localName, + String elementName, Attributes atts) + throws SAXException { - - if (m_needToCallSetDocumentInfo){ + if (m_needToCallSetDocumentInfo) { super.setDocumentInfo(); m_needToCallSetDocumentInfo = false; } /* we are notified of the start of an element */ - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { /* we have not yet sent the first element on its way */ - if (m_firstElementName != null) - { + if (m_firstElementName != null) { /* this is not the first element, but a later one. * But we have the old element pending, so flush it out, * then send this one on its way. @@ -645,16 +570,14 @@ public final class ToUnknownStream extends SerializerBase * Pass the call on to the underlying handler * @see XSLOutputAttributes#getVersion() */ - public String getVersion() - { + public String getVersion() { return m_handler.getVersion(); } /** * @see XSLOutputAttributes#setDoctype(String, String) */ - public void setDoctype(String system, String pub) - { + public void setDoctype(String system, String pub) { m_handler.setDoctypePublic(pub); m_handler.setDoctypeSystem(system); } @@ -665,10 +588,8 @@ public final class ToUnknownStream extends SerializerBase * @param doctype the public doctype to set * @see XSLOutputAttributes#setDoctypePublic(String) */ - public void setDoctypePublic(String doctype) - { + public void setDoctypePublic(String doctype) { m_handler.setDoctypePublic(doctype); - m_setDoctypePublic_called = true; } /** @@ -677,18 +598,15 @@ public final class ToUnknownStream extends SerializerBase * @param doctype the system doctype to set * @see XSLOutputAttributes#setDoctypeSystem(String) */ - public void setDoctypeSystem(String doctype) - { + public void setDoctypeSystem(String doctype) { m_handler.setDoctypeSystem(doctype); - m_setDoctypeSystem_called = true; } /** * Pass the call on to the underlying handler * @see XSLOutputAttributes#setEncoding(String) */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { m_handler.setEncoding(encoding); } @@ -696,34 +614,29 @@ public final class ToUnknownStream extends SerializerBase * Pass the call on to the underlying handler * @see XSLOutputAttributes#setIndent(boolean) */ - public void setIndent(boolean indent) - { + public void setIndent(boolean indent) { m_handler.setIndent(indent); } /** * Pass the call on to the underlying handler */ - public void setIndentAmount(int value) - { + public void setIndentAmount(int value) { m_handler.setIndentAmount(value); } /** * @see XSLOutputAttributes#setMediaType(String) */ - public void setMediaType(String mediaType) - { + public void setMediaType(String mediaType) { m_handler.setMediaType(mediaType); - m_setMediaType_called = true; } /** * Pass the call on to the underlying handler * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { m_handler.setOmitXMLDeclaration(b); } @@ -731,27 +644,16 @@ public final class ToUnknownStream extends SerializerBase * Pass the call on to the underlying handler * @see XSLOutputAttributes#setStandalone(String) */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { m_handler.setStandalone(standalone); } - /** - * @see XSLOutputAttributes#setVersion(String) - */ - /** * Pass the call on to the underlying handler * @see org.xml.sax.ext.DeclHandler#attributeDecl(String, String, String, String, String) */ - public void attributeDecl( - String arg0, - String arg1, - String arg2, - String arg3, - String arg4) - throws SAXException - { + public void attributeDecl(String arg0, String arg1, String arg2, + String arg3, String arg4) throws SAXException { m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4); } @@ -761,8 +663,7 @@ public final class ToUnknownStream extends SerializerBase */ public void elementDecl(String arg0, String arg1) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { emitFirstTag(); } m_handler.elementDecl(arg0, arg1); @@ -778,8 +679,7 @@ public final class ToUnknownStream extends SerializerBase String systemId) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.externalEntityDecl(name, publicId, systemId); @@ -792,8 +692,7 @@ public final class ToUnknownStream extends SerializerBase public void internalEntityDecl(String arg0, String arg1) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.internalEntityDecl(arg0, arg1); @@ -806,29 +705,21 @@ public final class ToUnknownStream extends SerializerBase public void characters(char[] characters, int offset, int length) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } - m_handler.characters(characters, offset, length); - } /** * Pass the call on to the underlying handler * @see org.xml.sax.ContentHandler#endDocument() */ - public void endDocument() throws SAXException - { - if (m_firstTagNotEmitted) - { + public void endDocument() throws SAXException { + if (m_firstTagNotEmitted) { flush(); } - m_handler.endDocument(); - - } /** @@ -838,17 +729,14 @@ public final class ToUnknownStream extends SerializerBase public void endElement(String namespaceURI, String localName, String qName) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); if (namespaceURI == null && m_firstElementURI != null) namespaceURI = m_firstElementURI; - if (localName == null && m_firstElementLocalName != null) localName = m_firstElementLocalName; } - m_handler.endElement(namespaceURI, localName, qName); } @@ -856,8 +744,7 @@ public final class ToUnknownStream extends SerializerBase * Pass the call on to the underlying handler * @see org.xml.sax.ContentHandler#endPrefixMapping(String) */ - public void endPrefixMapping(String prefix) throws SAXException - { + public void endPrefixMapping(String prefix) throws SAXException { m_handler.endPrefixMapping(prefix); } @@ -1071,12 +958,9 @@ public final class ToUnknownStream extends SerializerBase m_wrapped_handler_not_initialized = false; } - private void emitFirstTag() throws SAXException - { - if (m_firstElementName != null) - { - if (m_wrapped_handler_not_initialized) - { + private void emitFirstTag() throws SAXException { + if (m_firstElementName != null) { + if (m_wrapped_handler_not_initialized) { initStreamOutput(); m_wrapped_handler_not_initialized = false; } @@ -1086,14 +970,11 @@ public final class ToUnknownStream extends SerializerBase m_attributes = null; // Output namespaces of first tag - if (m_namespacePrefix != null) - { + if (m_namespacePrefix != null) { final int n = m_namespacePrefix.size(); - for (int i = 0; i < n; i++) - { - final String prefix = - (String) m_namespacePrefix.get(i); - final String uri = (String) m_namespaceURI.get(i); + for (int i = 0; i < n; i++) { + final String prefix = m_namespacePrefix.get(i); + final String uri = m_namespaceURI.get(i); m_handler.startPrefixMapping(prefix, uri, false); } m_namespacePrefix = null; @@ -1109,8 +990,7 @@ public final class ToUnknownStream extends SerializerBase * Don't want to override static function on SerializerBase * So added Unknown suffix to method name. */ - private String getLocalNameUnknown(String value) - { + private String getLocalNameUnknown(String value) { int idx = value.lastIndexOf(':'); if (idx >= 0) value = value.substring(idx + 1); @@ -1121,13 +1001,12 @@ public final class ToUnknownStream extends SerializerBase } /** - * Utility function to return prefix - * - * Don't want to override static function on SerializerBase - * So added Unknown suffix to method name. - */ - private String getPrefixPartUnknown(String qname) - { + * Utility function to return prefix + * + * Don't want to override static function on SerializerBase + * So added Unknown suffix to method name. + */ + private String getPrefixPartUnknown(String qname) { final int index = qname.indexOf(':'); return (index > 0) ? qname.substring(0, index) : EMPTYSTRING; } @@ -1139,8 +1018,7 @@ public final class ToUnknownStream extends SerializerBase * * @return true if the first element is an opening tag */ - private boolean isFirstElemHTML() - { + private boolean isFirstElemHTML() { boolean isHTML; // is the first tag html, not considering the prefix ? @@ -1148,29 +1026,27 @@ public final class ToUnknownStream extends SerializerBase getLocalNameUnknown(m_firstElementName).equalsIgnoreCase("html"); // Try to rule out if this is not to be an HTML document based on URI - if (isHTML - && m_firstElementURI != null - && !EMPTYSTRING.equals(m_firstElementURI)) + if (isHTML && + m_firstElementURI != null && + !EMPTYSTRING.equals(m_firstElementURI)) { // the element has a non-trivial namespace isHTML = false; } // Try to rule out if this is an not to be an HTML document based on prefix - if (isHTML && m_namespacePrefix != null) - { + if (isHTML && m_namespacePrefix != null) { /* the first element has a name of "html", but lets check the prefix. * If the prefix points to a namespace with a URL that is not "" * then the doecument doesn't start with an tag, and isn't html */ final int max = m_namespacePrefix.size(); - for (int i = 0; i < max; i++) - { + for (int i = 0; i < max; i++) { final String prefix = m_namespacePrefix.get(i); final String uri = m_namespaceURI.get(i); - if (m_firstElementPrefix != null - && m_firstElementPrefix.equals(prefix) - && !EMPTYSTRING.equals(uri)) + if (m_firstElementPrefix != null && + m_firstElementPrefix.equals(prefix) && + !EMPTYSTRING.equals(uri)) { // The first element has a prefix, so it can't be isHTML = false; @@ -1181,11 +1057,11 @@ public final class ToUnknownStream extends SerializerBase } return isHTML; } + /** * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { return m_handler.asDOMSerializer(); } @@ -1194,15 +1070,14 @@ public final class ToUnknownStream extends SerializerBase * specified in the cdata-section-elements attribute. * @see SerializationHandler#setCdataSectionElements(java.util.Vector) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { m_handler.setCdataSectionElements(URI_and_localNames); } + /** * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) */ - public void addAttributes(Attributes atts) throws SAXException - { + public void addAttributes(Attributes atts) throws SAXException { m_handler.addAttributes(atts); } @@ -1211,98 +1086,83 @@ public final class ToUnknownStream extends SerializerBase * Simply returns the mappings of the wrapped handler. * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { NamespaceMappings mappings = null; - if (m_handler != null) - { + if (m_handler != null) { mappings = m_handler.getNamespaceMappings(); } return mappings; } + /** * @see SerializationHandler#flushPending() */ - public void flushPending() throws SAXException - { - + public void flushPending() throws SAXException { flush(); - m_handler.flushPending(); } - private void flush() - { - try - { - if (m_firstTagNotEmitted) - { - emitFirstTag(); - } - if (m_needToCallStartDocument) - { - m_handler.startDocument(); - m_needToCallStartDocument = false; - } - } - catch(SAXException e) - { + private void flush() { + try { + if (m_firstTagNotEmitted) { + emitFirstTag(); + } + if (m_needToCallStartDocument) { + m_handler.startDocument(); + m_needToCallStartDocument = false; + } + } catch(SAXException e) { throw new RuntimeException(e.toString()); } - - } /** * @see ExtendedContentHandler#getPrefix */ - public String getPrefix(String namespaceURI) - { + public String getPrefix(String namespaceURI) { return m_handler.getPrefix(namespaceURI); } + /** * @see ExtendedContentHandler#entityReference(java.lang.String) */ - public void entityReference(String entityName) throws SAXException - { + public void entityReference(String entityName) throws SAXException { m_handler.entityReference(entityName); } /** * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) */ - public String getNamespaceURI(String qname, boolean isElement) - { + public String getNamespaceURI(String qname, boolean isElement) { return m_handler.getNamespaceURI(qname, isElement); } - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { return m_handler.getNamespaceURIFromPrefix(prefix); } - public void setTransformer(Transformer t) - { + public void setTransformer(Transformer t) { m_handler.setTransformer(t); if ((t instanceof SerializerTrace) && - (((SerializerTrace) t).hasTraceListeners())) { - m_tracer = (SerializerTrace) t; + (((SerializerTrace) t).hasTraceListeners())) + { + m_tracer = (SerializerTrace) t; } else { - m_tracer = null; + m_tracer = null; } } - public Transformer getTransformer() - { + + public Transformer getTransformer() { return m_handler.getTransformer(); } /** * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) */ - public void setContentHandler(ContentHandler ch) - { + public void setContentHandler(ContentHandler ch) { m_handler.setContentHandler(ch); } + /** * This method is used to set the source locator, which might be used to * generated an error message. @@ -1310,14 +1170,11 @@ public final class ToUnknownStream extends SerializerBase * * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { m_handler.setSourceLocator(locator); } - protected void firePseudoElement(String elementName) - { - + protected void firePseudoElement(String elementName) { if (m_tracer != null) { StringBuffer sb = new StringBuffer(); diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java index 82df564ee0b..6197e6e35ec 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java @@ -3,13 +3,12 @@ * DO NOT REMOVE OR ALTER! */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,9 +18,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: XSLOutputAttributes.java,v 1.2.4.1 2005/09/15 08:15:32 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.util.ArrayList; @@ -55,8 +52,7 @@ import java.util.ArrayList; * * @xsl.usage internal */ -interface XSLOutputAttributes -{ +interface XSLOutputAttributes { /** * Returns the previously set value of the value to be used as the public * identifier in the document type declaration (DTD). @@ -65,6 +61,7 @@ interface XSLOutputAttributes * output document. */ public String getDoctypePublic(); + /** * Returns the previously set value of the value to be used * as the system identifier in the document type declaration (DTD). @@ -73,13 +70,15 @@ interface XSLOutputAttributes * */ public String getDoctypeSystem(); + /** * @return the character encoding to be used in the output document. */ public String getEncoding(); + /** - * @return true if the output document should be indented to visually - * indicate its structure. + * @return true if the output document should be indented to visually + * indicate its structure. */ public boolean getIndent(); @@ -87,21 +86,25 @@ interface XSLOutputAttributes * @return the number of spaces to indent for each indentation level. */ public int getIndentAmount(); + /** * @return the mediatype the media-type or MIME type associated with the * output document. */ public String getMediaType(); + /** * @return true if the XML declaration is to be omitted from the output * document. */ public boolean getOmitXMLDeclaration(); + /** - * @return a value of "yes" if the standalone delaration is to - * be included in the output document. - */ + * @return a value of "yes" if the standalone delaration is to + * be included in the output document. + */ public String getStandalone(); + /** * @return the version of the output format. */ @@ -132,20 +135,23 @@ interface XSLOutputAttributes public void setDoctype(String system, String pub); /** Set the value coming from the xsl:output doctype-public stylesheet attribute. - * @param doctype the public identifier to be used in the DOCTYPE - * declaration in the output document. - */ + * @param doctype the public identifier to be used in the DOCTYPE + * declaration in the output document. + */ public void setDoctypePublic(String doctype); + /** Set the value coming from the xsl:output doctype-system stylesheet attribute. - * @param doctype the system identifier to be used in the DOCTYPE - * declaration in the output document. - */ + * @param doctype the system identifier to be used in the DOCTYPE + * declaration in the output document. + */ public void setDoctypeSystem(String doctype); + /** * Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * @param encoding the character encoding */ public void setEncoding(String encoding); + /** * Sets the value coming from the xsl:output indent stylesheet * attribute. @@ -153,18 +159,21 @@ interface XSLOutputAttributes * indicate its structure. */ public void setIndent(boolean indent); + /** * Sets the value coming from the xsl:output media-type stylesheet attribute. * @param mediatype the media-type or MIME type associated with the output * document. */ public void setMediaType(String mediatype); + /** * Sets the value coming from the xsl:output omit-xml-declaration stylesheet attribute * @param b true if the XML declaration is to be omitted from the output * document. */ public void setOmitXMLDeclaration(boolean b); + /** * Sets the value coming from the xsl:output standalone stylesheet attribute. * @param standalone a value of "yes" indicates that the @@ -172,6 +181,7 @@ interface XSLOutputAttributes * document. */ public void setStandalone(String standalone); + /** * Sets the value coming from the xsl:output version attribute. * @param version the version of the output format. @@ -194,6 +204,7 @@ interface XSLOutputAttributes * @return The value of the parameter */ public String getOutputProperty(String name); + /** * Get the default value for a property that affects seraialization, * or null if there is none. It is possible that a non-default value @@ -203,6 +214,7 @@ interface XSLOutputAttributes * @return The default value of the parameter, or null if there is no default value. */ public String getOutputPropertyDefault(String name); + /** * Set the non-default value for a property that affects seraialization. * @param name The name of the property, which is just the local name @@ -216,7 +228,7 @@ interface XSLOutputAttributes * * @val The non-default value of the parameter */ - public void setOutputProperty(String name, String val); + public void setOutputProperty(String name, String val); /** * Set the default value for a property that affects seraialization. @@ -231,5 +243,5 @@ interface XSLOutputAttributes * * @val The default value of the parameter */ - public void setOutputPropertyDefault(String name, String val); + public void setOutputPropertyDefault(String name, String val); } diff --git a/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java b/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java index 59d195e3d8b..c479ab117ba 100644 --- a/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java +++ b/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java @@ -27,17 +27,20 @@ import static jaxp.library.JAXPTestUtilities.getSystemProperty; import java.io.BufferedReader; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; -import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; @@ -47,6 +50,7 @@ import org.testng.AssertJUnit; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.w3c.dom.Document; +import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; @@ -69,33 +73,10 @@ import com.sun.org.apache.xml.internal.serialize.XMLSerializer; * @run testng/othervm -DrunSecMngr=true transform.TransformerTest * @run testng/othervm transform.TransformerTest * @summary Transformer Tests - * @bug 6272879 6305029 6505031 8150704 8162598 + * @bug 6272879 6305029 6505031 8150704 8162598 8169772 */ @Listeners({jaxp.library.FilePolicy.class}) public class TransformerTest { - private Transformer createTransformer() throws TransformerException { - return TransformerFactory.newInstance().newTransformer(); - } - - private Transformer createTransformerFromInputstream(InputStream xslStream) throws TransformerException { - return TransformerFactory.newInstance().newTransformer(new StreamSource(xslStream)); - } - - private Transformer createTransformerFromResource(String xslResource) throws TransformerException { - return TransformerFactory.newInstance().newTransformer(new StreamSource(getClass().getResource(xslResource).toString())); - } - - private Document transformInputStreamToDocument(Transformer transformer, InputStream sourceStream) throws TransformerException { - DOMResult response = new DOMResult(); - transformer.transform(new StreamSource(sourceStream), response); - return (Document)response.getNode(); - } - - private StringWriter transformResourceToStringWriter(Transformer transformer, String xmlResource) throws TransformerException { - StringWriter sw = new StringWriter(); - transformer.transform(new StreamSource(getClass().getResource(xmlResource).toString()), new StreamResult(sw)); - return sw; - } /** * Reads the contents of the given file into a string. @@ -302,10 +283,15 @@ public class TransformerTest { System.out.println(sourceXml); System.out.println(); + // transform to DOM result + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes()))); + DOMResult result = new DOMResult(); + t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result); + Document document = (Document)result.getNode(); + System.out.println("Result after transformation:"); System.out.println("============================"); - Document document = transformInputStreamToDocument(createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())), - new ByteArrayInputStream(sourceXml.getBytes())); OutputFormat format = new OutputFormat(); format.setIndenting(true); new XMLSerializer(System.out, format).serialize(document); @@ -335,13 +321,14 @@ public class TransformerTest { // test SAXSource SAXSource saxSource = new SAXSource(new XMLReaderFor6305029(), new InputSource()); StringWriter resultWriter = new StringWriter(); - createTransformer().transform(saxSource, new StreamResult(resultWriter)); + TransformerFactory tf = TransformerFactory.newInstance(); + tf.newTransformer().transform(saxSource, new StreamResult(resultWriter)); AssertJUnit.assertEquals("Identity transform of SAXSource", XML_DOCUMENT, resultWriter.toString()); // test StreamSource StreamSource streamSource = new StreamSource(new StringReader(XML_DOCUMENT)); resultWriter = new StringWriter(); - createTransformer().transform(streamSource, new StreamResult(resultWriter)); + tf.newTransformer().transform(streamSource, new StreamResult(resultWriter)); AssertJUnit.assertEquals("Identity transform of StreamSource", XML_DOCUMENT, resultWriter.toString()); } @@ -351,10 +338,13 @@ public class TransformerTest { */ @Test public final void testBug6505031() throws TransformerException { - Transformer transformer = createTransformerFromResource("transform.xsl"); - transformer.setParameter("config", getClass().getResource("config.xml").toString()); - transformer.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); - String s = transformResourceToStringWriter(transformer, "template.xml").toString(); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("transform.xsl").toString())); + t.setParameter("config", getClass().getResource("config.xml").toString()); + t.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("template.xml").toString()), new StreamResult(sw)); + String s = sw.toString(); Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value")); } @@ -365,17 +355,20 @@ public class TransformerTest { @Test public final void testBug8150704() throws TransformerException, IOException { System.out.println("Testing transformation of Bug8150704-1.xml..."); - Transformer transformer = createTransformerFromResource("Bug8150704-1.xsl"); - StringWriter result = transformResourceToStringWriter(transformer, "Bug8150704-1.xml"); - String resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-1.xsl").toString())); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("Bug8150704-1.xml").toString()), new StreamResult(sw)); + String resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); String reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-1.ref").getPath())); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-1.xml does not match reference"); System.out.println("Passed."); System.out.println("Testing transformation of Bug8150704-2.xml..."); - transformer = createTransformerFromResource("Bug8150704-2.xsl"); - result = transformResourceToStringWriter(transformer, "Bug8150704-2.xml"); - resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); + t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-2.xsl").toString())); + sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("Bug8150704-2.xml").toString()), new StreamResult(sw)); + resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-2.ref").getPath())); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-2.xml does not match reference"); System.out.println("Passed."); @@ -422,11 +415,15 @@ public class TransformerTest { System.out.println(sourceXml); System.out.println(); + // transform to DOM result + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes()))); + DOMResult result = new DOMResult(); + t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result); + Document document = (Document)result.getNode(); + System.out.println("Result after transformation:"); System.out.println("============================"); - Document document = transformInputStreamToDocument( - createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())), - new ByteArrayInputStream(sourceXml.getBytes())); OutputFormat format = new OutputFormat(); format.setIndenting(true); new XMLSerializer(System.out, format).serialize(document); @@ -438,4 +435,38 @@ public class TransformerTest { checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null); Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6"); } + + /** + * @bug 8169772 + * @summary Test transformation of DOM with null valued text node + * + * This test would throw a NullPointerException during transform when the + * fix was not present. + */ + @Test + public final void testBug8169772() throws ParserConfigurationException, + SAXException, IOException, TransformerException + { + // create a small DOM + Document doc = DocumentBuilderFactory.newInstance(). + newDocumentBuilder().parse( + new ByteArrayInputStream( + "".getBytes() + ) + ); + + // insert a bad element + Element e = doc.createElement("ERROR"); + e.appendChild(doc.createTextNode(null)); + doc.getDocumentElement().appendChild(e); + + // transform + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + TransformerFactory.newInstance().newTransformer().transform( + new DOMSource(doc.getDocumentElement()), new StreamResult(bos) + ); + System.out.println("Transformation result (DOM with null text node):"); + System.out.println("================================================"); + System.out.println(bos); + } } From e76a5487435693c10e4521faf5aa60bb54fd4695 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:33 +0000 Subject: [PATCH 184/402] Added tag jdk-9+146 for changeset 89406c257bc9 --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 60e0db5186c..58e9fe724f4 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -388,3 +388,4 @@ f64afae7f1a5608e438585bbf0bc23785e69cba0 jdk-9+141 1fc62b1c629fb80fdaa639d3b59452a184f0d705 jdk-9+143 8d337fd6333e28c48aa87880144b840aad82baaf jdk-9+144 ff98aa9ec9fae991e426ce5926fc9036d25f5562 jdk-9+145 +a22e2671d88f6b22a4aa82e3966986542ed2a381 jdk-9+146 From d768f16fea8a7919ba5ce18599541614e88a646f Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:33 +0000 Subject: [PATCH 185/402] Added tag jdk-9+146 for changeset d139f0e91e7e --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index 909878451d9..9adfbbce6b1 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -388,3 +388,4 @@ b32f998da32b488ec7c4e9dbb3c750841b48e74d jdk-9+141 6211236ef15ec796806357608b1dd1b70c258ece jdk-9+143 d4f1dae174098e799c48948e866054c52e11a186 jdk-9+144 a44b156ae7f06bf41b9bece30df7775e482395dd jdk-9+145 +ecd74b41ab65bf228837b5bdf99690638d55425c jdk-9+146 From 16734f37d5a32a73238bfd402ea80dc1a9cbae66 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:34 +0000 Subject: [PATCH 186/402] Added tag jdk-9+146 for changeset 296b6f1ad81e --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index cd5f02b0b6d..c7fc0f3084c 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -548,3 +548,4 @@ fec31089c2ef5a12dd64f401b0bf2e00f56ee0d0 jdk-9+140 d87d5d430c42342f0320ca7f5cbe0cbd1f9d62ba jdk-9+143 6187b582d02aee38341dc8ce4011906e9b364e9f jdk-9+144 61e7ea56312351657e69198c503a6f7bf865af83 jdk-9+145 +a82cb5350cad96a0b4de496afebe3ded89f27efa jdk-9+146 From 2e931825c6a4fb29ddc26e23fc1a0d2c87d9c37d Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:35 +0000 Subject: [PATCH 187/402] Added tag jdk-9+146 for changeset f7a57d034f22 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 766e790c648..e6027fc4c5b 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -388,3 +388,4 @@ e93b7ea559759f036c9f69fd2ddaf47bb4e98385 jdk-9+140 8dbc8594f9d5149bf1c22221272284609408227a jdk-9+143 efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 99b7853cfbd8227c4441de4b6119c10742556840 jdk-9+145 +6e4ff59afb5d0adf21a72c4ff534326594a99e5d jdk-9+146 From 174b258e57b0f4642bc141017bfc39d77b380681 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:35 +0000 Subject: [PATCH 188/402] Added tag jdk-9+146 for changeset 0b97f62b6064 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index c3fd9c28825..b0676a90a3d 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -388,3 +388,4 @@ bdafa0cc34a97a2f8db4847a4efd34b407943591 jdk-9+142 ce81d03ad7320dca3d673374c1a33bc0efd9136a jdk-9+143 99be33734ff62b75116b1202d49a4d4e1bda4226 jdk-9+144 71558b38bad786f11350790cef7d2c6409813e91 jdk-9+145 +09eda28b98e4b9cae1d29e94f0cf1a01cc42c207 jdk-9+146 From ebe680ca0f5b990edcde865718f3f9400ef4cdaf Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:35 +0000 Subject: [PATCH 189/402] Added tag jdk-9+146 for changeset 17e6a319acd1 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index 0cce729770a..9ab79ccac2c 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -391,3 +391,4 @@ b2c18f755228d1d19a86cd7d5fa1abb6b1495dfb jdk-9+141 1c988e708a06257119d54d8a57e99e3b0f37ff18 jdk-9+143 92523c51d6a48b0a83912ba3cc43bc57b8159c2a jdk-9+144 29277a4e73077269358859c43bd6658593fc0410 jdk-9+145 +1461e3e07876ea61bd0a07355a43912c9b04022a jdk-9+146 From 51f50b64e51f8354c4d6ebc7f783935e1d7dcec5 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:36 +0000 Subject: [PATCH 190/402] Added tag jdk-9+146 for changeset 6003e36b56df --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index ab225307c96..b904c053085 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -388,3 +388,4 @@ d245e56f4a79a8a8d18bd143c08f079ee98ab638 jdk-9+142 6ef8a1453577832626b0efb7f70a3102b721ebbf jdk-9+143 47871e348144bafddea0ede3a44299461e254a2d jdk-9+144 cb9e896265ef45295fdd09986dee76624e4d41e4 jdk-9+145 +26f972dc2d174a75bc32131c29661c78568586b0 jdk-9+146 From 1be16f5deedbfebb815566ba8daa6ee7350ea3c6 Mon Sep 17 00:00:00 2001 From: Lana Steuck Date: Wed, 23 Nov 2016 16:16:37 +0000 Subject: [PATCH 191/402] Added tag jdk-9+146 for changeset e9aa3423c897 --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index fd73992bc90..86eef2f2fc5 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -379,3 +379,4 @@ d3f5d7311a1aec3152b17d75046d5d298245a0b4 jdk-9+142 b4e57ead3fae4939b70dd345d1f6744a1dedfa21 jdk-9+143 a7f21ee6ed30695a6de14e74035d2857a754f62b jdk-9+144 4a68dd740be8aa0d1a25f94985b3cb2e190ccfce jdk-9+145 +55f5a96988de8237f3ee65a69aa4a48aed9ca8d4 jdk-9+146 From 794f11de728e08f4c5ae4119d45956fe86a5fdd2 Mon Sep 17 00:00:00 2001 From: John Jiang Date: Wed, 23 Nov 2016 18:13:51 -0800 Subject: [PATCH 192/402] 8158916: ProblemList.txt update for com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java Change the associated issue from JDK-8141370 to JDK-8169942 Reviewed-by: dfuchs --- jdk/test/ProblemList.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 91e2c4b4f30..b42555a066c 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -304,6 +304,6 @@ demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java 8151899 generic- # jdk_other -com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8141370 linux-i586,macosx-all +com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8169942 linux-i586,macosx-all,windows-x64 ############################################################################ From b1a1a5ab71ef0e2b732cee7d771cac2953429b16 Mon Sep 17 00:00:00 2001 From: Jonathan Gibbons Date: Wed, 23 Nov 2016 19:31:41 -0800 Subject: [PATCH 193/402] 8170301: remove debug print statement Reviewed-by: ksrini --- .../share/classes/com/sun/tools/javac/main/Option.java | 1 - 1 file changed, 1 deletion(-) diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java index 8d58c0abe74..27edb7b0b02 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java @@ -682,7 +682,6 @@ public enum Option { Class.forName(JDK9Wrappers.VMHelper.VM_CLASSNAME); String[] runtimeArgs = JDK9Wrappers.VMHelper.getRuntimeArguments(); for (String arg : runtimeArgs) { - System.err.println("runtime arg: " + arg); // Handle any supported runtime options; ignore all others. // The runtime arguments always use the single token form, e.g. "--name=value". for (Option o : getSupportedRuntimeOptions()) { From 54244b5e6d18a0e16adabaecc7d9c1eebe9ce0bf Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Thu, 24 Nov 2016 11:44:37 +0100 Subject: [PATCH 194/402] 8170279: Langtools test/Makefile ignores failed tests Reviewed-by: alanb, tbell, mchung --- langtools/test/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/langtools/test/Makefile b/langtools/test/Makefile index 57792fa9721..47e9c2b08b0 100644 --- a/langtools/test/Makefile +++ b/langtools/test/Makefile @@ -318,7 +318,7 @@ jtreg-tests: check-jtreg FRC @rm -f -r $(JTREG_OUTPUT_DIR)/JTwork $(JTREG_OUTPUT_DIR)/JTreport \ $(JTREG_OUTPUT_DIR)/diff.html $(JTREG_OUTPUT_DIR)/status.txt @mkdir -p $(JTREG_OUTPUT_DIR) - JT_JAVA=$(JT_JAVA) $(JTREG) \ + ( JT_JAVA=$(JT_JAVA) $(JTREG) \ -a -ignore:quiet $(if $(JTREG_VERBOSE),-v:$(JTREG_VERBOSE)) \ -r:$(JTREG_OUTPUT_DIR)/JTreport \ -w:$(JTREG_OUTPUT_DIR)/JTwork \ @@ -327,10 +327,10 @@ jtreg-tests: check-jtreg FRC $(JTREG_EXCLUSIONS) \ $(JTREG_OPTIONS) \ $(JTREG_TESTDIRS) \ - 2>&1 | tee $(JTREG_OUTPUT_DIR)/output.txt \ - || ( $(call EXIT_IF_FATAL,$(FATAL_JTREG_EXIT)) ; \ + || ( $(call EXIT_IF_FATAL,$(FATAL_JTREG_EXIT)) ; \ echo $$status > $(JTREG_OUTPUT_DIR)/status.txt \ - ) + ) \ + ) 2>&1 | tee $(JTREG_OUTPUT_DIR)/output.txt ifdef JTREG_REFERENCE JT_JAVA=$(JT_JAVA) $(JTDIFF) -o $(JTREG_OUTPUT_DIR)/diff.html \ $(JTREG_REFERENCE) $(JTREG_OUTPUT_DIR)/JTreport \ From 500ce8299e0751397e58e9f60676d93b9bc31101 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Thu, 24 Nov 2016 11:50:26 +0100 Subject: [PATCH 195/402] 8170280: Enable -g for all java compilation in the build Reviewed-by: simonis, tbell, dholmes, ihse --- common/autoconf/flags.m4 | 1 - common/autoconf/generated-configure.sh | 4 +--- make/Images.gmk | 2 +- make/common/JavaCompilation.gmk | 7 ++++++- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index 6a0eb9f8e3e..24fbf4422b1 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -838,7 +838,6 @@ AC_DEFUN([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK_HELPER], fastdebug | slowdebug ) $2CFLAGS_JDK="[$]$2CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" $2CXXFLAGS_JDK="[$]$2CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 55e9e3f4eca..e643c426a89 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -5093,7 +5093,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1479822431 +DATE_WHEN_GENERATED=1479984616 ############################################################################### # @@ -50022,7 +50022,6 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA fastdebug | slowdebug ) CFLAGS_JDK="$CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" CXXFLAGS_JDK="$CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; @@ -50846,7 +50845,6 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA fastdebug | slowdebug ) OPENJDK_BUILD_CFLAGS_JDK="$OPENJDK_BUILD_CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" OPENJDK_BUILD_CXXFLAGS_JDK="$OPENJDK_BUILD_CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; diff --git a/make/Images.gmk b/make/Images.gmk index 1af9698a218..f9bc0e243d6 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -131,7 +131,7 @@ JLINK_TOOL := $(JLINK) --module-path $(IMAGES_OUTPUTDIR)/jmods \ $(JLINK_JLI_CLASSES) \ # -JLINK_JRE_EXTRA_OPTS := --no-man-pages --no-header-files +JLINK_JRE_EXTRA_OPTS := --no-man-pages --no-header-files --strip-debug ifeq ($(JLINK_KEEP_PACKAGED_MODULES), true) JLINK_JDK_EXTRA_OPTS := --keep-packaged-modules $(JDK_IMAGE_DIR)/jmods diff --git a/make/common/JavaCompilation.gmk b/make/common/JavaCompilation.gmk index 9220865a534..21e8517685d 100644 --- a/make/common/JavaCompilation.gmk +++ b/make/common/JavaCompilation.gmk @@ -172,6 +172,7 @@ endef # KEEP_DUPS:=Do not remove duplicate file names from different source roots. # FAIL_NO_SRC:=Set to false to not fail the build if no source files are found, # default is true. +# DEBUG_SYMBOLS:=Set to false to disable generation of debug symbols. SetupJavaCompilation = $(NamedParamsMacroTemplate) define SetupJavaCompilationBody @@ -183,7 +184,11 @@ define SetupJavaCompilationBody # Extract the info from the java compiler setup. $1_JVM := $$($$($1_SETUP)_JVM) $1_JAVAC := $$($$($1_SETUP)_JAVAC) - $1_FLAGS := $$($$($1_SETUP)_FLAGS) $$($1_ADD_JAVAC_FLAGS) $(JAVAC_FLAGS) + $1_FLAGS := + ifneq ($$($1_DEBUG_SYMBOLS), false) + $1_FLAGS := -g + endif + $1_FLAGS += $$($$($1_SETUP)_FLAGS) $$($1_ADD_JAVAC_FLAGS) $(JAVAC_FLAGS) ifneq ($$($1_CLASSPATH), ) $1_FLAGS += -cp $$(call PathList, $$($1_CLASSPATH)) endif From 8a83f76baae119bb2c55ad14199004eea04d1081 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Thu, 24 Nov 2016 15:32:14 +0100 Subject: [PATCH 196/402] 7164925: Change -KPIC to -xcode=pic32 on sparc Reviewed-by: erikj --- common/autoconf/flags.m4 | 12 ++++++++---- common/autoconf/generated-configure.sh | 16 ++++++++++------ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index 24fbf4422b1..ba1e8dbc4b1 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -311,7 +311,11 @@ AC_DEFUN([FLAGS_SETUP_COMPILER_FLAGS_FOR_LIBS], SET_SHARED_LIBRARY_MAPFILE='-Wl,-version-script=[$]1' fi elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then - PICFLAG="-KPIC" + if test "x$OPENJDK_TARGET_CPU" = xsparcv9; then + PICFLAG="-xcode=pic32" + else + PICFLAG="-KPIC" + fi C_FLAG_REORDER='-xF' CXX_FLAG_REORDER='-xF' SHARED_LIBRARY_FLAGS="-G" @@ -893,12 +897,12 @@ AC_DEFUN([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK_HELPER], # Set some additional per-OS defines. if test "x$OPENJDK_$1_OS" = xlinux; then $2JVM_CFLAGS="[$]$2JVM_CFLAGS -DLINUX" - $2JVM_CFLAGS="[$]$2JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + $2JVM_CFLAGS="[$]$2JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_$1_OS" = xsolaris; then $2JVM_CFLAGS="[$]$2JVM_CFLAGS -DSOLARIS" $2JVM_CFLAGS="[$]$2JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_$1_OS" = xmacosx; then $2COMMON_CCXXFLAGS_JDK="[$]$2COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" $2JVM_CFLAGS="[$]$2JVM_CFLAGS -D_ALLBSD_SOURCE" @@ -1309,7 +1313,7 @@ BASIC_DEFUN_NAMED([FLAGS_COMPILER_CHECK_ARGUMENTS], AC_MSG_CHECKING([if both compilers support "ARG_ARGUMENT"]) supports=no if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi - + AC_MSG_RESULT([$supports]) if test "x$supports" = "xyes" ; then : diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index e643c426a89..9179032971e 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -5093,7 +5093,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1479984616 +DATE_WHEN_GENERATED=1479997904 ############################################################################### # @@ -49103,7 +49103,11 @@ $as_echo "$ac_cv_c_bigendian" >&6; } SET_SHARED_LIBRARY_MAPFILE='-Wl,-version-script=$1' fi elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then - PICFLAG="-KPIC" + if test "x$OPENJDK_TARGET_CPU" = xsparcv9; then + PICFLAG="-xcode=pic32" + else + PICFLAG="-KPIC" + fi C_FLAG_REORDER='-xF' CXX_FLAG_REORDER='-xF' SHARED_LIBRARY_FLAGS="-G" @@ -50077,12 +50081,12 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA # Set some additional per-OS defines. if test "x$OPENJDK_TARGET_OS" = xlinux; then JVM_CFLAGS="$JVM_CFLAGS -DLINUX" - JVM_CFLAGS="$JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + JVM_CFLAGS="$JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_TARGET_OS" = xsolaris; then JVM_CFLAGS="$JVM_CFLAGS -DSOLARIS" JVM_CFLAGS="$JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_TARGET_OS" = xmacosx; then COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" JVM_CFLAGS="$JVM_CFLAGS -D_ALLBSD_SOURCE" @@ -50900,12 +50904,12 @@ $as_echo "$as_me: GCC >= 6 detected; adding ${NO_DELETE_NULL_POINTER_CHECKS_CFLA # Set some additional per-OS defines. if test "x$OPENJDK_BUILD_OS" = xlinux; then OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -DLINUX" - OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_BUILD_OS" = xsolaris; then OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -DSOLARIS" OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_BUILD_OS" = xmacosx; then OPENJDK_BUILD_COMMON_CCXXFLAGS_JDK="$OPENJDK_BUILD_COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -D_ALLBSD_SOURCE" From 87f732d5818c9d0adf7a66ea511a3069bde78790 Mon Sep 17 00:00:00 2001 From: Frank Yuan Date: Fri, 25 Nov 2016 11:16:51 +0800 Subject: [PATCH 197/402] 8170192: [JAXP] [TESTBUG] test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java should grant permissions to jtreg, javatest, and testng jars Reviewed-by: dfuchs, clanger, joehw, jjg, lana --- .../libs/jaxp/library/JAXPPolicyManager.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java index a52c854a707..652997edd15 100644 --- a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java @@ -23,6 +23,7 @@ package jaxp.library; +import java.net.URL; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; @@ -34,6 +35,7 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.PropertyPermission; +import java.util.Set; import java.util.StringJoiner; @@ -107,12 +109,7 @@ public class JAXPPolicyManager { addPermission(new SecurityPermission("getPolicy")); addPermission(new SecurityPermission("setPolicy")); addPermission(new RuntimePermission("setSecurityManager")); - //Properties that jtreg and TestNG require - addPermission(new PropertyPermission("testng.show.stack.frames", "read")); addPermission(new PropertyPermission("test.src", "read")); - addPermission(new PropertyPermission("test.classes", "read")); - addPermission(new PropertyPermission("dataproviderthreadcount", "read")); - addPermission(new PropertyPermission("experimental", "read")); } /* @@ -163,6 +160,8 @@ public class JAXPPolicyManager { * JAXP concrete classes. */ class TestPolicy extends Policy { + private final static Set TEST_JARS = + Set.of("jtreg.jar", "javatest.jar", "testng.jar", "jcommander.jar"); private final PermissionCollection permissions = new Permissions(); private ThreadLocal> transientPermissions = new ThreadLocal<>(); @@ -211,6 +210,16 @@ class TestPolicy extends Policy { return permissions; } + private boolean isTestMachineryDomain(ProtectionDomain domain) { + CodeSource cs = (domain == null) ? null : domain.getCodeSource(); + URL loc = (cs == null) ? null : cs.getLocation(); + String path = (loc == null) ? null : loc.getPath(); + return path != null && TEST_JARS.stream() + .filter(path::endsWith) + .findAny() + .isPresent(); + } + @Override public boolean implies(ProtectionDomain domain, Permission perm) { if (allowAll()) @@ -221,8 +230,11 @@ class TestPolicy extends Policy { if (permissions.implies(perm)) return true; - else - return tmpImplies(perm); + + if (isTestMachineryDomain(domain)) + return true; + + return tmpImplies(perm); } /* From f4c9d73b3ef7dacbde0187c13085c3dcf9960ee6 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Thu, 24 Nov 2016 20:48:52 -0800 Subject: [PATCH 198/402] 8164316: Refine the Doclet APIs Reviewed-by: jjg --- .../classes/jdk/javadoc/doclet/Doclet.java | 31 +- .../jdk/javadoc/doclet/DocletEnvironment.java | 71 ++-- .../jdk/javadoc/doclet/package-info.java | 324 ++++++++++-------- .../jdk/javadoc/doclet/taglet/Taglet.java | 8 +- .../doclets/formats/html/ClassUseWriter.java | 3 +- .../formats/html/ConfigurationImpl.java | 267 ++++++--------- .../doclets/formats/html/HtmlDoclet.java | 8 +- .../formats/html/HtmlDocletWriter.java | 4 +- .../formats/html/ModuleFrameWriter.java | 6 +- .../formats/html/PackageFrameWriter.java | 6 +- .../html/SerializedFormWriterImpl.java | 2 +- .../formats/html/SourceToHTMLConverter.java | 4 +- .../doclets/toolkit/AbstractDoclet.java | 11 +- .../doclets/toolkit/Configuration.java | 293 +++++++++------- .../internal/doclets/toolkit/WorkArounds.java | 10 - .../builders/SerializedFormBuilder.java | 2 +- .../doclets/toolkit/util/ClassTree.java | 4 +- .../doclets/toolkit/util/ClassUseMapper.java | 2 +- .../util/DeprecatedAPIListBuilder.java | 2 +- .../doclets/toolkit/util/IndexBuilder.java | 4 +- .../internal/doclets/toolkit/util/Utils.java | 46 ++- .../jdk/javadoc/internal/tool/DocEnvImpl.java | 52 +-- .../javadoc/internal/tool/ElementsTable.java | 223 +++++------- .../javadoc/internal/tool/JavadocEnter.java | 1 + .../jdk/javadoc/internal/tool/Start.java | 34 +- .../internal/tool/ToolEnvironment.java | 18 +- .../doclet/testBaseClass/BaseClass.java | 21 +- .../test/jdk/javadoc/tool/6227454/Test.java | 31 +- .../javadoc/tool/BreakIteratorWarning.java | 3 +- .../javadoc/tool/InlineTagsWithBraces.java | 2 +- langtools/test/jdk/javadoc/tool/NoStar.java | 3 +- .../jdk/javadoc/tool/OptionSyntaxTest.java | 25 +- .../jdk/javadoc/tool/T4994049/T4994049.java | 3 +- .../completionFailure/CompletionFailure.java | 3 +- .../test/jdk/javadoc/tool/dupOk/DupOk.java | 3 +- .../jdk/javadoc/tool/example/Example.java | 159 +++++++++ .../test/jdk/javadoc/tool/example/Tester.java | 116 +++++++ .../jdk/javadoc/tool/example/overview.html | 27 ++ .../javadoc/tool/modules/ModuleTestBase.java | 16 +- .../javadoc/tool/sourceOnly/p/SourceOnly.java | 7 +- .../tool/sourceOption/SourceOption.java | 3 +- .../test/tools/lib/toolbox/JavadocTask.java | 10 + 42 files changed, 1079 insertions(+), 789 deletions(-) create mode 100644 langtools/test/jdk/javadoc/tool/example/Example.java create mode 100644 langtools/test/jdk/javadoc/tool/example/Tester.java create mode 100644 langtools/test/jdk/javadoc/tool/example/overview.html diff --git a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java index 75572f35aff..103c3c8196d 100644 --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java @@ -25,7 +25,7 @@ package jdk.javadoc.doclet; -import java.util.ListIterator; +import java.util.List; import java.util.Locale; import java.util.Set; @@ -67,7 +67,7 @@ public interface Doclet { * @param locale the locale to be used * @param reporter the reporter to be used */ - public void init(Locale locale, Reporter reporter); + void init(Locale locale, Reporter reporter); /** * Returns a name identifying the doclet. A name is a simple identifier @@ -76,14 +76,14 @@ public interface Doclet { * * @return name of the Doclet */ - public abstract String getName(); + String getName(); /** * Returns all the supported options. * * @return a set containing all the supported options, an empty set if none */ - public Set