1 /*
   2  * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.javadoc.internal.doclets.toolkit.util;
  27 
  28 import java.io.*;
  29 import java.net.*;
  30 import java.util.HashMap;
  31 import java.util.Map;
  32 
  33 import javax.lang.model.element.Element;
  34 import javax.lang.model.element.PackageElement;
  35 import javax.tools.Diagnostic;
  36 import javax.tools.DocumentationTool;
  37 
  38 import jdk.javadoc.doclet.Reporter;
  39 import jdk.javadoc.internal.doclets.toolkit.BaseConfiguration;
  40 
  41 /**
  42  * Process and manage "-link" and "-linkoffline" to external packages. The
  43  * options "-link" and "-linkoffline" both depend on the fact that Javadoc now
  44  * generates "package-list"(lists all the packages which are getting
  45  * documented) file in the current or the destination directory, while
  46  * generating the documentation.
  47  *
  48  *  <p><b>This is NOT part of any supported API.
  49  *  If you write code that depends on this, you do so at your own risk.
  50  *  This code and its internal interfaces are subject to change or
  51  *  deletion without notice.</b>
  52  *
  53  * @author Atul M Dambalkar
  54  * @author Robert Field
  55  */
  56 public class Extern {
  57 
  58     /**
  59      * Map package names onto Extern Item objects.
  60      * Lazily initialized.
  61      */
  62     private Map<String, Item> packageToItemMap;
  63 
  64     /**
  65      * The global configuration information for this run.
  66      */
  67     private final BaseConfiguration configuration;
  68 
  69     /**
  70      * True if we are using -linkoffline and false if -link is used instead.
  71      */
  72     private boolean linkoffline = false;
  73 
  74     /**
  75      * Stores the info for one external doc set
  76      */
  77     private class Item {
  78 
  79         /**
  80          * Package name, found in the "package-list" file in the {@link path}.
  81          */
  82         final String packageName;
  83 
  84         /**
  85          * The URL or the directory path at which the package documentation will be
  86          * avaliable.
  87          */
  88         final String path;
  89 
  90         /**
  91          * If given path is directory path then true else if it is a URL then false.
  92          */
  93         final boolean relative;
  94 
  95         /**
  96          * Constructor to build a Extern Item object and map it with the package name.
  97          * If the same package name is found in the map, then the first mapped
  98          * Item object or offline location will be retained.
  99          *
 100          * @param packageName Package name found in the "package-list" file.
 101          * @param path        URL or Directory path from where the "package-list"
 102          * file is picked.
 103          * @param relative    True if path is URL, false if directory path.
 104          */
 105         Item(String packageName, String path, boolean relative) {
 106             this.packageName = packageName;
 107             this.path = path;
 108             this.relative = relative;
 109             if (packageToItemMap == null) {
 110                 packageToItemMap = new HashMap<>();
 111             }
 112             if (!packageToItemMap.containsKey(packageName)) { // save the previous
 113                 packageToItemMap.put(packageName, this);        // mapped location
 114             }
 115         }
 116 
 117         /**
 118          * String representation of "this" with packagename and the path.
 119          */
 120         @Override
 121         public String toString() {
 122             return packageName + (relative? " -> " : " => ") + path;
 123         }
 124     }
 125 
 126     public Extern(BaseConfiguration configuration) {
 127         this.configuration = configuration;
 128     }
 129 
 130     /**
 131      * Determine if a element item is externally documented.
 132      *
 133      * @param element an Element.
 134      * @return true if the element is externally documented
 135      */
 136     public boolean isExternal(Element element) {
 137         if (packageToItemMap == null) {
 138             return false;
 139         }
 140         PackageElement pe = configuration.utils.containingPackage(element);
 141         if (pe.isUnnamed()) {
 142             return false;
 143         }
 144         return packageToItemMap.get(configuration.utils.getPackageName(pe)) != null;
 145     }
 146 
 147     /**
 148      * Convert a link to be an external link if appropriate.
 149      *
 150      * @param pkgName The package name.
 151      * @param relativepath    The relative path.
 152      * @param filename    The link to convert.
 153      * @return if external return converted link else return null
 154      */
 155     public DocLink getExternalLink(String pkgName, DocPath relativepath, String filename) {
 156         return getExternalLink(pkgName, relativepath, filename, null);
 157     }
 158 
 159     public DocLink getExternalLink(String pkgName, DocPath relativepath, String filename,
 160             String memberName) {
 161         Item fnd = findPackageItem(pkgName);
 162         if (fnd == null)
 163             return null;
 164 
 165         DocPath p = fnd.relative ?
 166                 relativepath.resolve(fnd.path).resolve(filename) :
 167                 DocPath.create(fnd.path).resolve(filename);
 168 
 169         return new DocLink(p, "is-external=true", memberName);
 170     }
 171 
 172     /**
 173      * Build the extern package list from given URL or the directory path,
 174      * as specified with the "-link" flag.
 175      * Flag error if the "-link" or "-linkoffline" option is already used.
 176      *
 177      * @param url        URL or Directory path.
 178      * @param reporter   The <code>DocErrorReporter</code> used to report errors.
 179      * @return true if successful, false otherwise
 180      * @throws DocFileIOException if there is a problem reading a package list file
 181      */
 182     public boolean link(String url, Reporter reporter) throws DocFileIOException {
 183         return link(url, url, reporter, false);
 184     }
 185 
 186     /**
 187      * Build the extern package list from given URL or the directory path,
 188      * as specified with the "-linkoffline" flag.
 189      * Flag error if the "-link" or "-linkoffline" option is already used.
 190      *
 191      * @param url        URL or Directory path.
 192      * @param pkglisturl This can be another URL for "package-list" or ordinary
 193      *                   file.
 194      * @param reporter   The <code>DocErrorReporter</code> used to report errors.
 195      * @return true if successful, false otherwise
 196      * @throws DocFileIOException if there is a problem reading a package list file
 197      */
 198     public boolean link(String url, String pkglisturl, Reporter reporter) throws DocFileIOException {
 199         return link(url, pkglisturl, reporter, true);
 200     }
 201 
 202     /*
 203      * Build the extern package list from given URL or the directory path.
 204      * Flag error if the "-link" or "-linkoffline" option is already used.
 205      *
 206      * @param url        URL or Directory path.
 207      * @param pkglisturl This can be another URL for "package-list" or ordinary
 208      *                   file.
 209      * @param reporter   The <code>DocErrorReporter</code> used to report errors.
 210      * @param linkoffline True if -linkoffline is used and false if -link is used.
 211      * @return true if successful, false otherwise
 212      * @throws DocFileIOException if there is a problem reading a package list file
 213      */
 214     private boolean link(String url, String pkglisturl, Reporter reporter, boolean linkoffline)
 215                 throws DocFileIOException {
 216         this.linkoffline = linkoffline;
 217         try {
 218             url = adjustEndFileSeparator(url);
 219             if (isUrl(pkglisturl)) {
 220                 readPackageListFromURL(url, toURL(adjustEndFileSeparator(pkglisturl)));
 221             } else {
 222                 readPackageListFromFile(url, DocFile.createFileForInput(configuration, pkglisturl));
 223             }
 224             return true;
 225         } catch (Fault f) {
 226             reporter.print(Diagnostic.Kind.WARNING, f.getMessage());
 227             return false;
 228         }
 229     }
 230 
 231     private URL toURL(String url) throws Fault {
 232         try {
 233             return new URL(url);
 234         } catch (MalformedURLException e) {
 235             throw new Fault(configuration.getText("doclet.MalformedURL", url), e);
 236         }
 237     }
 238 
 239     private class Fault extends Exception {
 240         private static final long serialVersionUID = 0;
 241 
 242         Fault(String msg, Exception cause) {
 243             super(msg, cause);
 244         }
 245     }
 246 
 247     /**
 248      * Get the Extern Item object associated with this package name.
 249      *
 250      * @param pkgName Package name.
 251      */
 252     private Item findPackageItem(String pkgName) {
 253         if (packageToItemMap == null) {
 254             return null;
 255         }
 256         return packageToItemMap.get(pkgName);
 257     }
 258 
 259     /**
 260      * If the URL or Directory path is missing end file separator, add that.
 261      */
 262     private String adjustEndFileSeparator(String url) {
 263         return url.endsWith("/") ? url : url + '/';
 264     }
 265 
 266     /**
 267      * Fetch the URL and read the "package-list" file.
 268      *
 269      * @param urlpath        Path to the packages.
 270      * @param pkglisturlpath URL or the path to the "package-list" file.
 271      */
 272     private void readPackageListFromURL(String urlpath, URL pkglisturlpath) throws Fault {
 273         try {
 274             URL link = pkglisturlpath.toURI().resolve(DocPaths.PACKAGE_LIST.getPath()).toURL();
 275             readPackageList(link.openStream(), urlpath, false);
 276         } catch (URISyntaxException | MalformedURLException exc) {
 277             throw new Fault(configuration.getText("doclet.MalformedURL", pkglisturlpath.toString()), exc);
 278         } catch (IOException exc) {
 279             throw new Fault(configuration.getText("doclet.URL_error", pkglisturlpath.toString()), exc);
 280         }
 281     }
 282 
 283     /**
 284      * Read the "package-list" file which is available locally.
 285      *
 286      * @param path URL or directory path to the packages.
 287      * @param pkgListPath Path to the local "package-list" file.
 288      * @throws Fault if an error occurs that can be treated as a warning
 289      * @throws DocFileIOException if there is a problem opening the package list file
 290      */
 291     private void readPackageListFromFile(String path, DocFile pkgListPath)
 292             throws Fault, DocFileIOException {
 293         DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST);
 294         if (! (file.isAbsolute() || linkoffline)){
 295             file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT);
 296         }
 297         try {
 298             if (file.exists() && file.canRead()) {
 299                 boolean pathIsRelative =
 300                         !isUrl(path)
 301                         && !DocFile.createFileForInput(configuration, path).isAbsolute();
 302                 readPackageList(file.openInputStream(), path, pathIsRelative);
 303             } else {
 304                 throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null);
 305             }
 306         } catch (IOException exc) {
 307            throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc);
 308         }
 309     }
 310 
 311     /**
 312      * Read the file "package-list" and for each package name found, create
 313      * Extern object and associate it with the package name in the map.
 314      *
 315      * @param input    InputStream from the "package-list" file.
 316      * @param path     URL or the directory path to the packages.
 317      * @param relative Is path relative?
 318      * @throws IOException if there is a problem reading or closing the stream
 319      */
 320     private void readPackageList(InputStream input, String path, boolean relative)
 321                          throws IOException {
 322         try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
 323             StringBuilder strbuf = new StringBuilder();
 324             int c;
 325             while ((c = in.read()) >= 0) {
 326                 char ch = (char) c;
 327                 if (ch == '\n' || ch == '\r') {
 328                     if (strbuf.length() > 0) {
 329                         String packname = strbuf.toString();
 330                         String packpath = path
 331                                 + packname.replace('.', '/') + '/';
 332                         Item ignore = new Item(packname, packpath, relative);
 333                         strbuf.setLength(0);
 334                     }
 335                 } else {
 336                     strbuf.append(ch);
 337                 }
 338             }
 339         }
 340     }
 341 
 342     public boolean isUrl (String urlCandidate) {
 343         try {
 344             URL ignore = new URL(urlCandidate);
 345             //No exception was thrown, so this must really be a URL.
 346             return true;
 347         } catch (MalformedURLException e) {
 348             //Since exception is thrown, this must be a directory path.
 349             return false;
 350         }
 351     }
 352 }