001    /*
002     * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
003     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004     *
005     * This code is free software; you can redistribute it and/or modify it
006     * under the terms of the GNU General Public License version 2 only, as
007     * published by the Free Software Foundation.  Sun designates this
008     * particular file as subject to the "Classpath" exception as provided
009     * by Sun in the LICENSE file that accompanied this code.
010     *
011     * This code is distributed in the hope that it will be useful, but WITHOUT
012     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013     * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014     * version 2 for more details (a copy is included in the LICENSE file that
015     * accompanied this code).
016     *
017     * You should have received a copy of the GNU General Public License version
018     * 2 along with this work; if not, write to the Free Software Foundation,
019     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020     *
021     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022     * CA 95054 USA or visit www.sun.com if you need additional information or
023     * have any questions.
024     */
025    
026    package com.sun.tools.doclets.internal.toolkit.util;
027    
028    import com.sun.tools.doclets.internal.toolkit.*;
029    
030    import com.sun.javadoc.*;
031    import java.util.Map;
032    import java.util.HashMap;
033    import java.io.*;
034    import java.net.*;
035    
036    /**
037     * Process and manage "-link" and "-linkoffline" to external packages. The
038     * options "-link" and "-linkoffline" both depend on the fact that Javadoc now
039     * generates "package-list"(lists all the packages which are getting
040     * documented) file in the current or the destination directory, while
041     * generating the documentation.
042     *
043     * This code is not part of an API.
044     * It is implementation that is subject to change.
045     * Do not use it as an API
046     *
047     * @author Atul M Dambalkar
048     * @author Robert Field
049     */
050    public class Extern {
051    
052        /**
053         * Map package names onto Extern Item objects.
054         * Lazily initialized.
055         */
056        private Map<String,Item> packageToItemMap;
057    
058        /**
059         * The global configuration information for this run.
060         */
061        private final Configuration configuration;
062    
063        /**
064         * True if we are using -linkoffline and false if -link is used instead.
065         */
066        private boolean linkoffline = false;
067    
068        /**
069         * Stores the info for one external doc set
070         */
071        private class Item {
072    
073            /**
074             * Package name, found in the "package-list" file in the {@link path}.
075             */
076            final String packageName;
077    
078            /**
079             * The URL or the directory path at which the package documentation will be
080             * avaliable.
081             */
082            final String path;
083    
084            /**
085             * If given path is directory path then true else if it is a URL then false.
086             */
087            final boolean relative;
088    
089            /**
090             * Constructor to build a Extern Item object and map it with the package name.
091             * If the same package name is found in the map, then the first mapped
092             * Item object or offline location will be retained.
093             *
094             * @param packagename Package name found in the "package-list" file.
095             * @param path        URL or Directory path from where the "package-list"
096             * file is picked.
097             * @param relative    True if path is URL, false if directory path.
098             */
099            Item(String packageName, String path, boolean relative) {
100                this.packageName = packageName;
101                this.path = path;
102                this.relative = relative;
103                if (packageToItemMap == null) {
104                    packageToItemMap = new HashMap<String,Item>();
105                }
106                if (!packageToItemMap.containsKey(packageName)) { // save the previous
107                    packageToItemMap.put(packageName, this);        // mapped location
108                }
109            }
110    
111            /**
112             * String representation of "this" with packagename and the path.
113             */
114            public String toString() {
115                return packageName + (relative? " -> " : " => ") + path;
116            }
117        }
118    
119        public Extern(Configuration configuration) {
120            this.configuration = configuration;
121        }
122    
123        /**
124         * Determine if a doc item is externally documented.
125         *
126         * @param doc A ProgramElementDoc.
127         */
128        public boolean isExternal(ProgramElementDoc doc) {
129            if (packageToItemMap == null) {
130                return false;
131            }
132            return packageToItemMap.get(doc.containingPackage().name()) != null;
133        }
134    
135        /**
136         * Convert a link to be an external link if appropriate.
137         *
138         * @param pkgName The package name.
139         * @param relativepath    The relative path.
140         * @param link    The link to convert.
141         * @return if external return converted link else return null
142         */
143        public String getExternalLink(String pkgName,
144                                      String relativepath, String link) {
145            Item fnd = findPackageItem(pkgName);
146            if (fnd != null) {
147                String externlink = fnd.path + link;
148                if (fnd.relative) {  // it's a relative path.
149                    return relativepath + externlink;
150                } else {
151                    return externlink;
152                }
153            }
154            return null;
155        }
156    
157        /**
158         * Build the extern package list from given URL or the directory path.
159         * Flag error if the "-link" or "-linkoffline" option is already used.
160         *
161         * @param url        URL or Directory path.
162         * @param pkglisturl This can be another URL for "package-list" or ordinary
163         *                   file.
164         * @param reporter   The <code>DocErrorReporter</code> used to report errors.
165         * @param linkoffline True if -linkoffline isused and false if -link is used.
166         */
167        public boolean url(String url, String pkglisturl,
168                                  DocErrorReporter reporter, boolean linkoffline) {
169            this.linkoffline = linkoffline;
170            String errMsg = composeExternPackageList(url, pkglisturl);
171            if (errMsg != null) {
172                reporter.printWarning(errMsg);
173                return false;
174            } else {
175                return true;
176            }
177        }
178    
179        /**
180         * Get the Extern Item object associated with this package name.
181         *
182         * @param pkgname Package name.
183         */
184        private Item findPackageItem(String pkgName) {
185            if (packageToItemMap == null) {
186                return null;
187            }
188            return packageToItemMap.get(pkgName);
189        }
190    
191        /**
192         * Adjusts the end file separator if it is missing from the URL or the
193         * directory path and depending upon the URL or file path, fetch or
194         * read the "package-list" file.
195         *
196         * @param urlOrDirPath        URL or the directory path.
197         * @param pkgListUrlOrDirPath URL or directory path for the "package-list" file or the "package-list"
198         * file itself.
199         */
200        private String composeExternPackageList(String urlOrDirPath, String pkgListUrlOrDirPath) {
201            urlOrDirPath = adjustEndFileSeparator(urlOrDirPath);
202            pkgListUrlOrDirPath = adjustEndFileSeparator(pkgListUrlOrDirPath);
203            return isUrl(pkgListUrlOrDirPath) ?
204                fetchURLComposeExternPackageList(urlOrDirPath, pkgListUrlOrDirPath) :
205                readFileComposeExternPackageList(urlOrDirPath, pkgListUrlOrDirPath);
206        }
207    
208        /**
209         * If the URL or Directory path is missing end file separator, add that.
210         */
211        private String adjustEndFileSeparator(String url) {
212            String filesep = "/";
213            if (!url.endsWith(filesep)) {
214                url += filesep;
215            }
216            return url;
217        }
218    
219        /**
220         * Fetch the URL and read the "package-list" file.
221         *
222         * @param urlpath        Path to the packages.
223         * @param pkglisturlpath URL or the path to the "package-list" file.
224         */
225        private String fetchURLComposeExternPackageList(String urlpath,
226                                                       String pkglisturlpath) {
227            String link = pkglisturlpath + "package-list";
228            try {
229                readPackageList((new URL(link)).openStream(), urlpath, false);
230            } catch (MalformedURLException exc) {
231                return configuration.getText("doclet.MalformedURL", link);
232            } catch (IOException exc) {
233                return configuration.getText("doclet.URL_error", link);
234            }
235            return null;
236        }
237    
238        /**
239         * Read the "package-list" file which is available locally.
240         *
241         * @param path URL or directory path to the packages.
242         * @param pkgListPath Path to the local "package-list" file.
243         */
244        private String readFileComposeExternPackageList(String path,
245                                                       String pkgListPath) {
246    
247            String link = pkgListPath + "package-list";
248            if (! ((new File(pkgListPath)).isAbsolute() || linkoffline)){
249                link = configuration.destDirName + link;
250            }
251            try {
252                File file = new File(link);
253                if (file.exists() && file.canRead()) {
254                    readPackageList(new FileInputStream(file), path,
255                        ! ((new File(path)).isAbsolute() || isUrl(path)));
256                } else {
257                    return configuration.getText("doclet.File_error", link);
258                }
259            } catch (FileNotFoundException exc) {
260                return configuration.getText("doclet.File_error", link);
261            } catch (IOException exc) {
262                return configuration.getText("doclet.File_error", link);
263            }
264            return null;
265        }
266    
267        /**
268         * Read the file "package-list" and for each package name found, create
269         * Extern object and associate it with the package name in the map.
270         *
271         * @param input    InputStream from the "package-list" file.
272         * @param path     URL or the directory path to the packages.
273         * @param relative Is path relative?
274         */
275        private void readPackageList(InputStream input, String path,
276                                    boolean relative)
277                             throws IOException {
278            BufferedReader in = new BufferedReader(new InputStreamReader(input));
279            StringBuffer strbuf = new StringBuffer();
280            try {
281                int c;
282                while ((c = in.read()) >= 0) {
283                    char ch = (char)c;
284                    if (ch == '\n' || ch == '\r') {
285                        if (strbuf.length() > 0) {
286                            String packname = strbuf.toString();
287                            String packpath = path +
288                                          packname.replace('.', '/') + '/';
289                            new Item(packname, packpath, relative);
290                            strbuf.setLength(0);
291                        }
292                    } else {
293                        strbuf.append(ch);
294                    }
295                }
296            } finally {
297                input.close();
298            }
299        }
300    
301        public boolean isUrl (String urlCandidate) {
302            try {
303                new URL(urlCandidate);
304                //No exception was thrown, so this must really be a URL.
305                return true;
306            } catch (MalformedURLException e) {
307                //Since exception is thrown, this must be a directory path.
308                return false;
309            }
310        }
311    }