diff --git a/src/java.base/share/classes/java/lang/String.java b/src/java.base/share/classes/java/lang/String.java index d366e676602..b687894df1c 100644 --- a/src/java.base/share/classes/java/lang/String.java +++ b/src/java.base/share/classes/java/lang/String.java @@ -37,6 +37,7 @@ import java.util.Objects; import java.util.Spliterator; import java.util.StringJoiner; +import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -2972,6 +2973,25 @@ public String align(int n) { return indent(indent > n ? Integer.MIN_VALUE : indent, true); } + /** + * This method allows the application of a function to {@code this} + * string. The function should expect a single String argument + * and produce an {@code R} result. + * + * @param f functional interface to a apply + * + * @param class of the result + * + * @return the result of applying the function to this string + * + * @see java.util.function.Function + * + * @since 12 + */ + public R transform(Function f) { + return f.apply(this); + } + /** * This object (which is already a string!) is itself returned. * diff --git a/src/java.base/share/classes/java/net/HostPortrange.java b/src/java.base/share/classes/java/net/HostPortrange.java index 09f20d43cbe..56bf21e466d 100644 --- a/src/java.base/share/classes/java/net/HostPortrange.java +++ b/src/java.base/share/classes/java/net/HostPortrange.java @@ -60,7 +60,7 @@ public int hashCode() { HostPortrange(String scheme, String str) { // Parse the host name. A name has up to three components, the // hostname, a port number, or two numbers representing a port - // range. "www.sun.com:8080-9090" is a valid host name. + // range. "www.example.com:8080-9090" is a valid host name. // With IPv6 an address can be 2010:836B:4179::836B:4179 // An IPv6 address needs to be enclose in [] diff --git a/src/java.base/share/classes/java/net/InetAddress.java b/src/java.base/share/classes/java/net/InetAddress.java index 65b95d24e35..5d9ae2ae1ad 100644 --- a/src/java.base/share/classes/java/net/InetAddress.java +++ b/src/java.base/share/classes/java/net/InetAddress.java @@ -1168,7 +1168,7 @@ private static NameService createNameService() { * No name service is checked for the validity of the address. * *

The host name can either be a machine name, such as - * "{@code java.sun.com}", or a textual representation of its IP + * "{@code www.example.com}", or a textual representation of its IP * address. *

No validity checking is done on the host name either. * @@ -1213,7 +1213,7 @@ public static InetAddress getByAddress(String host, byte[] addr) * Determines the IP address of a host, given the host's name. * *

The host name can either be a machine name, such as - * "{@code java.sun.com}", or a textual representation of its + * "{@code www.example.com}", or a textual representation of its * IP address. If a literal IP address is supplied, only the * validity of the address format is checked. * @@ -1259,7 +1259,7 @@ private static InetAddress getByName(String host, InetAddress reqAddr) * based on the configured name service on the system. * *

The host name can either be a machine name, such as - * "{@code java.sun.com}", or a textual representation of its IP + * "{@code www.example.com}", or a textual representation of its IP * address. If a literal IP address is supplied, only the * validity of the address format is checked. * diff --git a/src/java.base/share/classes/java/net/SocketPermission.java b/src/java.base/share/classes/java/net/SocketPermission.java index 60866b053f6..c1ff962c051 100644 --- a/src/java.base/share/classes/java/net/SocketPermission.java +++ b/src/java.base/share/classes/java/net/SocketPermission.java @@ -63,7 +63,7 @@ * or as "localhost" (for the local machine). * The wildcard "*" may be included once in a DNS name host * specification. If it is included, it must be in the leftmost - * position, as in "*.sun.com". + * position, as in "*.example.com". *

* The format of the IPv6reference should follow that specified in RFC 2732: Format @@ -115,11 +115,11 @@ * note that if the following permission: * *

- *   p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept");
+ *   p1 = new SocketPermission("foo.example.com:7777", "connect,accept");
  * 
* * is granted to some code, it allows that code to connect to port 7777 on - * {@code puffin.eng.sun.com}, and to accept connections on that port. + * {@code foo.example.com}, and to accept connections on that port. * *

Similarly, if the following permission: * @@ -211,7 +211,7 @@ public final class SocketPermission extends Permission // all the IP addresses of the host private transient InetAddress[] addresses; - // true if the hostname is a wildcard (e.g. "*.sun.com") + // true if the hostname is a wildcard (e.g. "*.example.com") private transient boolean wildcard; // true if we were initialized with a single numeric IP address @@ -274,9 +274,9 @@ private static synchronized Debug getDebug() { *

* Examples of SocketPermission instantiation are the following: *

-     *    nr = new SocketPermission("www.catalog.com", "connect");
-     *    nr = new SocketPermission("www.sun.com:80", "connect");
-     *    nr = new SocketPermission("*.sun.com", "connect");
+     *    nr = new SocketPermission("www.example.com", "connect");
+     *    nr = new SocketPermission("www.example.com:80", "connect");
+     *    nr = new SocketPermission("*.example.com", "connect");
      *    nr = new SocketPermission("*.edu", "resolve");
      *    nr = new SocketPermission("204.160.241.0", "connect");
      *    nr = new SocketPermission("localhost:1024-65535", "listen");
@@ -400,7 +400,7 @@ private void init(String host, int mask) {
 
         // Parse the host name.  A name has up to three components, the
         // hostname, a port number, or two numbers representing a port
-        // range.   "www.sun.com:8080-9090" is a valid host name.
+        // range.   "www.example.com:8080-9090" is a valid host name.
 
         // With IPv6 an address can be 2010:836B:4179::836B:4179
         // An IPv6 address needs to be enclose in []
@@ -835,10 +835,10 @@ void getIP()
      * 
    *
  • If this object was initialized with a single IP address and one of p's * IP addresses is equal to this object's IP address. - *
  • If this object is a wildcard domain (such as *.sun.com), and + *
  • If this object is a wildcard domain (such as *.example.com), and * p's canonical name (the name without any preceding *) - * ends with this object's canonical host name. For example, *.sun.com - * implies *.eng.sun.com. + * ends with this object's canonical host name. For example, *.example.com + * implies *.foo.example.com. *
  • If this object was not initialized with a single IP address, and one of this * object's IP addresses equals one of p's IP addresses. *
  • If this canonical name equals p's canonical name. @@ -878,7 +878,7 @@ public boolean implies(Permission p) { *
  • Checks that "p"'s port range is included in this port range *
  • If this object was initialized with an IP address, checks that * one of "p"'s IP addresses is equal to this object's IP address. - *
  • If either object is a wildcard domain (i.e., "*.sun.com"), + *
  • If either object is a wildcard domain (i.e., "*.example.com"), * attempt to match based on the wildcard. *
  • If this object was not initialized with an IP address, attempt * to find a match based on the IP addresses in both objects. @@ -944,8 +944,8 @@ boolean impliesIgnoreMask(SocketPermission that) { // check and see if we have any wildcards... if (this.wildcard || that.wildcard) { // if they are both wildcards, return true iff - // that's cname ends with this cname (i.e., *.sun.com - // implies *.eng.sun.com) + // that's cname ends with this cname (i.e., *.example.com + // implies *.foo.example.com) if (this.wildcard && that.wildcard) return (that.cname.endsWith(this.cname)); @@ -1057,7 +1057,7 @@ public boolean equals(Object obj) { // "1.2.3.4" equal to "1.2.3.4.", or // "*.edu" equal to "*.edu", but it // does not catch "crypto" equal to - // "crypto.eng.sun.com". + // "crypto.foo.example.com". if (this.getName().equalsIgnoreCase(that.getName())) { return true; @@ -1313,7 +1313,7 @@ public static void main(String args[]) throws Exception { SocketPermissionCollection nps = new SocketPermissionCollection(); nps.add(this_); nps.add(new SocketPermission("www-leland.stanford.edu","connect")); - nps.add(new SocketPermission("www-sun.com","connect")); + nps.add(new SocketPermission("www-example.com","connect")); System.out.println("nps.implies(that) = " + nps.implies(that_)); System.out.println("-----\n"); } diff --git a/src/java.base/share/classes/java/net/URI.java b/src/java.base/share/classes/java/net/URI.java index 4a789d462d5..2f5ac158d6e 100644 --- a/src/java.base/share/classes/java/net/URI.java +++ b/src/java.base/share/classes/java/net/URI.java @@ -83,7 +83,7 @@ * subject to further parsing. Some examples of opaque URIs are: * *
      - *
    • {@code mailto:java-net@java.sun.com}
    • + *
    • {@code mailto:java-net@www.example.com}
    • *
    • {@code news:comp.lang.java}
    • *
    • {@code urn:isbn:096139210x}
    • *
    @@ -399,7 +399,7 @@ * For any URI u that does not contain redundant syntax such as two * slashes before an empty authority (as in {@code file:///tmp/} ) or a * colon following a host name but no port (as in - * {@code http://java.sun.com:} ), and that does not encode characters + * {@code http://www.example.com:} ), and that does not encode characters * except those that must be quoted, the following identities also hold: *
      *     new URI(u.getScheme(),
    diff --git a/src/java.base/share/classes/java/net/URL.java b/src/java.base/share/classes/java/net/URL.java
    index 0d6e4a52a87..93de5622ed8 100644
    --- a/src/java.base/share/classes/java/net/URL.java
    +++ b/src/java.base/share/classes/java/net/URL.java
    @@ -95,7 +95,7 @@
      * as a "ref" or a "reference". The fragment is indicated by the sharp
      * sign character "#" followed by more characters. For example,
      * 
    - *     http://java.sun.com/index.html#chapter1
    + *     http://www.example.com/index.html#chapter1
      * 
    *

    * This fragment is not technically part of the URL. Rather, it @@ -109,7 +109,7 @@ * relative to another URL. Relative URLs are frequently used within * HTML pages. For example, if the contents of the URL: *

    - *     http://java.sun.com/index.html
    + *     http://www.example.com/index.html
      * 
    * contained within it the relative URL: *
    @@ -117,7 +117,7 @@
      * 
    * it would be a shorthand for: *
    - *     http://java.sun.com/FAQ.html
    + *     http://www.example.com/FAQ.html
      * 
    *

    * The relative URL need not specify all the components of a URL. If @@ -1421,13 +1421,12 @@ static URLStreamHandler getURLStreamHandler(String protocol) { // this thread created. handler = handler2; } - } - // Insert this handler into the hashtable - if (handler != null) { - handlers.put(protocol, handler); + // Insert this handler into the hashtable + if (handler != null) { + handlers.put(protocol, handler); + } } - return handler; } diff --git a/src/java.base/share/classes/java/net/URLPermission.java b/src/java.base/share/classes/java/net/URLPermission.java index 33751937858..56c066838a2 100644 --- a/src/java.base/share/classes/java/net/URLPermission.java +++ b/src/java.base/share/classes/java/net/URLPermission.java @@ -57,7 +57,7 @@ * RFC 2732. Literal IPv6 addresses must however, be enclosed in '[]' characters. * The dnsname specification can be preceded by "*." which means * the name will match any hostname whose right-most domain labels are the same as - * this name. For example, "*.oracle.com" matches "foo.bar.oracle.com" + * this name. For example, "*.example.com" matches "foo.bar.example.com" *

    * portrange is used to specify a port number, or a bounded or unbounded range of ports * that this permission applies to. If portrange is absent or invalid, then a default @@ -78,18 +78,18 @@ * Example urlDescription * * - * http://www.oracle.com/a/b/c.html + * http://www.example.com/a/b/c.html * A url which identifies a specific (single) resource * - * http://www.oracle.com/a/b/* + * http://www.example.com/a/b/* * The '*' character refers to all resources in the same "directory" - in * other words all resources with the same number of path components, and * which only differ in the final path component, represented by the '*'. * * - * http://www.oracle.com/a/b/- + * http://www.example.com/a/b/- * The '-' character refers to all resources recursively below the - * preceding path (e.g. http://www.oracle.com/a/b/c/d/e.html matches this + * preceding path (e.g. http://www.example.com/a/b/c/d/e.html matches this * example). * * @@ -267,9 +267,9 @@ public String getActions() { *

  • if this's url scheme is not equal to p's url scheme return false
  • *
  • if the scheme specific part of this's url is '*' return true
  • *
  • if the set of hosts defined by p's url hostrange is not a subset of - * this's url hostrange then return false. For example, "*.foo.oracle.com" - * is a subset of "*.oracle.com". "foo.bar.oracle.com" is not - * a subset of "*.foo.oracle.com"
  • + * this's url hostrange then return false. For example, "*.foo.example.com" + * is a subset of "*.example.com". "foo.bar.example.com" is not + * a subset of "*.foo.example.com"
  • *
  • if the portrange defined by p's url is not a subset of the * portrange defined by this's url then return false. *
  • if the path or paths specified by p's url are contained in the diff --git a/src/java.base/share/classes/java/net/package-info.java b/src/java.base/share/classes/java/net/package-info.java index 1f305be9833..b221c6bf2f7 100644 --- a/src/java.base/share/classes/java/net/package-info.java +++ b/src/java.base/share/classes/java/net/package-info.java @@ -131,7 +131,7 @@ * InputStream. *

    Here is an example:

    *
    - * URI uri = new URI("http://java.sun.com/");
    + * URI uri = new URI("http://www.example.com/");
      * URL url = uri.toURL();
      * InputStream in = url.openStream();
      * 
    diff --git a/src/java.base/share/classes/java/nio/file/Files.java b/src/java.base/share/classes/java/nio/file/Files.java index ed10a082087..baca08e412c 100644 --- a/src/java.base/share/classes/java/nio/file/Files.java +++ b/src/java.base/share/classes/java/nio/file/Files.java @@ -3067,7 +3067,7 @@ public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) * it to a file: *
          *     Path path = ...
    -     *     URI u = URI.create("http://java.sun.com/");
    +     *     URI u = URI.create("http://www.example.com/");
          *     try (InputStream in = u.toURL().openStream()) {
          *         Files.copy(in, path);
          *     }
    diff --git a/src/java.base/share/classes/java/security/CodeSource.java b/src/java.base/share/classes/java/security/CodeSource.java
    index a1f98eeb557..670c2a14ea4 100644
    --- a/src/java.base/share/classes/java/security/CodeSource.java
    +++ b/src/java.base/share/classes/java/security/CodeSource.java
    @@ -309,13 +309,13 @@ public final CodeSigner[] getCodeSigners() {
          * 

    * For example, the codesource objects with the following locations * and null certificates all imply - * the codesource with the location "http://java.sun.com/classes/foo.jar" + * the codesource with the location "http://www.example.com/classes/foo.jar" * and null certificates: *

          *     http:
    -     *     http://*.sun.com/classes/*
    -     *     http://java.sun.com/classes/-
    -     *     http://java.sun.com/classes/foo.jar
    +     *     http://*.example.com/classes/*
    +     *     http://www.example.com/classes/-
    +     *     http://www.example.com/classes/foo.jar
          * 
    * * Note that if this CodeSource has a null location and a null diff --git a/src/java.base/share/classes/java/security/KeyStore.java b/src/java.base/share/classes/java/security/KeyStore.java index 6fc72821117..acb34db2383 100644 --- a/src/java.base/share/classes/java/security/KeyStore.java +++ b/src/java.base/share/classes/java/security/KeyStore.java @@ -1813,8 +1813,8 @@ private static final KeyStore getInstance(File file, char[] password, } } - throw new KeyStoreException("Unrecognized keystore format: " + - keystore); + throw new KeyStoreException("This keystore does not support probing " + + "and must be loaded with a specified type"); } /** diff --git a/src/java.base/share/classes/sun/security/ssl/SSLCipher.java b/src/java.base/share/classes/sun/security/ssl/SSLCipher.java index 267670e4a34..34883b094b0 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLCipher.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLCipher.java @@ -530,22 +530,22 @@ SSLWriteCipher createWriteCipher(Authenticator authenticator, ProtocolVersion protocolVersion, SecretKey key, IvParameterSpec iv, SecureRandom random) throws GeneralSecurityException { - if (readCipherGenerators.length == 0) { + if (writeCipherGenerators.length == 0) { return null; } - WriteCipherGenerator rcg = null; + WriteCipherGenerator wcg = null; for (Map.Entry me : writeCipherGenerators) { for (ProtocolVersion pv : me.getValue()) { if (protocolVersion == pv) { - rcg = me.getKey(); + wcg = me.getKey(); } } } - if (rcg != null) { - return rcg.createCipher(this, authenticator, + if (wcg != null) { + return wcg.createCipher(this, authenticator, protocolVersion, transformation, key, iv, random); } return null; diff --git a/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/src/java.base/share/classes/sun/security/tools/keytool/Main.java index b8137b63d24..aebcd5f25a1 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1328,28 +1328,39 @@ && isKeyStoreRelated(command)) { if (f.exists()) { // Probe for real type. A JKS can be loaded as PKCS12 because // DualFormat support, vice versa. - keyStore = KeyStore.getInstance(f, pass); - String realType = keyStore.getType(); - if (realType.equalsIgnoreCase("JKS") - || realType.equalsIgnoreCase("JCEKS")) { - boolean allCerts = true; - for (String a : Collections.list(keyStore.aliases())) { - if (!keyStore.entryInstanceOf( - a, TrustedCertificateEntry.class)) { - allCerts = false; - break; + String realType = storetype; + try { + keyStore = KeyStore.getInstance(f, pass); + realType = keyStore.getType(); + if (realType.equalsIgnoreCase("JKS") + || realType.equalsIgnoreCase("JCEKS")) { + boolean allCerts = true; + for (String a : Collections.list(keyStore.aliases())) { + if (!keyStore.entryInstanceOf( + a, TrustedCertificateEntry.class)) { + allCerts = false; + break; + } + } + // Don't warn for "cacerts" style keystore. + if (!allCerts) { + weakWarnings.add(String.format( + rb.getString("jks.storetype.warning"), + realType, ksfname)); } } - // Don't warn for "cacerts" style keystore. - if (!allCerts) { - weakWarnings.add(String.format( - rb.getString("jks.storetype.warning"), - realType, ksfname)); - } + } catch (KeyStoreException e) { + // Probing not supported, therefore cannot be JKS or JCEKS. + // Skip the legacy type warning at all. } if (inplaceImport) { - String realSourceStoreType = KeyStore.getInstance( - new File(inplaceBackupName), srcstorePass).getType(); + String realSourceStoreType = srcstoretype; + try { + realSourceStoreType = KeyStore.getInstance( + new File(inplaceBackupName), srcstorePass).getType(); + } catch (KeyStoreException e) { + // Probing not supported. Assuming srcstoretype. + } String format = realType.equalsIgnoreCase(realSourceStoreType) ? rb.getString("backup.keystore.warning") : diff --git a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/AttributeSet.java b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/AttributeSet.java index cd5ef47e268..5da16bd3bfc 100644 --- a/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/AttributeSet.java +++ b/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/AttributeSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -95,7 +95,7 @@ public void parseContents(Parser parser) { parser.reportError(Constants.ERROR, err); } _name = parser.getQNameIgnoreDefaultNs(name); - if ((_name == null) || (_name.equals(EMPTYSTRING))) { + if ((_name == null) || (_name.getStringRep().equals(EMPTYSTRING))) { ErrorMsg msg = new ErrorMsg(ErrorMsg.UNNAMED_ATTRIBSET_ERR, this); parser.reportError(Constants.ERROR, msg); } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index f93cf8e9834..9c4b1f01829 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -1778,9 +1778,6 @@ Type condType(List positions, List condTypes) { if (condTypes.isEmpty()) { return syms.objectType; //TODO: how to handle? } - if (condTypes.size() == 1) { - return condTypes.head; - } Type first = condTypes.head; // If same type, that is the result if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t))) @@ -2906,6 +2903,15 @@ public void scan(JCTree tree) { } super.scan(tree); } + + @Override + public void visitClassDef(JCClassDecl that) { + // or class declaration trees! + } + + public void visitLambda(JCLambda that) { + // or lambda expressions! + } }.scan(tree); } diff --git a/src/jdk.crypto.ec/share/native/libsunec/impl/ec.c b/src/jdk.crypto.ec/share/native/libsunec/impl/ec.c index c439eb702bd..3586724eec0 100644 --- a/src/jdk.crypto.ec/share/native/libsunec/impl/ec.c +++ b/src/jdk.crypto.ec/share/native/libsunec/impl/ec.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. * Use is subject to license terms. * * This library is free software; you can redistribute it and/or @@ -43,11 +43,11 @@ #include #ifndef _KERNEL +#include #include #include #ifndef _WIN32 -#include #include #endif /* _WIN32 */ @@ -109,16 +109,16 @@ ec_points_mul(const ECParams *params, const mp_int *k1, const mp_int *k2, printf("\n"); if (k1 != NULL) { - mp_tohex(k1, mpstr); + mp_tohex((mp_int*)k1, mpstr); printf("ec_points_mul: scalar k1: %s\n", mpstr); - mp_todecimal(k1, mpstr); + mp_todecimal((mp_int*)k1, mpstr); printf("ec_points_mul: scalar k1: %s (dec)\n", mpstr); } if (k2 != NULL) { - mp_tohex(k2, mpstr); + mp_tohex((mp_int*)k2, mpstr); printf("ec_points_mul: scalar k2: %s\n", mpstr); - mp_todecimal(k2, mpstr); + mp_todecimal((mp_int*)k2, mpstr); printf("ec_points_mul: scalar k2: %s (dec)\n", mpstr); } diff --git a/src/jdk.crypto.ec/share/native/libsunec/impl/ecdecode.c b/src/jdk.crypto.ec/share/native/libsunec/impl/ecdecode.c index acc10d9ccbc..7667ac32152 100644 --- a/src/jdk.crypto.ec/share/native/libsunec/impl/ecdecode.c +++ b/src/jdk.crypto.ec/share/native/libsunec/impl/ecdecode.c @@ -49,6 +49,7 @@ #ifdef _KERNEL #include #else +#include #include #endif #include "ec.h" diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java index cb27890ee33..56e6c83aa3e 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java @@ -223,7 +223,7 @@ protected void addDescription(ModuleElement mdle, Content dlTree, SearchIndexIte String moduleName = utils.getFullyQualifiedName(mdle); Content link = getModuleLink(mdle, new StringContent(moduleName)); si.setLabel(moduleName); - si.setCategory(resources.getText("doclet.Modules")); + si.setCategory(SearchIndexItem.Category.MODULES); Content dt = HtmlTree.DT(link); dt.addContent(" - "); dt.addContent(contents.module_); @@ -247,7 +247,7 @@ protected void addDescription(PackageElement pkg, Content dlTree, SearchIndexIte si.setContainingModule(utils.getFullyQualifiedName(utils.containingModule(pkg))); } si.setLabel(utils.getPackageName(pkg)); - si.setCategory(resources.getText("doclet.Packages")); + si.setCategory(SearchIndexItem.Category.PACKAGES); Content dt = HtmlTree.DT(link); dt.addContent(" - "); dt.addContent(contents.package_); @@ -270,7 +270,7 @@ protected void addDescription(TypeElement typeElement, Content dlTree, SearchInd LinkInfoImpl.Kind.INDEX, typeElement).strong(true)); si.setContainingPackage(utils.getPackageName(utils.containingPackage(typeElement))); si.setLabel(utils.getSimpleName(typeElement)); - si.setCategory(resources.getText("doclet.Types")); + si.setCategory(SearchIndexItem.Category.TYPES); Content dt = HtmlTree.DT(link); dt.addContent(" - "); addClassInfo(typeElement, dt); @@ -318,7 +318,7 @@ protected void addDescription(Element member, Content dlTree, SearchIndexItem si } else { si.setLabel(name); } - si.setCategory(resources.getText("doclet.Members")); + si.setCategory(SearchIndexItem.Category.MEMBERS); Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink, getDocLink(LinkInfoImpl.Kind.INDEX, member, name)); Content dt = HtmlTree.DT(span); @@ -439,7 +439,7 @@ protected void createSearchIndexFiles() throws DocFileIOException { } if (!configuration.packages.isEmpty()) { SearchIndexItem si = new SearchIndexItem(); - si.setCategory(resources.getText("doclet.Packages")); + si.setCategory(SearchIndexItem.Category.PACKAGES); si.setLabel(resources.getText("doclet.All_Packages")); si.setUrl(DocPaths.ALLPACKAGES_INDEX.getPath()); configuration.packageSearchIndex.add(si); @@ -447,7 +447,7 @@ protected void createSearchIndexFiles() throws DocFileIOException { createSearchIndexFile(DocPaths.PACKAGE_SEARCH_INDEX_JSON, DocPaths.PACKAGE_SEARCH_INDEX_ZIP, DocPaths.PACKAGE_SEARCH_INDEX_JS, configuration.packageSearchIndex, "packageSearchIndex"); SearchIndexItem si = new SearchIndexItem(); - si.setCategory(resources.getText("doclet.Types")); + si.setCategory(SearchIndexItem.Category.TYPES); si.setLabel(resources.getText("doclet.All_Classes")); si.setUrl(DocPaths.ALLCLASSES_INDEX.getPath()); configuration.typeSearchIndex.add(si); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java index e6df1f6059a..16f07e67229 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/DocFilesHandlerImpl.java @@ -169,7 +169,7 @@ private boolean handleHtmlFile(DocFile srcfile, DocPath dstPath) throws DocFileI DocPath dfilePath = dstPath.resolve(srcfile.getName()); HtmlDocletWriter docletWriter = new DocFileWriter(configuration, dfilePath, element); - configuration.messages.notice("doclet.Generating_0", docletWriter.filename); + configuration.messages.notice("doclet.Generating_0", docletWriter.filename.getPath()); String title = getWindowTitle(docletWriter, dfElement).trim(); HtmlTree htmlContent = docletWriter.getBody(true, title); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java index 508cb4e01cb..f4e37b96e9f 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java @@ -139,19 +139,6 @@ protected void generateOtherFiles(DocletEnvironment docEnv, ClassTree classtree) if (configuration.createtree) { TreeWriter.generate(configuration, classtree); } - if (configuration.createindex) { - configuration.buildSearchTagIndex(); - if (configuration.splitindex) { - SplitIndexWriter.generate(configuration, indexbuilder); - } else { - SingleIndexWriter.generate(configuration, indexbuilder); - } - AllClassesIndexWriter.generate(configuration, - new IndexBuilder(configuration, nodeprecated, true)); - if (!configuration.packages.isEmpty()) { - AllPackagesIndexWriter.generate(configuration); - } - } if (!(configuration.nodeprecatedlist || nodeprecated)) { DeprecatedListWriter.generate(configuration); @@ -172,6 +159,20 @@ protected void generateOtherFiles(DocletEnvironment docEnv, ClassTree classtree) } } + if (configuration.createindex) { + configuration.buildSearchTagIndex(); + if (configuration.splitindex) { + SplitIndexWriter.generate(configuration, indexbuilder); + } else { + SingleIndexWriter.generate(configuration, indexbuilder); + } + AllClassesIndexWriter.generate(configuration, + new IndexBuilder(configuration, nodeprecated, true)); + if (!configuration.packages.isEmpty()) { + AllPackagesIndexWriter.generate(configuration); + } + } + if (!configuration.frames) { if (configuration.createoverview) { IndexRedirectWriter.generate(configuration, DocPaths.OVERVIEW_SUMMARY, DocPaths.INDEX); diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SearchIndexItem.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SearchIndexItem.java index 5ffe917121c..cafbc015b24 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SearchIndexItem.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SearchIndexItem.java @@ -35,9 +35,17 @@ */ public class SearchIndexItem { + enum Category { + MODULES, + PACKAGES, + TYPES, + MEMBERS, + SEARCH_TAGS + } + + private Category category; private String label = ""; private String url = ""; - private String category = ""; private String containingModule = ""; private String containingPackage = ""; private String containingClass = ""; @@ -72,7 +80,7 @@ public void setContainingClass(String c) { containingClass = c; } - public void setCategory(String c) { + public void setCategory(Category c) { category = c; } @@ -94,11 +102,13 @@ public String getDescription() { public String toString() { StringBuilder item = new StringBuilder(""); - if (category.equals("Modules")) { + switch (category) { + case MODULES: item.append("{") .append("\"l\":\"").append(label).append("\"") .append("}"); - } else if (category.equals("Packages")) { + break; + case PACKAGES: item.append("{"); if (!containingModule.isEmpty()) { item.append("\"m\":\"").append(containingModule).append("\","); @@ -108,7 +118,8 @@ public String toString() { item.append(",\"url\":\"").append(url).append("\""); } item.append("}"); - } else if (category.equals("Types")) { + break; + case TYPES: item.append("{"); if (!containingPackage.equals("")) { item.append("\"p\":\"").append(containingPackage).append("\","); @@ -118,7 +129,8 @@ public String toString() { item.append(",\"url\":\"").append(url).append("\""); } item.append("}"); - } else if (category.equals("Members")) { + break; + case MEMBERS: item.append("{") .append("\"p\":\"").append(containingPackage).append("\",") .append("\"c\":\"").append(containingClass).append("\",") @@ -127,7 +139,8 @@ public String toString() { item.append(",\"url\":\"").append(url).append("\""); } item.append("}"); - } else { + break; + case SEARCH_TAGS: item.append("{") .append("\"l\":\"").append(label).append("\",") .append("\"h\":\"").append(holder).append("\","); @@ -136,6 +149,9 @@ public String toString() { } item.append("\"u\":\"").append(url).append("\"") .append("}"); + break; + default: + throw new IllegalStateException("category not set"); } return item.toString(); } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java index bc58d6f0ab4..002737d2056 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/TagletWriterImpl.java @@ -41,11 +41,11 @@ import jdk.javadoc.internal.doclets.formats.html.markup.ContentBuilder; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTree; -import jdk.javadoc.internal.doclets.formats.html.markup.Links; import jdk.javadoc.internal.doclets.formats.html.markup.RawHtml; import jdk.javadoc.internal.doclets.formats.html.markup.StringContent; import jdk.javadoc.internal.doclets.toolkit.BaseConfiguration; import jdk.javadoc.internal.doclets.toolkit.Content; +import jdk.javadoc.internal.doclets.toolkit.DocletElement; import jdk.javadoc.internal.doclets.toolkit.Resources; import jdk.javadoc.internal.doclets.toolkit.builders.SerializedFormBuilder; import jdk.javadoc.internal.doclets.toolkit.taglets.TagletWriter; @@ -421,48 +421,43 @@ private Content createAnchorAndSearchIndex(Element element, String tagText, Stri SearchIndexItem si = new SearchIndexItem(); si.setLabel(tagText); si.setDescription(desc); + si.setUrl(htmlWriter.path.getPath() + "#" + anchorName); DocPaths docPaths = configuration.docPaths; new SimpleElementVisitor9() { - @Override - public Void visitModule(ModuleElement e, Void p) { - si.setUrl(docPaths.moduleSummary(e).getPath() + "#" + anchorName); - si.setHolder(utils.getFullyQualifiedName(element)); - return null; - } - - @Override - public Void visitPackage(PackageElement e, Void p) { - si.setUrl(docPaths.forPackage(e).getPath() - + "/" + DocPaths.PACKAGE_SUMMARY.getPath() + "#" + anchorName); - si.setHolder(utils.getSimpleName(element)); - return null; - } - - @Override - public Void visitType(TypeElement e, Void p) { - si.setUrl(docPaths.forClass(e).getPath() + "#" + anchorName); - si.setHolder(utils.getFullyQualifiedName(e)); - return null; - } - @Override public Void visitVariable(VariableElement e, Void p) { TypeElement te = utils.getEnclosingTypeElement(e); - si.setUrl(docPaths.forClass(te).getPath() + "#" + anchorName); si.setHolder(utils.getFullyQualifiedName(e) + "." + utils.getSimpleName(e)); return null; } + @Override + public Void visitUnknown(Element e, Void p) { + if (e instanceof DocletElement) { + DocletElement de = (DocletElement) e; + switch (de.getSubKind()) { + case OVERVIEW: + si.setHolder(resources.getText("doclet.Overview")); + break; + case DOCFILE: + si.setHolder(de.getPackageElement().toString()); + break; + default: + throw new IllegalStateException(); + } + return null; + } else { + return super.visitUnknown(e, p); + } + } + @Override protected Void defaultAction(Element e, Void p) { - TypeElement te = utils.getEnclosingTypeElement(e); - si.setUrl(docPaths.forClass(te).getPath() + "#" + anchorName); si.setHolder(utils.getFullyQualifiedName(e)); return null; } }.visit(element); - Contents contents = configuration.getContents(); - si.setCategory(contents.getContent("doclet.SearchTags").toString()); + si.setCategory(SearchIndexItem.Category.SEARCH_TAGS); configuration.tagSearchIndex.add(si); } } diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties index edc4662ad92..19afdd43f66 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets.properties @@ -211,9 +211,6 @@ doclet.Modifier=Modifier doclet.Type=Type doclet.Modifier_and_Type=Modifier and Type doclet.Implementation=Implementation(s): -doclet.Types=Types -doclet.Members=Members -doclet.SearchTags=SearchTags doclet.search=SEARCH: doclet.Field=Field doclet.Property=Property @@ -230,6 +227,7 @@ doclet.linkMismatch_PackagedLinkedtoModule=The code being documented uses packag but the packages defined in {0} are in named modules. doclet.linkMismatch_ModuleLinkedtoPackage=The code being documented uses modules but the packages defined \ in {0} are in the unnamed module. +doclet.urlRedirected=URL {0} was redirected to {1} -- Update the command-line options to suppress this warning. #Documentation for Enums doclet.enum_values_doc.fullbody=\ diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_ja.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_ja.properties index d5a537bc733..b3e67ae1ef3 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_ja.properties +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_ja.properties @@ -202,9 +202,6 @@ doclet.Modifier=\u4FEE\u98FE\u5B50 doclet.Type=\u30BF\u30A4\u30D7 doclet.Modifier_and_Type=\u4FEE\u98FE\u5B50\u3068\u30BF\u30A4\u30D7 doclet.Implementation=\u5B9F\u88C5: -doclet.Types=\u30BF\u30A4\u30D7 -doclet.Members=\u30E1\u30F3\u30D0\u30FC -doclet.SearchTags=SearchTags doclet.search=SEARCH: doclet.Field=\u30D5\u30A3\u30FC\u30EB\u30C9 doclet.Property=\u30D7\u30ED\u30D1\u30C6\u30A3 diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_zh_CN.properties b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_zh_CN.properties index 58ecb5a1928..362e45ac8bb 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_zh_CN.properties +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/doclets_zh_CN.properties @@ -202,9 +202,6 @@ doclet.Modifier=\u9650\u5B9A\u7B26 doclet.Type=\u7C7B\u578B doclet.Modifier_and_Type=\u4FEE\u9970\u7B26\u548C\u7C7B\u578B doclet.Implementation=\u5B9E\u73B0: -doclet.Types=\u7C7B\u578B -doclet.Members=\u6210\u5458 -doclet.SearchTags=\u641C\u7D22\u6807\u8BB0 doclet.search=SEARCH: doclet.Field=\u5B57\u6BB5 doclet.Property=\u5C5E\u6027 diff --git a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java index 520bb9488dd..0a05f32b66a 100644 --- a/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java +++ b/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Extern.java @@ -25,8 +25,15 @@ package jdk.javadoc.internal.doclets.toolkit.util; -import java.io.*; -import java.net.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; @@ -35,6 +42,7 @@ import javax.lang.model.element.ModuleElement; import javax.lang.model.element.PackageElement; import javax.tools.Diagnostic; +import javax.tools.Diagnostic.Kind; import javax.tools.DocumentationTool; import jdk.javadoc.doclet.Reporter; @@ -85,7 +93,7 @@ public class Extern { private class Item { /** - * Element name, found in the "element-list" file in the {@link path}. + * Element name, found in the "element-list" file in the {@link #path}. */ final String elementName; @@ -157,7 +165,7 @@ public boolean isExternal(Element element) { */ public boolean isModule(String elementName) { Item elem = moduleItems.get(elementName); - return (elem == null) ? false : true; + return elem != null; } /** @@ -245,14 +253,6 @@ private boolean link(String url, String elemlisturl, Reporter reporter, boolean } } - private URL toURL(String url) throws Fault { - try { - return new URL(url); - } catch (MalformedURLException e) { - throw new Fault(resources.getText("doclet.MalformedURL", url), e); - } - } - private class Fault extends Exception { private static final long serialVersionUID = 0; @@ -296,7 +296,9 @@ private String adjustEndFileSeparator(String url) { private void readElementListFromURL(String urlpath, URL elemlisturlpath) throws Fault { try { URL link = elemlisturlpath.toURI().resolve(DocPaths.ELEMENT_LIST.getPath()).toURL(); - readElementList(link.openStream(), urlpath, false); + try (InputStream in = open(link)) { + readElementList(in, urlpath, false); + } } catch (URISyntaxException | MalformedURLException exc) { throw new Fault(resources.getText("doclet.MalformedURL", elemlisturlpath.toString()), exc); } catch (IOException exc) { @@ -313,7 +315,9 @@ private void readElementListFromURL(String urlpath, URL elemlisturlpath) throws private void readAlternateURL(String urlpath, URL elemlisturlpath) throws Fault { try { URL link = elemlisturlpath.toURI().resolve(DocPaths.PACKAGE_LIST.getPath()).toURL(); - readElementList(link.openStream(), urlpath, false); + try (InputStream in = open(link)) { + readElementList(in, urlpath, false); + } } catch (URISyntaxException | MalformedURLException exc) { throw new Fault(resources.getText("doclet.MalformedURL", elemlisturlpath.toString()), exc); } catch (IOException exc) { @@ -377,9 +381,9 @@ private void readElementList(DocFile file, String path) throws Fault, DocFileIOE private void readElementList(InputStream input, String path, boolean relative) throws Fault, IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) { - String elemname = null; + String elemname; + DocPath elempath; String moduleName = null; - DocPath elempath = null; DocPath basePath = DocPath.create(path); while ((elemname = in.readLine()) != null) { if (elemname.length() > 0) { @@ -406,9 +410,25 @@ private void readElementList(InputStream input, String path, boolean relative) } } + private void checkLinkCompatibility(String packageName, String moduleName, String path) throws Fault { + PackageElement pe = utils.elementUtils.getPackageElement(packageName); + if (pe != null) { + ModuleElement me = (ModuleElement)pe.getEnclosingElement(); + if (me == null || me.isUnnamed()) { + if (moduleName != null) { + throw new Fault(resources.getText("doclet.linkMismatch_PackagedLinkedtoModule", + path), null); + } + } else if (moduleName == null) { + throw new Fault(resources.getText("doclet.linkMismatch_ModuleLinkedtoPackage", + path), null); + } + } + } + public boolean isUrl (String urlCandidate) { try { - URL ignore = new URL(urlCandidate); + new URL(urlCandidate); //No exception was thrown, so this must really be a URL. return true; } catch (MalformedURLException e) { @@ -417,17 +437,70 @@ public boolean isUrl (String urlCandidate) { } } - private void checkLinkCompatibility(String packageName, String moduleName, String path) throws Fault { - PackageElement pe = configuration.utils.elementUtils.getPackageElement(packageName); - if (pe != null) { - ModuleElement me = (ModuleElement)pe.getEnclosingElement(); - if (me == null || me.isUnnamed()) { - if (moduleName != null) - throw new Fault(resources.getText("doclet.linkMismatch_PackagedLinkedtoModule", - path), null); - } else if (moduleName == null) - throw new Fault(resources.getText("doclet.linkMismatch_ModuleLinkedtoPackage", - path), null); + private URL toURL(String url) throws Fault { + try { + return new URL(url); + } catch (MalformedURLException e) { + throw new Fault(resources.getText("doclet.MalformedURL", url), e); } } + + /** + * Open a stream to a URL, following a limited number of redirects + * if necessary. + * + * @param url the URL + * @return the stream + * @throws IOException if an error occurred accessing the URL + */ + private InputStream open(URL url) throws IOException { + URLConnection conn = url.openConnection(); + + boolean redir; + int redirects = 0; + InputStream in; + + do { + // Open the input stream before getting headers, + // because getHeaderField() et al swallow IOExceptions. + in = conn.getInputStream(); + redir = false; + + if (conn instanceof HttpURLConnection) { + HttpURLConnection http = (HttpURLConnection)conn; + int stat = http.getResponseCode(); + // See: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection + switch (stat) { + case 300: // Multiple Choices + case 301: // Moved Permanently + case 302: // Found (previously Moved Temporarily) + case 303: // See Other + case 307: // Temporary Redirect + case 308: // Permanent Redirect + URL base = http.getURL(); + String loc = http.getHeaderField("Location"); + URL target = null; + if (loc != null) { + target = new URL(base, loc); + } + http.disconnect(); + if (target == null || redirects >= 5) { + throw new IOException("illegal URL redirect"); + } + redir = true; + conn = target.openConnection(); + redirects++; + } + } + } while (redir); + + if (!url.equals(conn.getURL())) { + configuration.getReporter().print(Kind.WARNING, + resources.getText("doclet.urlRedirected", url, conn.getURL())); + } + + return in; + } } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java index 3d04758c01c..c2945f3ae9d 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/EventInstrumentation.java @@ -435,6 +435,10 @@ private void makeInstrumented() { // MyEvent#shouldCommit() updateMethod(METHOD_EVENT_SHOULD_COMMIT, methodVisitor -> { Label fail = new Label(); + if (guardHandlerReference) { + getEventHandler(methodVisitor); + methodVisitor.visitJumpInsn(Opcodes.IFNULL, fail); + } // if (!eventHandler.shouldCommit(duration) goto fail; getEventHandler(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java index eacb24243e8..9a72179e080 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/SecuritySupport.java @@ -79,6 +79,14 @@ public final class SecuritySupport { static final SafePath USER_HOME = getPathInProperty("user.home", null); static final SafePath JAVA_IO_TMPDIR = getPathInProperty("java.io.tmpdir", null); + static { + // ensure module java.base can read module jdk.jfr as early as possible + addReadEdge(Object.class); + addHandlerExport(Object.class); + addEventsExport(Object.class); + addInstrumentExport(Object.class); + } + final static class SecureRecorderListener implements FlightRecorderListener { private final AccessControlContext context; @@ -262,6 +270,18 @@ static void addHandlerExport(Class clazz) { Modules.addExports(JFR_MODULE, Utils.HANDLERS_PACKAGE_NAME, clazz.getModule()); } + static void addEventsExport(Class clazz) { + Modules.addExports(JFR_MODULE, Utils.EVENTS_PACKAGE_NAME, clazz.getModule()); + } + + static void addInstrumentExport(Class clazz) { + Modules.addExports(JFR_MODULE, Utils.INSTRUMENT_PACKAGE_NAME, clazz.getModule()); + } + + static void addReadEdge(Class clazz) { + Modules.addReads(clazz.getModule(), JFR_MODULE); + } + public static void registerEvent(Class eventClass) { doPrivileged(() -> MetadataRepository.getInstance().register(eventClass), new FlightRecorderPermission(Utils.REGISTER_EVENT)); } diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/JDKEvents.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/JDKEvents.java index e0859c588fb..593b164e346 100644 --- a/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/JDKEvents.java +++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/instrument/JDKEvents.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.List; -import jdk.internal.module.Modules; import jdk.jfr.Event; import jdk.jfr.FlightRecorder; import jdk.jfr.events.ActiveRecordingEvent; @@ -99,12 +98,6 @@ public final class JDKEvents { public synchronized static void initialize() { try { if (initializationTriggered == false) { - Module jdkJfrModule = Event.class.getModule(); - Module javaBaseModule = Object.class.getModule(); - Modules.addReads(javaBaseModule, jdkJfrModule); - Modules.addExports(jdkJfrModule, Utils.EVENTS_PACKAGE_NAME, javaBaseModule); - Modules.addExports(jdkJfrModule, Utils.INSTRUMENT_PACKAGE_NAME, javaBaseModule); - Modules.addExports(jdkJfrModule, Utils.HANDLERS_PACKAGE_NAME, javaBaseModule); for (Class mirrorEventClass : mirrorEventClasses) { SecuritySupport.registerMirror(((Class)mirrorEventClass)); } diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index 52325983c42..a29da510423 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -61,8 +61,6 @@ compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java 8190680 generic-all compiler/runtime/Test8168712.java 8211769,8211771 generic-ppc64,generic-ppc64le,linux-s390x -compiler/intrinsics/mathexact/MulExactLConstantTest.java 8214189 windows-all - ############################################################################# # :hotspot_gc diff --git a/test/hotspot/jtreg/compiler/arguments/TestScavengeRootsInCode.java b/test/hotspot/jtreg/compiler/arguments/TestScavengeRootsInCode.java index 69865ddabbd..224ce752135 100644 --- a/test/hotspot/jtreg/compiler/arguments/TestScavengeRootsInCode.java +++ b/test/hotspot/jtreg/compiler/arguments/TestScavengeRootsInCode.java @@ -25,7 +25,7 @@ * @test * @bug 8214025 * @summary Test compilation with non-default value for ScavengeRootsInCode. - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xcomp -XX:-TieredCompilation + * @run main/othervm -XX:+UnlockDiagnosticVMOptions -Xcomp -XX:-TieredCompilation * -XX:ScavengeRootsInCode=1 compiler.arguments.TestScavengeRootsInCode */ diff --git a/test/hotspot/jtreg/compiler/integerArithmetic/MultiplyByConstantLongMax.java b/test/hotspot/jtreg/compiler/integerArithmetic/MultiplyByConstantLongMax.java new file mode 100644 index 00000000000..f586f90c1a0 --- /dev/null +++ b/test/hotspot/jtreg/compiler/integerArithmetic/MultiplyByConstantLongMax.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2018, Red Hat, Inc. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact 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 8214189 + * @summary test/hotspot/jtreg/compiler/intrinsics/mathexact/MulExactLConstantTest.java fails on Windows x64 when run with -XX:-TieredCompilation + * + * @run main/othervm -XX:-TieredCompilation -XX:-BackgroundCompilation -XX:-UseOnStackReplacement MultiplyByConstantLongMax + * + */ + +public class MultiplyByConstantLongMax { + public static void main(String[] args) { + for (int i = 0; i < 20_000; i++) { + if (test(1) != Long.MAX_VALUE) { + throw new RuntimeException("incorrect result"); + } + } + } + + private static long test(long v) { + return v * Long.MAX_VALUE; + } +} diff --git a/test/hotspot/jtreg/runtime/NMT/MallocStressTest.java b/test/hotspot/jtreg/runtime/NMT/MallocStressTest.java index 4305c2864e4..730dcea3e3d 100644 --- a/test/hotspot/jtreg/runtime/NMT/MallocStressTest.java +++ b/test/hotspot/jtreg/runtime/NMT/MallocStressTest.java @@ -186,13 +186,19 @@ public void run() { if (size == 0) size = 1; long addr = MallocStressTest.whiteBox.NMTMallocWithPseudoStack(size, r); if (addr != 0) { - MallocMemory mem = new MallocMemory(addr, size); - synchronized(MallocStressTest.mallocd_memory) { - MallocStressTest.mallocd_memory.add(mem); - MallocStressTest.mallocd_total += size; + try { + MallocMemory mem = new MallocMemory(addr, size); + synchronized(MallocStressTest.mallocd_memory) { + MallocStressTest.mallocd_memory.add(mem); + MallocStressTest.mallocd_total += size; + } + } catch (OutOfMemoryError e) { + // Don't include this malloc memory because it didn't + // get recorded in mallocd_memory list. + MallocStressTest.whiteBox.NMTFree(addr); + break; } } else { - System.out.println("Out of malloc memory"); break; } } diff --git a/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClasses.java b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClasses.java index bd677a0fa4e..7f61f757203 100644 --- a/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClasses.java +++ b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClasses.java @@ -41,8 +41,13 @@ public class ReplaceCriticalClasses { public static void main(String args[]) throws Throwable { + ReplaceCriticalClasses rcc = new ReplaceCriticalClasses(); + rcc.process(args); + } + + public void process(String args[]) throws Throwable { if (args.length == 0) { - launchChildProcesses(); + launchChildProcesses(getTests()); } else if (args.length == 3 && args[0].equals("child")) { Class klass = Class.forName(args[2].replace("/", ".")); if (args[1].equals("-shared")) { @@ -58,7 +63,7 @@ public static void main(String args[]) throws Throwable { } } - static void launchChildProcesses() throws Throwable { + public String[] getTests() { String tests[] = { // CDS should be disabled -- these critical classes will be replaced // because JvmtiExport::early_class_hook_env() is true. @@ -74,18 +79,25 @@ static void launchChildProcesses() throws Throwable { "java/lang/Cloneable", "java/io/Serializable", - // Try to replace classes that are used by the archived subgraph graphs. - "-subgraph java/util/ArrayList", - "-subgraph java/lang/module/ResolvedModule", + /* Try to replace classes that are used by the archived subgraph graphs. + The following test cases are in ReplaceCriticalClassesForSubgraphs.java. + "-early -notshared -subgraph java/lang/module/ResolvedModule jdk.internal.module.ArchivedModuleGraph", + "-early -notshared -subgraph java/lang/Long java.lang.Long$LongCache", + "-subgraph java/lang/Long java.lang.Long$LongCache", + */ - // Replace classes that are loaded after JVMTI_PHASE_PRIMORDIAL. It's OK to replace such + // Replace classes that are loaded after JVMTI_PHASE_PRIMORDIAL. It's OK to replace + // such // classes even when CDS is enabled. Nothing bad should happen. "-notshared jdk/internal/vm/PostVMInitHook", "-notshared java/util/Locale", "-notshared sun/util/locale/BaseLocale", "-notshared java/lang/Readable", }; + return tests; + } + static void launchChildProcesses(String tests[]) throws Throwable { int n = 0; for (String s : tests) { System.out.println("Test case[" + (n++) + "] = \"" + s + "\""); @@ -96,9 +108,10 @@ static void launchChildProcesses() throws Throwable { static void launchChild(String args[]) throws Throwable { if (args.length < 1) { - throw new RuntimeException("Invalid test case. Should be <-early> <-subgraph> <-notshared> klassName"); + throw new RuntimeException("Invalid test case. Should be <-early> <-subgraph> <-notshared> klassName subgraphKlass"); } String klassName = null; + String subgraphKlass = null; String early = ""; boolean subgraph = false; String shared = "-shared"; @@ -112,11 +125,19 @@ static void launchChild(String args[]) throws Throwable { } else if (opt.equals("-notshared")) { shared = opt; } else { + if (!subgraph) { throw new RuntimeException("Unknown option: " + opt); + } } } - klassName = args[args.length-1]; + if (subgraph) { + klassName = args[args.length-2]; + subgraphKlass = args[args.length-1]; + } else { + klassName = args[args.length-1]; + } Class.forName(klassName.replace("/", ".")); // make sure it's a valid class + final String subgraphInit = "initialize_from_archived_subgraph " + subgraphKlass; // We will pass an option like "-agentlib:SimpleClassFileLoadHook=java/util/Locale,XXX,XXX". // The SimpleClassFileLoadHook agent would attempt to hook the java/util/Locale class @@ -142,8 +163,7 @@ static void launchChild(String args[]) throws Throwable { "-Xbootclasspath/a:" + ClassFileInstaller.getJarPath("whitebox.jar")); if (subgraph) { - opts.addSuffix("-Xlog:cds+heap", - "-Xlog:class+load"); + opts.addSuffix("-Xlog:cds,cds+heap"); } opts.addSuffix("ReplaceCriticalClasses", @@ -152,11 +172,22 @@ static void launchChild(String args[]) throws Throwable { klassName); final boolean expectDisable = !early.equals(""); + final boolean checkSubgraph = subgraph; + final boolean expectShared = shared.equals("-shared"); CDSTestUtils.run(opts).assertNormalExit(out -> { if (expectDisable) { out.shouldContain("UseSharedSpaces: CDS is disabled because early JVMTI ClassFileLoadHook is in use."); System.out.println("CDS disabled as expected"); } + if (checkSubgraph) { + if (expectShared) { + if (!out.getOutput().contains("UseSharedSpaces: Unable to map at required address in java heap")) { + out.shouldContain(subgraphInit); + } + } else { + out.shouldNotContain(subgraphInit); + } + } }); } diff --git a/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClassesForSubgraphs.java b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClassesForSubgraphs.java new file mode 100644 index 00000000000..eadc0207086 --- /dev/null +++ b/test/hotspot/jtreg/runtime/SharedArchiveFile/serviceability/ReplaceCriticalClassesForSubgraphs.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2018, 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 how CDS works when critical library classes are replaced with JVMTI ClassFileLoadHook + * @library /test/lib + * @requires vm.cds.archived.java.heap + * @build sun.hotspot.WhiteBox + * @run driver ClassFileInstaller -jar whitebox.jar sun.hotspot.WhiteBox + * @run main/othervm/native ReplaceCriticalClassesForSubgraphs + */ + +public class ReplaceCriticalClassesForSubgraphs extends ReplaceCriticalClasses { + public static void main(String args[]) throws Throwable { + ReplaceCriticalClassesForSubgraphs rcc = new ReplaceCriticalClassesForSubgraphs(); + rcc.process(args); + } + + public String[] getTests() { + String tests[] = { + // Try to replace classes that are used by the archived subgraph graphs. + "-early -notshared -subgraph java/lang/module/ResolvedModule jdk.internal.module.ArchivedModuleGraph", + "-early -notshared -subgraph java/lang/Long java.lang.Long$LongCache", + "-subgraph java/lang/Long java.lang.Long$LongCache", + }; + return tests; + } +} diff --git a/test/hotspot/jtreg/runtime/appcds/LotsOfClasses.java b/test/hotspot/jtreg/runtime/appcds/LotsOfClasses.java index 6cf58ed4653..aa1fc0f3599 100644 --- a/test/hotspot/jtreg/runtime/appcds/LotsOfClasses.java +++ b/test/hotspot/jtreg/runtime/appcds/LotsOfClasses.java @@ -57,9 +57,16 @@ public static void main(String[] args) throws Throwable { opts.addSuffix("--add-modules"); opts.addSuffix("ALL-SYSTEM"); opts.addSuffix("-Xlog:hashtables"); + opts.addSuffix("-Xms500m"); + opts.addSuffix("-Xmx500m"); OutputAnalyzer out = CDSTestUtils.createArchive(opts); - CDSTestUtils.checkDump(out); + try { + CDSTestUtils.checkDump(out); + } catch (java.lang.RuntimeException re) { + out.shouldContain( + "number of memory regions exceeds maximum due to fragmentation"); + } } static void findAllClasses(ArrayList list) throws Throwable { diff --git a/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java b/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java index a66ebf1954f..f490bbe0aca 100644 --- a/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java +++ b/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2018, 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 @@ -39,7 +39,8 @@ static void analyzeOutputOn(ProcessBuilder pb) throws Exception { OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("[safepoint,cleanup]"); output.shouldContain("safepoint cleanup tasks"); - output.shouldContain("deflating idle monitors"); + output.shouldContain("deflating global idle monitors"); + output.shouldContain("deflating per-thread idle monitors"); output.shouldContain("updating inline caches"); output.shouldContain("compilation policy safepoint handler"); output.shouldContain("purging class loader data graph"); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/aod/jvmti_aod.cpp b/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/aod/jvmti_aod.cpp index 98679eff799..df75829cbab 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/aod/jvmti_aod.cpp +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/aod/jvmti_aod.cpp @@ -263,6 +263,7 @@ int nsk_jvmti_aod_redefineClass( error = jvmti->Allocate(size, &classBytes); if (error != JVMTI_ERROR_NONE) { NSK_DISPLAY1("Failed to create memory %s\n", TranslateError(error)); + fclose(bytecode); return NSK_FALSE; } diff --git a/test/jdk/java/lang/String/Transform.java b/test/jdk/java/lang/String/Transform.java new file mode 100644 index 00000000000..a2c1f9c8d66 --- /dev/null +++ b/test/jdk/java/lang/String/Transform.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2018, 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 Unit tests for String#transform(Function f) + * @run main Transform + */ + +import java.util.function.Function; +import java.util.stream.Collectors; + +public class Transform { + public static void main(String[] args) { + test1(); + } + + /* + * Test String#transform(Function f) functionality. + */ + static void test1() { + simpleTransform("toUpperCase", "abc", s -> s.toUpperCase()); + simpleTransform("toLowerCase", "ABC", s -> s.toLowerCase()); + simpleTransform("substring", "John Smith", s -> s.substring(0, 4)); + + String multiline = " This is line one\n" + + " This is line two\n" + + " This is line three\n"; + String expected = "This is line one!\n" + + " This is line two!\n" + + " This is line three!\n"; + check("multiline", multiline.transform(string -> { + return string.lines() + .map(s -> s.transform(t -> t.substring(4) + "!")) + .collect(Collectors.joining("\n", "", "\n")); + }), expected); + } + + static void simpleTransform(String test, String s, Function f) { + check(test, s.transform(f), f.apply(s)); + } + + static void check(String test, Object output, Object expected) { + if (output != expected && (output == null || !output.equals(expected))) { + System.err.println("Testing " + test + ": unexpected result"); + System.err.println("Output:"); + System.err.println(output); + System.err.println("Expected:"); + System.err.println(expected); + throw new RuntimeException(); + } + } +} diff --git a/test/jdk/jdk/jfr/event/compiler/TestCompilerConfig.java b/test/jdk/jdk/jfr/event/compiler/TestCompilerConfig.java index d1236a931f3..3bcfee23978 100644 --- a/test/jdk/jdk/jfr/event/compiler/TestCompilerConfig.java +++ b/test/jdk/jdk/jfr/event/compiler/TestCompilerConfig.java @@ -40,7 +40,7 @@ * @run main/othervm jdk.jfr.event.compiler.TestCompilerConfig */ public class TestCompilerConfig { - private final static String EVENT_NAME = EventNames.CompilerConfig; + private final static String EVENT_NAME = EventNames.CompilerConfiguration; public static void main(String[] args) throws Exception { Recording recording = new Recording(); diff --git a/test/jdk/jdk/jfr/event/gc/detailed/TestEvacuationInfoEvent.java b/test/jdk/jdk/jfr/event/gc/detailed/TestEvacuationInfoEvent.java index f2ea27bb5c1..0383a862b63 100644 --- a/test/jdk/jdk/jfr/event/gc/detailed/TestEvacuationInfoEvent.java +++ b/test/jdk/jdk/jfr/event/gc/detailed/TestEvacuationInfoEvent.java @@ -45,7 +45,7 @@ * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:-UseFastUnorderedTimeStamps -XX:G1HeapRegionSize=1m -Xmx64m -Xmn16m -XX:+UseG1GC jdk.jfr.event.gc.detailed.TestEvacuationInfoEvent */ public class TestEvacuationInfoEvent { - private final static String EVENT_INFO_NAME = EventNames.EvacuationInfo; + private final static String EVENT_INFO_NAME = EventNames.EvacuationInformation; private final static String EVENT_FAILED_NAME = EventNames.EvacuationFailed; public static void main(String[] args) throws Throwable { @@ -69,8 +69,8 @@ public static void main(String[] args) throws Throwable { long setUsedAfter = Events.assertField(event, "cSetUsedAfter").atLeast(0L).getValue(); long setUsedBefore = Events.assertField(event, "cSetUsedBefore").atLeast(setUsedAfter).getValue(); int allocationRegions = Events.assertField(event, "allocationRegions").atLeast(0).getValue(); - long allocRegionsUsedBefore = Events.assertField(event, "allocRegionsUsedBefore").atLeast(0L).getValue(); - long allocRegionsUsedAfter = Events.assertField(event, "allocRegionsUsedAfter").atLeast(0L).getValue(); + long allocRegionsUsedBefore = Events.assertField(event, "allocationRegionsUsedBefore").atLeast(0L).getValue(); + long allocRegionsUsedAfter = Events.assertField(event, "allocationRegionsUsedAfter").atLeast(0L).getValue(); long bytesCopied = Events.assertField(event, "bytesCopied").atLeast(0L).getValue(); int regionsFreed = Events.assertField(event, "regionsFreed").atLeast(0).getValue(); diff --git a/test/jdk/jdk/jfr/event/metadata/TestLookForUntestedEvents.java b/test/jdk/jdk/jfr/event/metadata/TestLookForUntestedEvents.java new file mode 100644 index 00000000000..6c550e4d457 --- /dev/null +++ b/test/jdk/jdk/jfr/event/metadata/TestLookForUntestedEvents.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2018, 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 jdk.jfr.event.metadata; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import jdk.jfr.EventType; +import jdk.jfr.Experimental; +import jdk.jfr.FlightRecorder; +import jdk.test.lib.jfr.EventNames; +import jdk.test.lib.Utils; + +/** + * @test Check for JFR events not covered by tests + * @key jfr + * @requires vm.hasJFR + * @library /test/lib /test/jdk + * @run main jdk.jfr.event.metadata.TestLookForUntestedEvents + */ +public class TestLookForUntestedEvents { + private static final Path jfrTestRoot = Paths.get(Utils.TEST_SRC).getParent().getParent(); + private static final String MSG_SEPARATOR = "=========================="; + private static Set jfrEventTypes = new HashSet<>(); + + private static final Set knownEventsMissingFromEventNames = new HashSet<>( + Arrays.asList( + // The Z* events below should be marked as experimental; see: JDK-8213966 + "ZStatisticsSampler", "ZStatisticsCounter", + "ZPageAllocation", "ZThreadPhase" + ) + ); + + private static final Set hardToTestEvents = new HashSet<>( + Arrays.asList( + "DataLoss", "IntFlag", "ReservedStackActivation", + "DoubleFlag", "UnsignedLongFlagChanged", "IntFlagChanged", + "UnsignedIntFlag", "UnsignedIntFlagChanged", "DoubleFlagChanged") + ); + + // GC uses specific framework to test the events, instead of using event names literally. + // GC tests were inspected, as well as runtime output of GC tests. + // The following events below are know to be covered based on that inspection. + private static final Set coveredGcEvents = new HashSet<>( + Arrays.asList( + "MetaspaceGCThreshold", "MetaspaceAllocationFailure", "MetaspaceOOM", + "MetaspaceChunkFreeListSummary", "G1HeapSummary", "ParallelOldGarbageCollection", + "OldGarbageCollection", "G1GarbageCollection", "GCPhasePause", + "GCPhasePauseLevel1", "GCPhasePauseLevel2", "GCPhasePauseLevel3", + "GCPhasePauseLevel4", "GCPhaseConcurrent") + ); + + // This is a "known failure list" for this test. + // NOTE: if the event is not covered, a bug should be open, and bug number + // noted in the comments for this set. + private static final Set knownNotCoveredEvents = new HashSet<>( + // DumpReason: JDK-8213918, Shutdown: JDK-8213917 + Arrays.asList("DumpReason", "Shutdown") + ); + + + public static void main(String[] args) throws Exception { + for (EventType type : FlightRecorder.getFlightRecorder().getEventTypes()) { + if (type.getAnnotation(Experimental.class) == null) { + jfrEventTypes.add(type.getName().replace("jdk.", "")); + } + } + + checkEventNamesClass(); + lookForEventsNotCoveredByTests(); + } + + // Look thru JFR tests to make sure JFR events are referenced in the tests + private static void lookForEventsNotCoveredByTests() throws Exception { + List paths = Files.walk(jfrTestRoot) + .filter(Files::isRegularFile) + .filter(path -> isJavaFile(path)) + .collect(Collectors.toList()); + + Set eventsNotCoveredByTest = new HashSet<>(jfrEventTypes); + for (String event : jfrEventTypes) { + for (Path p : paths) { + if (findStringInFile(p, event)) { + eventsNotCoveredByTest.remove(event); + break; + } + } + } + + // Account for hard-to-test, experimental and GC tested events + eventsNotCoveredByTest.removeAll(hardToTestEvents); + eventsNotCoveredByTest.removeAll(coveredGcEvents); + eventsNotCoveredByTest.removeAll(knownNotCoveredEvents); + + if (!eventsNotCoveredByTest.isEmpty()) { + print(MSG_SEPARATOR + " Events not covered by test"); + for (String event: eventsNotCoveredByTest) { + print(event); + } + print(MSG_SEPARATOR); + throw new RuntimeException("Found JFR events not covered by tests"); + } + } + + // Make sure all the JFR events are accounted for in jdk.test.lib.jfr.EventNames + private static void checkEventNamesClass() throws Exception { + // jdk.test.lib.jfr.EventNames + Set eventsFromEventNamesClass = new HashSet<>(); + for (Field f : EventNames.class.getFields()) { + String name = f.getName(); + if (!name.equals("PREFIX")) { + String eventName = (String) f.get(null); + eventName = eventName.replace(EventNames.PREFIX, ""); + eventsFromEventNamesClass.add(eventName); + } + } + + // Account for the events that are known to be missing from the EventNames.java + eventsFromEventNamesClass.addAll(knownEventsMissingFromEventNames); + + if (!jfrEventTypes.equals(eventsFromEventNamesClass)) { + String exceptionMsg = "Events declared in jdk.test.lib.jfr.EventNames differ " + + "from events returned by FlightRecorder.getEventTypes()"; + print(MSG_SEPARATOR); + print(exceptionMsg); + print(""); + printSetDiff(jfrEventTypes, eventsFromEventNamesClass, + "jfrEventTypes", "eventsFromEventNamesClass"); + print(""); + + print("This could be because:"); + print("1) You forgot to write a unit test. Please do so in test/jdk/jdk/jfr/event/"); + print("2) You wrote a unit test, but you didn't reference the event in"); + print(" test/lib/jdk/test/lib/jfr/EventNames.java. "); + print("3) It is not feasible to test the event, not even a sanity test. "); + print(" Add the event name to test/lib/jdk/test/lib/jfr/EventNames.java "); + print(" and a short comment why it can't be tested"); + print("4) The event is experimental. Please add 'experimental=\"true\"' to "); + print(" element in metadata.xml if it is a native event, or @Experimental if it is a "); + print(" Java event. The event will now not show up in JMC"); + System.out.println(MSG_SEPARATOR); + throw new RuntimeException(exceptionMsg); + } + } + + // ================ Helper methods + private static boolean isJavaFile(Path p) { + String fileName = p.getFileName().toString(); + int i = fileName.lastIndexOf('.'); + if ( (i < 0) || (i > fileName.length()) ) { + return false; + } + return "java".equals(fileName.substring(i+1)); + } + + private static boolean findStringInFile(Path p, String searchTerm) throws IOException { + long c = 0; + try (Stream stream = Files.lines(p)) { + c = stream + .filter(line -> line.contains(searchTerm)) + .count(); + } + return (c != 0); + } + + private static void printSetDiff(Set a, Set b, + String setAName, String setBName) { + if (a.size() > b.size()) { + a.removeAll(b); + System.out.printf("Set %s has more elements than set %s:", setAName, setBName); + System.out.println(); + printSet(a); + } else { + b.removeAll(a); + System.out.printf("Set %s has more elements than set %s:", setBName, setAName); + System.out.println(); + printSet(b); + } + } + + private static void printSet(Set set) { + for (String e : set) { + System.out.println(e); + } + } + + private static void print(String s) { + System.out.println(s); + } +} diff --git a/test/jdk/jdk/jfr/event/runtime/TestSafepointEvents.java b/test/jdk/jdk/jfr/event/runtime/TestSafepointEvents.java index 743216d8a9a..285dbf2212b 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestSafepointEvents.java +++ b/test/jdk/jdk/jfr/event/runtime/TestSafepointEvents.java @@ -54,7 +54,7 @@ public class TestSafepointEvents { static final String[] EVENT_NAMES = new String[] { EventNames.SafepointBegin, - EventNames.SafepointStateSyncronization, + EventNames.SafepointStateSynchronization, EventNames.SafepointWaitBlocked, EventNames.SafepointCleanup, EventNames.SafepointCleanupTask, diff --git a/test/jdk/sun/security/tools/keytool/ProbingFailure.java b/test/jdk/sun/security/tools/keytool/ProbingFailure.java new file mode 100644 index 00000000000..1629a2cc717 --- /dev/null +++ b/test/jdk/sun/security/tools/keytool/ProbingFailure.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2018, 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 8214100 + * @summary use of keystore probing results in unnecessary exception thrown + * @library /test/lib + * @compile -XDignore.symbol.file ProbingFailure.java + * @run main ProbingFailure + */ + +import jdk.test.lib.SecurityTools; +import jdk.test.lib.process.OutputAnalyzer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.KeyStoreSpi; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.Date; +import java.util.Enumeration; + +public class ProbingFailure { + + public static void main(String[] args) throws Exception { + + // genkeypair + kt("-genkeypair -keystore mks -alias a -dname CN=A -storetype MYKS") + .shouldHaveExitValue(0); + + // list + kt("-list -keystore mks -storetype MYKS") + .shouldHaveExitValue(0); + + kt("-list -keystore mks") + .shouldHaveExitValue(1) + .shouldContain("This keystore does not support probing"); + + // importkeystore + kt("-importkeystore -srckeystore mks -srcstoretype MYKS -destkeystore p12") + .shouldHaveExitValue(0); + + kt("-importkeystore -srckeystore mks -destkeystore p12a") + .shouldHaveExitValue(1) + .shouldContain("This keystore does not support probing"); + + // in-place importkeystore + kt("-importkeystore -srckeystore mks -srcstoretype MYKS -destkeystore mks -deststoretype myks") + .shouldContain("The original keystore \"mks\" is backed up") + .shouldHaveExitValue(0); + + kt("-importkeystore -srckeystore mks -srcstoretype MYKS -destkeystore mks") + .shouldContain("Migrated \"mks\" to PKCS12") + .shouldHaveExitValue(0); + + kt("-importkeystore -srckeystore p12 -destkeystore p12 -deststoretype MYKS") + .shouldContain("Migrated \"p12\" to MYKS") + .shouldHaveExitValue(0); + } + + static OutputAnalyzer kt(String cmd) throws Exception { + return SecurityTools.keytool( + "-storepass changeit -keypass changeit -debug " + + "-srcstorepass changeit -deststorepass changeit " + + "-providerclass ProbingFailure$MyProvider " + + "-providerpath " + System.getProperty("test.classes") + + " " + cmd); + } + + public static class MyProvider extends Provider { + public MyProvider() { + super("MP", "1.0", "My Provider"); + put("KeyStore.MYKS", "ProbingFailure$MyKS"); + } + } + + // The MYKS keystore prepends a zero byte before a PKCS12 file + // and does not support probing. + public static class MyKS extends KeyStoreSpi { + + KeyStore ks; + + public MyKS() { + try { + ks = KeyStore.getInstance("PKCS12"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public Key engineGetKey(String alias, char[] password) + throws NoSuchAlgorithmException, UnrecoverableKeyException { + try { + return ks.getKey(alias, password); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public Certificate[] engineGetCertificateChain(String alias) { + try { + return ks.getCertificateChain(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public Certificate engineGetCertificate(String alias) { + try { + return ks.getCertificate(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public Date engineGetCreationDate(String alias) { + try { + return ks.getCreationDate(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public void engineSetKeyEntry(String alias, Key key, char[] password, + Certificate[] chain) throws KeyStoreException { + ks.setKeyEntry(alias, key, password, chain); + } + + @Override + public void engineSetKeyEntry(String alias, byte[] key, + Certificate[] chain) throws KeyStoreException { + ks.setKeyEntry(alias, key, chain); + } + + @Override + public void engineSetCertificateEntry(String alias, Certificate cert) + throws KeyStoreException { + ks.setCertificateEntry(alias, cert); + } + + @Override + public void engineDeleteEntry(String alias) throws KeyStoreException { + ks.deleteEntry(alias); + } + + @Override + public Enumeration engineAliases() { + try { + return ks.aliases(); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean engineContainsAlias(String alias) { + try { + return ks.containsAlias(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public int engineSize() { + try { + return ks.size(); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean engineIsKeyEntry(String alias) { + try { + return ks.isKeyEntry(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean engineIsCertificateEntry(String alias) { + try { + return ks.isCertificateEntry(alias); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public String engineGetCertificateAlias(Certificate cert) { + try { + return ks.getCertificateAlias(cert); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public void engineStore(OutputStream stream, char[] password) + throws IOException, NoSuchAlgorithmException, CertificateException { + stream.write(0); + try { + ks.store(stream, password); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } + + @Override + public void engineLoad(InputStream stream, char[] password) + throws IOException, NoSuchAlgorithmException, CertificateException { + if (stream != null) { + stream.read(); + } + ks.load(stream, password); + } + + @Override + public boolean engineProbe(InputStream stream) { + return false; + } + } +} diff --git a/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java b/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java new file mode 100644 index 00000000000..29e685dee00 --- /dev/null +++ b/test/langtools/jdk/javadoc/doclet/testIndexInPackageFiles/TestIndexInPackageFiles.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2018, 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 8213957 8213958 + * @summary Test use of at-index in package-iinfo and doc-files + * @library /tools/lib ../lib + * @modules jdk.javadoc/jdk.javadoc.internal.tool + * @build toolbox.ToolBox JavadocTester + * @run main TestIndexInPackageFiles + */ + +import java.io.IOException; +import java.nio.file.Path; +import toolbox.ToolBox; + +public class TestIndexInPackageFiles extends JavadocTester { + + public static void main(String... args) throws Exception { + TestIndexInPackageFiles tester = new TestIndexInPackageFiles (); + tester.runTests(); + } + + ToolBox tb = new ToolBox(); + + @Test + public void test() throws IOException { + Path src = Path.of("src"); + tb.writeJavaFiles(src, + "/**\n" + + " * Summary.\n" + + " * {@index test.name.1 additional info}\n" + + " * {@systemProperty test.property.1}\n" + + " */\n" + + "package p.q;", + "package p.q;\n" + + "/** This is a class in p.q. */\n" + + "public class C { }\n"); + + tb.writeFile(src.resolve("p/q/doc-files/extra.html"), + "Extra\n" + + "

    Extra

    \n" + + "{@index test.name.2 additional info}\n" + + "{@systemProperty test.property.2}\n" + + "\n"); + + tb.writeFile("overview.html", + "Overview\n" + + "

    Overview

    \n" + + "{@index test.name.3 additional info}\n" + + "\n"); + + + javadoc("-d", "out", + "-sourcepath", src.toString(), + "-overview", "overview.html", + "p.q"); + + checkExit(Exit.OK); + + // Note there is an implicit call to checkLinks, but that only + // checks the links are valid if they are actually present. + // Here, we specifically check for both ends of each link. + // However, we assume the search index files are generated appropriately, + // to match the A-Z index files checked here. + + checkOutput("p/q/package-summary.html", true, + "test.name.1", + "test.property.1"); + + checkOutput("p/q/doc-files/extra.html", true, + "test.name.2", + "test.property.2"); + + checkOutput("index.html", true, + "test.name.3"); + + checkOutput("index-all.html", true, + "test.name.1", + "test.name.2", + "test.name.3 - Search tag in Overview", + "test.property.1", + "test.property.2"); + } +} + diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java new file mode 100644 index 00000000000..fd7add71aa7 --- /dev/null +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2002, 2018, 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 8190312 + * @summary test redirected URLs for -link + * @library /tools/lib ../lib + * @modules jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * jdk.javadoc/jdk.javadoc.internal.api + * jdk.javadoc/jdk.javadoc.internal.tool + * @build toolbox.ToolBox toolbox.JavacTask JavadocTester + * @run main TestRedirectLinks + */ + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManagerFactory; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; + +import toolbox.JavacTask; +import toolbox.ToolBox; + + +public class TestRedirectLinks extends JavadocTester { + /** + * The entry point of the test. + * @param args the array of command line arguments. + */ + public static void main(String... args) throws Exception { + TestRedirectLinks tester = new TestRedirectLinks(); + tester.runTests(); + } + + private ToolBox tb = new ToolBox(); + + /* + * This test requires access to a URL that is redirected + * from http: to https:. + * For now, we use the main JDK API on docs.oracle.com. + * The test is skipped if access to the server is not available. + * (A better solution is to use a local testing web server.) + */ + @Test + public void testRedirects() throws Exception { + // first, test to see if access to external URLs is available + URL testURL = new URL("http://docs.oracle.com/en/java/javase/11/docs/api/element-list"); + boolean haveRedirectURL = false; + try { + URLConnection conn = testURL.openConnection(); + conn.connect(); + out.println("Opened connection to " + testURL); + if (conn instanceof HttpURLConnection) { + HttpURLConnection httpConn = (HttpURLConnection) conn; + int status = httpConn.getResponseCode(); + if (status / 100 == 3) { + haveRedirectURL = true; + } + out.println("Status: " + status); + int n = 0; + while (httpConn.getHeaderField(n) != null) { + out.println("Header: " + httpConn.getHeaderFieldKey(n) + ": " + httpConn.getHeaderField(n)); + n++; + } + } + } catch (Exception e) { + out.println("Exception occurred: " + e); + } + + if (!haveRedirectURL) { + out.println("Setup failed; this test skipped"); + return; + } + + String apiURL = "http://docs.oracle.com/en/java/javase/11/docs/api"; + String outRedirect = "outRedirect"; + javadoc("-d", outRedirect, + "-html4", + "-sourcepath", testSrc, + "-link", apiURL, + "pkg"); + checkExit(Exit.OK); + checkOutput("pkg/B.html", true, + "Link-Plain to String Class"); + checkOutput("pkg/C.html", true, + "Object"); + } + + private Path libApi = Path.of("libApi"); + private HttpServer oldServer = null; + private HttpsServer newServer = null; + + /** + * This test verifies redirection using temporary localhost web servers, + * such that one server redirects to the other. + */ + @Test + public void testWithServers() throws Exception { + // Set up a simple library + Path libSrc = Path.of("libSrc"); + tb.writeJavaFiles(libSrc.resolve("mA"), + "module mA { exports p1; exports p2; }", + "package p1; public class C1 { }", + "package p2; public class C2 { }"); + tb.writeJavaFiles(libSrc.resolve("mB"), + "module mB { exports p3; exports p4; }", + "package p3; public class C3 { }", + "package p4; public class C4 { }"); + + Path libModules = Path.of("libModules"); + Files.createDirectories(libModules); + + new JavacTask(tb) + .outdir(libModules) + .options("--module-source-path", libSrc.toString(), + "--module", "mA,mB") + .run() + .writeAll(); + + javadoc("-d", libApi.toString(), + "--module-source-path", libSrc.toString(), + "--module", "mA,mB" ); + + // start web servers + InetAddress localHost = InetAddress.getLocalHost(); + try { + oldServer = HttpServer.create(new InetSocketAddress(localHost, 0), 0); + String oldURL = "http:/" + oldServer.getAddress(); + oldServer.createContext("/", this::handleOldRequest); + out.println("Starting old server (" + oldServer.getClass().getSimpleName() + ") on " + oldURL); + oldServer.start(); + + SSLContext sslContext = new SimpleSSLContext().get(); + newServer = HttpsServer.create(new InetSocketAddress(localHost, 0), 0); + String newURL = "https:/" + newServer.getAddress(); + newServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + newServer.createContext("/", this::handleNewRequest); + out.println("Starting new server (" + newServer.getClass().getSimpleName() + ") on " + newURL); + newServer.start(); + + // Set up API to use that library + Path src = Path.of("src"); + tb.writeJavaFiles(src.resolve("mC"), + "module mC { requires mA; requires mB; exports p5; exports p6; }", + "package p5; public class C5 extends p1.C1 { }", + "package p6; public class C6 { public p4.C4 c4; }"); + + // Set defaults for HttpsURLConfiguration for the duration of this + // invocation of javadoc to use our testing sslContext + HostnameVerifier prevHostNameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); + SSLSocketFactory prevSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); + try { + HttpsURLConnection.setDefaultHostnameVerifier((hostName, session) -> true); + HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); + + javadoc("-d", "api", + "--module-source-path", src.toString(), + "--module-path", libModules.toString(), + "-link", "http:/" + oldServer.getAddress(), + "--module", "mC" ); + + } finally { + HttpsURLConnection.setDefaultHostnameVerifier(prevHostNameVerifier); + HttpsURLConnection.setDefaultSSLSocketFactory(prevSSLSocketFactory); + } + + // Verify the following: + // 1: A warning about the redirection is generated. + // 2: The contents of the redirected link were read successfully, + // identifying the remote API + // 3: The original URL is still used in the generated docs, to avoid assuming + // that all the other files at that link have been redirected as well. + checkOutput(Output.OUT, true, + "javadoc: warning - URL " + oldURL + "/element-list was redirected to " + newURL + "/element-list"); + checkOutput("mC/p5/C5.html", true, + "extends C1"); + checkOutput("mC/p6/C6.html", true, + "C4"); + } finally { + if (oldServer != null) { + out.println("Stopping old server on " + oldServer.getAddress()); + oldServer.stop(0); + } + if (newServer != null) { + out.println("Stopping new server on " + newServer.getAddress()); + newServer.stop(0); + } + } + } + + private void handleOldRequest(HttpExchange x) throws IOException { + out.println("old request: " + + x.getProtocol() + " " + + x.getRequestMethod() + " " + + x.getRequestURI()); + String newProtocol = (newServer instanceof HttpsServer) ? "https" : "http"; + String redirectTo = newProtocol + ":/" + newServer.getAddress() + x.getRequestURI(); + out.println(" redirect to: " + redirectTo); + x.getResponseHeaders().add("Location", redirectTo); + x.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, 0); + x.getResponseBody().close(); + } + + private void handleNewRequest(HttpExchange x) throws IOException { + out.println("new request: " + + x.getProtocol() + " " + + x.getRequestMethod() + " " + + x.getRequestURI()); + Path file = libApi.resolve(x.getRequestURI().getPath().substring(1).replace('/', File.separatorChar)); + System.err.println(file); + if (Files.exists(file)) { + byte[] bytes = Files.readAllBytes(file); + // in the context of this test, the only request should be element-list, + // which we can say is text/plain. + x.getResponseHeaders().add("Content-type", "text/plain"); + x.sendResponseHeaders(HttpURLConnection.HTTP_OK, bytes.length); + try (OutputStream responseStream = x.getResponseBody()) { + responseStream.write(bytes); + } + } else { + x.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0); + x.getResponseBody().close(); + } + } + + /** + * Creates a simple usable SSLContext for an HttpsServer using + * a default keystore in the test tree. + *

    + * This class is based on + * test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java + */ + static class SimpleSSLContext { + + private final SSLContext ssl; + + /** + * Loads default keystore. + */ + SimpleSSLContext() throws Exception { + Path p = Path.of(System.getProperty("test.src", ".")).toAbsolutePath(); + while (!Files.exists(p.resolve("TEST.ROOT"))) { + p = p.getParent(); + if (p == null) { + throw new IOException("can't find TEST.ROOT"); + } + } + + System.err.println("Test suite root: " + p); + Path testKeys = p.resolve("../lib/jdk/test/lib/net/testkeys").normalize(); + if (!Files.exists(testKeys)) { + throw new IOException("can't find testkeys"); + } + System.err.println("Test keys: " + testKeys); + + try (InputStream fis = Files.newInputStream(testKeys)) { + ssl = init(fis); + } + } + + private SSLContext init(InputStream i) throws Exception { + char[] passphrase = "passphrase".toCharArray(); + KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(i, passphrase); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); + kmf.init(ks, passphrase); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); + tmf.init(ks); + + SSLContext ssl = SSLContext.getInstance("TLS"); + ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + return ssl; + } + + SSLContext get() { + return ssl; + } + } +} diff --git a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java index 0a8fdd81094..8f7190c6946 100644 --- a/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java +++ b/test/langtools/jdk/javadoc/doclet/testSearch/TestSearch.java @@ -362,6 +362,44 @@ void testURLEncoding_html4() { checkSearchIndex(false); } + @Test + void testJapaneseLocale() { + javadoc("-locale", "ja_JP", + "-d", "out-jp", + "--no-module-directories", + "-Xdoclint:none", + "-sourcepath", testSrc, + "-use", + "pkg", "pkg1", "pkg2", "pkg3"); + checkExit(Exit.OK); + checkOutput(Output.OUT, true, + "\u30d1\u30c3\u30b1\u30fc\u30b8pkg\u306e\u30bd\u30fc\u30b9\u30fb\u30d5\u30a1" + + "\u30a4\u30eb\u3092\u8aad\u307f\u8fbc\u3093\u3067\u3044\u307e\u3059...\n", + "\u30d1\u30c3\u30b1\u30fc\u30b8pkg1\u306e\u30bd\u30fc\u30b9\u30fb\u30d5\u30a1" + + "\u30a4\u30eb\u3092\u8aad\u307f\u8fbc\u3093\u3067\u3044\u307e\u3059...\n"); + checkSearchJS(); + checkSearchIndex(true); + } + + @Test + void testChineseLocale() { + javadoc("-locale", "zh_CN", + "-d", "out-cn", + "--no-module-directories", + "-Xdoclint:none", + "-sourcepath", testSrc, + "-use", + "pkg", "pkg1", "pkg2", "pkg3"); + checkExit(Exit.OK); + checkOutput(Output.OUT, true, + "\u6b63\u5728\u52a0\u8f7d\u7a0b\u5e8f\u5305pkg\u7684\u6e90\u6587\u4ef6...\n", + "\u6b63\u5728\u52a0\u8f7d\u7a0b\u5e8f\u5305pkg1\u7684\u6e90\u6587\u4ef6...\n", + "\u6b63\u5728\u52a0\u8f7d\u7a0b\u5e8f\u5305pkg2\u7684\u6e90\u6587\u4ef6...\n", + "\u6b63\u5728\u52a0\u8f7d\u7a0b\u5e8f\u5305pkg3\u7684\u6e90\u6587\u4ef6...\n"); + checkSearchJS(); + checkSearchIndex(true); + } + void checkDocLintErrors() { checkOutput(Output.OUT, true, "A sample method. Testing search tag for {@index \"unclosed quote}.", diff --git a/test/langtools/tools/javac/T8203277/PreflowShouldVisitLambdaOrDiamondInsideLambdaTest.java b/test/langtools/tools/javac/T8203277/PreflowShouldVisitLambdaOrDiamondInsideLambdaTest.java new file mode 100644 index 00000000000..db9afc6fd06 --- /dev/null +++ b/test/langtools/tools/javac/T8203277/PreflowShouldVisitLambdaOrDiamondInsideLambdaTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018, 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 8203277 + * @summary preflow visitor used during lambda attribution shouldn't visit class definitions inside the lambda body + * @compile PreflowShouldVisitLambdaOrDiamondInsideLambdaTest.java + */ + +import java.util.List; +import java.util.function.Function; + +class PreflowShouldVisitLambdaOrDiamondInsideLambdaTest { + void build() { + List> list1 = transform(null, + builder -> new Function<>() { + public Double apply(String params) { return null; } + }); + + List> list2 = transform(null, + builder -> arg -> null); + } + + static List transform(List fromList, + Function function) { return null; } +} diff --git a/test/langtools/tools/javac/api/TestGetScopeResult.java b/test/langtools/tools/javac/api/TestGetScopeResult.java index a96434c3d12..88201a3bf65 100644 --- a/test/langtools/tools/javac/api/TestGetScopeResult.java +++ b/test/langtools/tools/javac/api/TestGetScopeResult.java @@ -134,7 +134,7 @@ public void run() throws IOException { implicitExplicitConflict1); String[] implicitExplicitConflict2 = { - "s:", + "s:none", ":t", "super:java.lang.Object", "this:Test" @@ -179,7 +179,8 @@ public Void visitLambdaExpression(LambdaExpressionTree node, Void p) { List expectedList = List.of(expected); if (!expectedList.equals(actual)) { - throw new IllegalStateException("Unexpected scope content: " + actual); + throw new IllegalStateException("Unexpected scope content: " + actual + "\n" + + "expected: " + expectedList); } } } diff --git a/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java b/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java new file mode 100644 index 00000000000..d7f9b6844c8 --- /dev/null +++ b/test/langtools/tools/javac/switchexpr/SwitchExpressionIsNotAConstant.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2018, 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 8214113 + * @summary Verify the switch expression's type does not have a constant attached, + * and so the switch expression is not elided. + * @compile --enable-preview --source 12 SwitchExpressionIsNotAConstant.java + * @run main/othervm --enable-preview SwitchExpressionIsNotAConstant + */ +public class SwitchExpressionIsNotAConstant { + + public static void main(String[] args) { + int i = 0; + { + i = 0; + int dummy = 1 + switch (i) { + default -> { + i++; + break 1; + } + }; + if (i != 1) { + throw new IllegalStateException("Side effects missing."); + } + } + { + i = 0; + int dummy = 1 + switch (i) { + case -1 -> 1; + default -> { + i++; + break 1; + } + }; + if (i != 1) { + throw new IllegalStateException("Side effects missing."); + } + } + { + i = 0; + int dummy = 1 + switch (i) { + default : + i++; + break 1; + }; + if (i != 1) { + throw new IllegalStateException("Side effects missing."); + } + } + { + i = 0; + int dummy = 1 + switch (i) { + case -1: break 1; + default: + i++; + break 1; + }; + if (i != 1) { + throw new IllegalStateException("Side effects missing."); + } + } + } + +} diff --git a/test/lib/jdk/test/lib/jfr/EventNames.java b/test/lib/jdk/test/lib/jfr/EventNames.java index c25e4e84fa5..a202fb22a53 100644 --- a/test/lib/jdk/test/lib/jfr/EventNames.java +++ b/test/lib/jdk/test/lib/jfr/EventNames.java @@ -54,7 +54,6 @@ public class EventNames { public final static String StringFlagChanged = PREFIX + "StringFlagChanged"; // Runtime - public final static String VMException = PREFIX + "JavaErrorThrow"; public final static String ThreadStart = PREFIX + "ThreadStart"; public final static String ThreadEnd = PREFIX + "ThreadEnd"; public final static String ThreadSleep = PREFIX + "ThreadSleep"; @@ -66,26 +65,26 @@ public class EventNames { public final static String ClassDefine = PREFIX + "ClassDefine"; public final static String ClassUnload = PREFIX + "ClassUnload"; public final static String SafepointBegin = PREFIX + "SafepointBegin"; - public final static String SafepointStateSyncronization = PREFIX + "SafepointStateSynchronization"; + public final static String SafepointStateSynchronization = PREFIX + "SafepointStateSynchronization"; public final static String SafepointWaitBlocked = PREFIX + "SafepointWaitBlocked"; public final static String SafepointCleanup = PREFIX + "SafepointCleanup"; public final static String SafepointCleanupTask = PREFIX + "SafepointCleanupTask"; public final static String SafepointEnd = PREFIX + "SafepointEnd"; public final static String ExecuteVMOperation = PREFIX + "ExecuteVMOperation"; public final static String Shutdown = PREFIX + "Shutdown"; - public final static String VMError = PREFIX + "VMError"; public final static String JavaThreadStatistics = PREFIX + "JavaThreadStatistics"; public final static String ClassLoadingStatistics = PREFIX + "ClassLoadingStatistics"; public final static String ClassLoaderStatistics = PREFIX + "ClassLoaderStatistics"; public final static String ThreadAllocationStatistics = PREFIX + "ThreadAllocationStatistics"; public final static String ExecutionSample = PREFIX + "ExecutionSample"; public final static String NativeMethodSample = PREFIX + "NativeMethodSample"; - public final static String ExecutionSampling = PREFIX + "ExecutionSampling"; public final static String ThreadDump = PREFIX + "ThreadDump"; public final static String OldObjectSample = PREFIX + "OldObjectSample"; public final static String BiasedLockRevocation = PREFIX + "BiasedLockRevocation"; public final static String BiasedLockSelfRevocation = PREFIX + "BiasedLockSelfRevocation"; public final static String BiasedLockClassRevocation = PREFIX + "BiasedLockClassRevocation"; + // This event is hard to test + public final static String ReservedStackActivation = PREFIX + "ReservedStackActivation"; // GC public final static String GCHeapSummary = PREFIX + "GCHeapSummary"; @@ -100,12 +99,13 @@ public class EventNames { public final static String G1HeapRegionTypeChange = PREFIX + "G1HeapRegionTypeChange"; public final static String TenuringDistribution = PREFIX + "TenuringDistribution"; public final static String GarbageCollection = PREFIX + "GarbageCollection"; - public final static String ParallelOldCollection = PREFIX + "ParallelOldGarbageCollection"; + public final static String ParallelOldGarbageCollection = PREFIX + "ParallelOldGarbageCollection"; + public final static String ParallelOldCollection = ParallelOldGarbageCollection; public final static String YoungGarbageCollection = PREFIX + "YoungGarbageCollection"; public final static String OldGarbageCollection = PREFIX + "OldGarbageCollection"; public final static String G1GarbageCollection = PREFIX + "G1GarbageCollection"; public final static String G1MMU = PREFIX + "G1MMU"; - public final static String EvacuationInfo = PREFIX + "EvacuationInfo"; + public final static String EvacuationInformation = PREFIX + "EvacuationInformation"; public final static String GCReferenceStatistics = PREFIX + "GCReferenceStatistics"; public final static String ObjectCountAfterGC = PREFIX + "ObjectCountAfterGC"; public final static String PromoteObjectInNewPLAB = PREFIX + "PromoteObjectInNewPLAB"; @@ -117,6 +117,7 @@ public class EventNames { public final static String GCPhasePauseLevel1 = PREFIX + "GCPhasePauseLevel1"; public final static String GCPhasePauseLevel2 = PREFIX + "GCPhasePauseLevel2"; public final static String GCPhasePauseLevel3 = PREFIX + "GCPhasePauseLevel3"; + public final static String GCPhasePauseLevel4 = PREFIX + "GCPhasePauseLevel4"; public final static String ObjectCount = PREFIX + "ObjectCount"; public final static String GCConfiguration = PREFIX + "GCConfiguration"; public final static String GCSurvivorConfiguration = PREFIX + "GCSurvivorConfiguration"; @@ -129,6 +130,7 @@ public class EventNames { public final static String G1BasicIHOP = PREFIX + "G1BasicIHOP"; public final static String AllocationRequiringGC = PREFIX + "AllocationRequiringGC"; public final static String GCPhaseParallel = PREFIX + "GCPhaseParallel"; + public final static String GCPhaseConcurrent = PREFIX + "GCPhaseConcurrent"; // Compiler public final static String Compilation = PREFIX + "Compilation"; @@ -136,7 +138,7 @@ public class EventNames { public final static String CompilationFailure = PREFIX + "CompilationFailure"; public final static String CompilerInlining = PREFIX + "CompilerInlining"; public final static String CompilerStatistics = PREFIX + "CompilerStatistics"; - public final static String CompilerConfig = PREFIX + "CompilerConfiguration"; + public final static String CompilerConfiguration = PREFIX + "CompilerConfiguration"; public final static String CodeCacheStatistics = PREFIX + "CodeCacheStatistics"; public final static String CodeCacheConfiguration = PREFIX + "CodeCacheConfiguration"; public final static String CodeSweeperStatistics = PREFIX + "CodeSweeperStatistics"; diff --git a/test/lib/jdk/test/lib/process/ProcessTools.java b/test/lib/jdk/test/lib/process/ProcessTools.java index 33a7939f586..396b08b2b04 100644 --- a/test/lib/jdk/test/lib/process/ProcessTools.java +++ b/test/lib/jdk/test/lib/process/ProcessTools.java @@ -464,7 +464,10 @@ public static OutputAnalyzer executeCommand(String... cmds) */ public static OutputAnalyzer executeCommand(ProcessBuilder pb) throws Throwable { - String cmdLine = pb.command().stream().collect(Collectors.joining(" ")); + String cmdLine = pb.command().stream() + .map(x -> (x.contains(" ") || x.contains("$")) + ? ("'" + x + "'") : x) + .collect(Collectors.joining(" ")); System.out.println("Command line: [" + cmdLine + "]"); OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); System.out.println(analyzer.getOutput());