View Javadoc
1   /*
2    * Copyright (c) 1997, 2013, 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 com.sun.tools.doclets.internal.toolkit;
27  
28  import java.io.*;
29  import java.util.*;
30  import java.util.regex.Matcher;
31  import java.util.regex.Pattern;
32  
33  import com.sun.javadoc.*;
34  import com.sun.tools.javac.sym.Profiles;
35  import com.sun.tools.javac.jvm.Profile;
36  import com.sun.tools.doclets.internal.toolkit.builders.BuilderFactory;
37  import com.sun.tools.doclets.internal.toolkit.taglets.*;
38  import com.sun.tools.doclets.internal.toolkit.util.*;
39  import javax.tools.JavaFileManager;
40  
41  /**
42   * Configure the output based on the options. Doclets should sub-class
43   * Configuration, to configure and add their own options. This class contains
44   * all user options which are supported by the 1.1 doclet and the standard
45   * doclet.
46   *
47   *  <p><b>This is NOT part of any supported API.
48   *  If you write code that depends on this, you do so at your own risk.
49   *  This code and its internal interfaces are subject to change or
50   *  deletion without notice.</b>
51   *
52   * @author Robert Field.
53   * @author Atul Dambalkar.
54   * @author Jamie Ho
55   */
56  public abstract class Configuration {
57  
58      /**
59       * Exception used to report a problem during setOptions.
60       */
61      public static class Fault extends Exception {
62          private static final long serialVersionUID = 0;
63  
64          Fault(String msg) {
65              super(msg);
66          }
67  
68          Fault(String msg, Exception cause) {
69              super(msg, cause);
70          }
71      }
72  
73      /**
74       * The factory for builders.
75       */
76      protected BuilderFactory builderFactory;
77  
78      /**
79       * The taglet manager.
80       */
81      public TagletManager tagletManager;
82  
83      /**
84       * The path to the builder XML input file.
85       */
86      public String builderXMLPath;
87  
88      /**
89       * The default path to the builder XML.
90       */
91      private static final String DEFAULT_BUILDER_XML = "resources/doclet.xml";
92  
93      /**
94       * The path to Taglets
95       */
96      public String tagletpath = "";
97  
98      /**
99       * This is true if option "-serialwarn" is used. Defualt value is false to
100      * suppress excessive warnings about serial tag.
101      */
102     public boolean serialwarn = false;
103 
104     /**
105      * The specified amount of space between tab stops.
106      */
107     public int sourcetab;
108 
109     public String tabSpaces;
110 
111     /**
112      * True if we should generate browsable sources.
113      */
114     public boolean linksource = false;
115 
116     /**
117      * True if command line option "-nosince" is used. Default value is
118      * false.
119      */
120     public boolean nosince = false;
121 
122     /**
123      * True if we should recursively copy the doc-file subdirectories
124      */
125     public boolean copydocfilesubdirs = false;
126 
127     /**
128      * The META charset tag used for cross-platform viewing.
129      */
130     public String charset = "";
131 
132     /**
133      * True if user wants to add member names as meta keywords.
134      * Set to false because meta keywords are ignored in general
135      * by most Internet search engines.
136      */
137     public boolean keywords = false;
138 
139     /**
140      * The meta tag keywords instance.
141      */
142     public final MetaKeywords metakeywords = new MetaKeywords(this);
143 
144     /**
145      * The list of doc-file subdirectories to exclude
146      */
147     protected Set<String> excludedDocFileDirs;
148 
149     /**
150      * The list of qualifiers to exclude
151      */
152     protected Set<String> excludedQualifiers;
153 
154     /**
155      * The Root of the generated Program Structure from the Doclet API.
156      */
157     public RootDoc root;
158 
159     /**
160      * Destination directory name, in which doclet will generate the entire
161      * documentation. Default is current directory.
162      */
163     public String destDirName = "";
164 
165     /**
166      * Destination directory name, in which doclet will copy the doc-files to.
167      */
168     public String docFileDestDirName = "";
169 
170     /**
171      * Encoding for this document. Default is default encoding for this
172      * platform.
173      */
174     public String docencoding = null;
175 
176     /**
177      * True if user wants to suppress descriptions and tags.
178      */
179     public boolean nocomment = false;
180 
181     /**
182      * Encoding for this document. Default is default encoding for this
183      * platform.
184      */
185     public String encoding = null;
186 
187     /**
188      * Generate author specific information for all the classes if @author
189      * tag is used in the doc comment and if -author option is used.
190      * <code>showauthor</code> is set to true if -author option is used.
191      * Default is don't show author information.
192      */
193     public boolean showauthor = false;
194 
195     /**
196      * Generate documentation for JavaFX getters and setters automatically
197      * by copying it from the appropriate property definition.
198      */
199     public boolean javafx = false;
200 
201     /**
202      * Generate version specific information for the all the classes
203      * if @version tag is used in the doc comment and if -version option is
204      * used. <code>showversion</code> is set to true if -version option is
205      * used.Default is don't show version information.
206      */
207     public boolean showversion = false;
208 
209     /**
210      * Sourcepath from where to read the source files. Default is classpath.
211      *
212      */
213     public String sourcepath = "";
214 
215     /**
216      * Argument for command line option "-Xprofilespath".
217      */
218     public String profilespath = "";
219 
220     /**
221      * Generate profiles documentation if profilespath is set and valid profiles
222      * are present.
223      */
224     public boolean showProfiles = false;
225 
226     /**
227      * Don't generate deprecated API information at all, if -nodeprecated
228      * option is used. <code>nodepracted</code> is set to true if
229      * -nodeprecated option is used. Default is generate deprected API
230      * information.
231      */
232     public boolean nodeprecated = false;
233 
234     /**
235      * The catalog of classes specified on the command-line
236      */
237     public ClassDocCatalog classDocCatalog;
238 
239     /**
240      * Message Retriever for the doclet, to retrieve message from the resource
241      * file for this Configuration, which is common for 1.1 and standard
242      * doclets.
243      *
244      * TODO:  Make this private!!!
245      */
246     public MessageRetriever message = null;
247 
248     /**
249      * True if user wants to suppress time stamp in output.
250      * Default is false.
251      */
252     public boolean notimestamp= false;
253 
254     /**
255      * The package grouping instance.
256      */
257     public final Group group = new Group(this);
258 
259     /**
260      * The tracker of external package links.
261      */
262     public final Extern extern = new Extern(this);
263 
264     /**
265      * Return the build date for the doclet.
266      */
267     public abstract String getDocletSpecificBuildDate();
268 
269     /**
270      * This method should be defined in all those doclets(configurations),
271      * which want to derive themselves from this Configuration. This method
272      * can be used to set its own command line options.
273      *
274      * @param options The array of option names and values.
275      * @throws DocletAbortException
276      */
277     public abstract void setSpecificDocletOptions(String[][] options) throws Fault;
278 
279     /**
280      * Return the doclet specific {@link MessageRetriever}
281      * @return the doclet specific MessageRetriever.
282      */
283     public abstract MessageRetriever getDocletSpecificMsg();
284 
285     /**
286      * A profiles object used to access profiles across various pages.
287      */
288     public Profiles profiles;
289 
290     /**
291      * An map of the profiles to packages.
292      */
293     public Map<String,PackageDoc[]> profilePackages;
294 
295     /**
296      * An array of the packages specified on the command-line merged
297      * with the array of packages that contain the classes specified on the
298      * command-line.  The array is sorted.
299      */
300     public PackageDoc[] packages;
301 
302     /**
303      * Constructor. Constructs the message retriever with resource file.
304      */
305     public Configuration() {
306         message =
307             new MessageRetriever(this,
308             "com.sun.tools.doclets.internal.toolkit.resources.doclets");
309         excludedDocFileDirs = new HashSet<String>();
310         excludedQualifiers = new HashSet<String>();
311         setTabWidth(DocletConstants.DEFAULT_TAB_STOP_LENGTH);
312     }
313 
314     /**
315      * Return the builder factory for this doclet.
316      *
317      * @return the builder factory for this doclet.
318      */
319     public BuilderFactory getBuilderFactory() {
320         if (builderFactory == null) {
321             builderFactory = new BuilderFactory(this);
322         }
323         return builderFactory;
324     }
325 
326     /**
327      * This method should be defined in all those doclets
328      * which want to inherit from this Configuration. This method
329      * should return the number of arguments to the command line
330      * option (including the option name).  For example,
331      * -notimestamp is a single-argument option, so this method would
332      * return 1.
333      *
334      * @param option Command line option under consideration.
335      * @return number of arguments to option (including the
336      * option name). Zero return means option not known.
337      * Negative value means error occurred.
338      */
339     public int optionLength(String option) {
340         option = option.toLowerCase();
341         if (option.equals("-author") ||
342             option.equals("-docfilessubdirs") ||
343             option.equals("-javafx") ||
344             option.equals("-keywords") ||
345             option.equals("-linksource") ||
346             option.equals("-nocomment") ||
347             option.equals("-nodeprecated") ||
348             option.equals("-nosince") ||
349             option.equals("-notimestamp") ||
350             option.equals("-quiet") ||
351             option.equals("-xnodate") ||
352             option.equals("-version")) {
353             return 1;
354         } else if (option.equals("-d") ||
355                    option.equals("-docencoding") ||
356                    option.equals("-encoding") ||
357                    option.equals("-excludedocfilessubdir") ||
358                    option.equals("-link") ||
359                    option.equals("-sourcetab") ||
360                    option.equals("-noqualifier") ||
361                    option.equals("-output") ||
362                    option.equals("-sourcepath") ||
363                    option.equals("-tag") ||
364                    option.equals("-taglet") ||
365                    option.equals("-tagletpath") ||
366                    option.equals("-xprofilespath")) {
367             return 2;
368         } else if (option.equals("-group") ||
369                    option.equals("-linkoffline")) {
370             return 3;
371         } else {
372             return -1;  // indicate we don't know about it
373         }
374     }
375 
376     /**
377      * Perform error checking on the given options.
378      *
379      * @param options  the given options to check.
380      * @param reporter the reporter used to report errors.
381      */
382     public abstract boolean validOptions(String options[][],
383         DocErrorReporter reporter);
384 
385     private void initProfiles() throws IOException {
386         if (profilespath.isEmpty())
387             return;
388 
389         profiles = Profiles.read(new File(profilespath));
390 
391         // Group the packages to be documented by the lowest profile (if any)
392         // in which each appears
393         Map<Profile, List<PackageDoc>> interimResults =
394                 new EnumMap<Profile, List<PackageDoc>>(Profile.class);
395         for (Profile p: Profile.values())
396             interimResults.put(p, new ArrayList<PackageDoc>());
397 
398         for (PackageDoc pkg: packages) {
399             if (nodeprecated && Util.isDeprecated(pkg)) {
400                 continue;
401             }
402             // the getProfile method takes a type name, not a package name,
403             // but isn't particularly fussy about the simple name -- so just use *
404             int i = profiles.getProfile(pkg.name().replace(".", "/") + "/*");
405             Profile p = Profile.lookup(i);
406             if (p != null) {
407                 List<PackageDoc> pkgs = interimResults.get(p);
408                 pkgs.add(pkg);
409             }
410         }
411 
412         // Build the profilePackages structure used by the doclet
413         profilePackages = new HashMap<String,PackageDoc[]>();
414         List<PackageDoc> prev = Collections.<PackageDoc>emptyList();
415         int size;
416         for (Map.Entry<Profile,List<PackageDoc>> e: interimResults.entrySet()) {
417             Profile p = e.getKey();
418             List<PackageDoc> pkgs =  e.getValue();
419             pkgs.addAll(prev); // each profile contains all lower profiles
420             Collections.sort(pkgs);
421             size = pkgs.size();
422             // For a profile, if there are no packages to be documented, do not add
423             // it to profilePackages map.
424             if (size > 0)
425                 profilePackages.put(p.name, pkgs.toArray(new PackageDoc[pkgs.size()]));
426             prev = pkgs;
427         }
428 
429         // Generate profiles documentation if any profile contains any
430         // of the packages to be documented.
431         showProfiles = !prev.isEmpty();
432     }
433 
434     private void initPackageArray() {
435         Set<PackageDoc> set = new HashSet<PackageDoc>(Arrays.asList(root.specifiedPackages()));
436         ClassDoc[] classes = root.specifiedClasses();
437         for (int i = 0; i < classes.length; i++) {
438             set.add(classes[i].containingPackage());
439         }
440         ArrayList<PackageDoc> results = new ArrayList<PackageDoc>(set);
441         Collections.sort(results);
442         packages = results.toArray(new PackageDoc[] {});
443     }
444 
445     /**
446      * Set the command line options supported by this configuration.
447      *
448      * @param options the two dimensional array of options.
449      */
450     public void setOptions(String[][] options) throws Fault {
451         LinkedHashSet<String[]> customTagStrs = new LinkedHashSet<String[]>();
452 
453         // Some options, specifically -link and -linkoffline, require that
454         // the output directory has already been created: so do that first.
455         for (int oi = 0; oi < options.length; ++oi) {
456             String[] os = options[oi];
457             String opt = os[0].toLowerCase();
458             if (opt.equals("-d")) {
459                 destDirName = addTrailingFileSep(os[1]);
460                 docFileDestDirName = destDirName;
461                 ensureOutputDirExists();
462                 break;
463             }
464         }
465 
466         for (int oi = 0; oi < options.length; ++oi) {
467             String[] os = options[oi];
468             String opt = os[0].toLowerCase();
469             if (opt.equals("-docfilessubdirs")) {
470                 copydocfilesubdirs = true;
471             } else if (opt.equals("-docencoding")) {
472                 docencoding = os[1];
473             } else if (opt.equals("-encoding")) {
474                 encoding = os[1];
475             } else if (opt.equals("-author")) {
476                 showauthor = true;
477             } else  if (opt.equals("-javafx")) {
478                 javafx = true;
479             } else if (opt.equals("-nosince")) {
480                 nosince = true;
481             } else if (opt.equals("-version")) {
482                 showversion = true;
483             } else if (opt.equals("-nodeprecated")) {
484                 nodeprecated = true;
485             } else if (opt.equals("-sourcepath")) {
486                 sourcepath = os[1];
487             } else if ((opt.equals("-classpath") || opt.equals("-cp")) &&
488                        sourcepath.length() == 0) {
489                 sourcepath = os[1];
490             } else if (opt.equals("-excludedocfilessubdir")) {
491                 addToSet(excludedDocFileDirs, os[1]);
492             } else if (opt.equals("-noqualifier")) {
493                 addToSet(excludedQualifiers, os[1]);
494             } else if (opt.equals("-linksource")) {
495                 linksource = true;
496             } else if (opt.equals("-sourcetab")) {
497                 linksource = true;
498                 try {
499                     setTabWidth(Integer.parseInt(os[1]));
500                 } catch (NumberFormatException e) {
501                     //Set to -1 so that warning will be printed
502                     //to indicate what is valid argument.
503                     sourcetab = -1;
504                 }
505                 if (sourcetab <= 0) {
506                     message.warning("doclet.sourcetab_warning");
507                     setTabWidth(DocletConstants.DEFAULT_TAB_STOP_LENGTH);
508                 }
509             } else if (opt.equals("-notimestamp")) {
510                 notimestamp = true;
511             } else if (opt.equals("-nocomment")) {
512                 nocomment = true;
513             } else if (opt.equals("-tag") || opt.equals("-taglet")) {
514                 customTagStrs.add(os);
515             } else if (opt.equals("-tagletpath")) {
516                 tagletpath = os[1];
517             }  else if (opt.equals("-xprofilespath")) {
518                 profilespath = os[1];
519             } else if (opt.equals("-keywords")) {
520                 keywords = true;
521             } else if (opt.equals("-serialwarn")) {
522                 serialwarn = true;
523             } else if (opt.equals("-group")) {
524                 group.checkPackageGroups(os[1], os[2]);
525             } else if (opt.equals("-link")) {
526                 String url = os[1];
527                 extern.link(url, url, root, false);
528             } else if (opt.equals("-linkoffline")) {
529                 String url = os[1];
530                 String pkglisturl = os[2];
531                 extern.link(url, pkglisturl, root, true);
532             }
533         }
534         if (sourcepath.length() == 0) {
535             sourcepath = System.getProperty("env.class.path") == null ? "" :
536                 System.getProperty("env.class.path");
537         }
538         if (docencoding == null) {
539             docencoding = encoding;
540         }
541 
542         classDocCatalog = new ClassDocCatalog(root.specifiedClasses(), this);
543         initTagletManager(customTagStrs);
544     }
545 
546     /**
547      * Set the command line options supported by this configuration.
548      *
549      * @throws DocletAbortException
550      */
551     public void setOptions() throws Fault {
552         initPackageArray();
553         setOptions(root.options());
554         try {
555             initProfiles();
556         } catch (Exception e) {
557             throw new DocletAbortException(e);
558         }
559         setSpecificDocletOptions(root.options());
560     }
561 
562     private void ensureOutputDirExists() throws Fault {
563         DocFile destDir = DocFile.createFileForDirectory(this, destDirName);
564         if (!destDir.exists()) {
565             //Create the output directory (in case it doesn't exist yet)
566             root.printNotice(getText("doclet.dest_dir_create", destDirName));
567             destDir.mkdirs();
568         } else if (!destDir.isDirectory()) {
569             throw new Fault(getText(
570                 "doclet.destination_directory_not_directory_0",
571                 destDir.getPath()));
572         } else if (!destDir.canWrite()) {
573             throw new Fault(getText(
574                 "doclet.destination_directory_not_writable_0",
575                 destDir.getPath()));
576         }
577     }
578 
579 
580     /**
581      * Initialize the taglet manager.  The strings to initialize the simple custom tags should
582      * be in the following format:  "[tag name]:[location str]:[heading]".
583      * @param customTagStrs the set two dimensional arrays of strings.  These arrays contain
584      * either -tag or -taglet arguments.
585      */
586     private void initTagletManager(Set<String[]> customTagStrs) {
587         tagletManager = tagletManager == null ?
588             new TagletManager(nosince, showversion, showauthor, javafx, message) :
589             tagletManager;
590         String[] args;
591         for (Iterator<String[]> it = customTagStrs.iterator(); it.hasNext(); ) {
592             args = it.next();
593             if (args[0].equals("-taglet")) {
594                 tagletManager.addCustomTag(args[1], getFileManager(), tagletpath);
595                 continue;
596             }
597             String[] tokens = tokenize(args[1],
598                 TagletManager.SIMPLE_TAGLET_OPT_SEPARATOR, 3);
599             if (tokens.length == 1) {
600                 String tagName = args[1];
601                 if (tagletManager.isKnownCustomTag(tagName)) {
602                     //reorder a standard tag
603                     tagletManager.addNewSimpleCustomTag(tagName, null, "");
604                 } else {
605                     //Create a simple tag with the heading that has the same name as the tag.
606                     StringBuilder heading = new StringBuilder(tagName + ":");
607                     heading.setCharAt(0, Character.toUpperCase(tagName.charAt(0)));
608                     tagletManager.addNewSimpleCustomTag(tagName, heading.toString(), "a");
609                 }
610             } else if (tokens.length == 2) {
611                 //Add simple taglet without heading, probably to excluding it in the output.
612                 tagletManager.addNewSimpleCustomTag(tokens[0], tokens[1], "");
613             } else if (tokens.length >= 3) {
614                 tagletManager.addNewSimpleCustomTag(tokens[0], tokens[2], tokens[1]);
615             } else {
616                 message.error("doclet.Error_invalid_custom_tag_argument", args[1]);
617             }
618         }
619     }
620 
621     /**
622      * Given a string, return an array of tokens.  The separator can be escaped
623      * with the '\' character.  The '\' character may also be escaped by the
624      * '\' character.
625      *
626      * @param s         the string to tokenize.
627      * @param separator the separator char.
628      * @param maxTokens the maximum number of tokens returned.  If the
629      *                  max is reached, the remaining part of s is appended
630      *                  to the end of the last token.
631      *
632      * @return an array of tokens.
633      */
634     private String[] tokenize(String s, char separator, int maxTokens) {
635         List<String> tokens = new ArrayList<String>();
636         StringBuilder  token = new StringBuilder ();
637         boolean prevIsEscapeChar = false;
638         for (int i = 0; i < s.length(); i += Character.charCount(i)) {
639             int currentChar = s.codePointAt(i);
640             if (prevIsEscapeChar) {
641                 // Case 1:  escaped character
642                 token.appendCodePoint(currentChar);
643                 prevIsEscapeChar = false;
644             } else if (currentChar == separator && tokens.size() < maxTokens-1) {
645                 // Case 2:  separator
646                 tokens.add(token.toString());
647                 token = new StringBuilder();
648             } else if (currentChar == '\\') {
649                 // Case 3:  escape character
650                 prevIsEscapeChar = true;
651             } else {
652                 // Case 4:  regular character
653                 token.appendCodePoint(currentChar);
654             }
655         }
656         if (token.length() > 0) {
657             tokens.add(token.toString());
658         }
659         return tokens.toArray(new String[] {});
660     }
661 
662     private void addToSet(Set<String> s, String str){
663         StringTokenizer st = new StringTokenizer(str, ":");
664         String current;
665         while(st.hasMoreTokens()){
666             current = st.nextToken();
667             s.add(current);
668         }
669     }
670 
671     /**
672      * Add a trailing file separator, if not found. Remove superfluous
673      * file separators if any. Preserve the front double file separator for
674      * UNC paths.
675      *
676      * @param path Path under consideration.
677      * @return String Properly constructed path string.
678      */
679     public static String addTrailingFileSep(String path) {
680         String fs = System.getProperty("file.separator");
681         String dblfs = fs + fs;
682         int indexDblfs;
683         while ((indexDblfs = path.indexOf(dblfs, 1)) >= 0) {
684             path = path.substring(0, indexDblfs) +
685                 path.substring(indexDblfs + fs.length());
686         }
687         if (!path.endsWith(fs))
688             path += fs;
689         return path;
690     }
691 
692     /**
693      * This checks for the validity of the options used by the user.
694      * This works exactly like
695      * {@link com.sun.javadoc.Doclet#validOptions(String[][],
696      * DocErrorReporter)}. This will validate the options which are shared
697      * by our doclets. For example, this method will flag an error using
698      * the DocErrorReporter if user has used "-nohelp" and "-helpfile" option
699      * together.
700      *
701      * @param options  options used on the command line.
702      * @param reporter used to report errors.
703      * @return true if all the options are valid.
704      */
705     public boolean generalValidOptions(String options[][],
706             DocErrorReporter reporter) {
707         boolean docencodingfound = false;
708         String encoding = "";
709         for (int oi = 0; oi < options.length; oi++) {
710             String[] os = options[oi];
711             String opt = os[0].toLowerCase();
712             if (opt.equals("-docencoding")) {
713                 docencodingfound = true;
714                 if (!checkOutputFileEncoding(os[1], reporter)) {
715                     return false;
716                 }
717             } else if (opt.equals("-encoding")) {
718                 encoding = os[1];
719             }
720         }
721         if (!docencodingfound && encoding.length() > 0) {
722             if (!checkOutputFileEncoding(encoding, reporter)) {
723                 return false;
724             }
725         }
726         return true;
727     }
728 
729     /**
730      * Check the validity of the given profile. Return false if there are no
731      * valid packages to be documented for the profile.
732      *
733      * @param profileName the profile that needs to be validated.
734      * @return true if the profile has valid packages to be documented.
735      */
736     public boolean shouldDocumentProfile(String profileName) {
737         return profilePackages.containsKey(profileName);
738     }
739 
740     /**
741      * Check the validity of the given Source or Output File encoding on this
742      * platform.
743      *
744      * @param docencoding output file encoding.
745      * @param reporter    used to report errors.
746      */
747     private boolean checkOutputFileEncoding(String docencoding,
748             DocErrorReporter reporter) {
749         OutputStream ost= new ByteArrayOutputStream();
750         OutputStreamWriter osw = null;
751         try {
752             osw = new OutputStreamWriter(ost, docencoding);
753         } catch (UnsupportedEncodingException exc) {
754             reporter.printError(getText("doclet.Encoding_not_supported",
755                 docencoding));
756             return false;
757         } finally {
758             try {
759                 if (osw != null) {
760                     osw.close();
761                 }
762             } catch (IOException exc) {
763             }
764         }
765         return true;
766     }
767 
768     /**
769      * Return true if the given doc-file subdirectory should be excluded and
770      * false otherwise.
771      * @param docfilesubdir the doc-files subdirectory to check.
772      */
773     public boolean shouldExcludeDocFileDir(String docfilesubdir){
774         if (excludedDocFileDirs.contains(docfilesubdir)) {
775             return true;
776         } else {
777             return false;
778         }
779     }
780 
781     /**
782      * Return true if the given qualifier should be excluded and false otherwise.
783      * @param qualifier the qualifier to check.
784      */
785     public boolean shouldExcludeQualifier(String qualifier){
786         if (excludedQualifiers.contains("all") ||
787             excludedQualifiers.contains(qualifier) ||
788             excludedQualifiers.contains(qualifier + ".*")) {
789             return true;
790         } else {
791             int index = -1;
792             while ((index = qualifier.indexOf(".", index + 1)) != -1) {
793                 if (excludedQualifiers.contains(qualifier.substring(0, index + 1) + "*")) {
794                     return true;
795                 }
796             }
797             return false;
798         }
799     }
800 
801     /**
802      * Return the qualified name of the <code>ClassDoc</code> if it's qualifier is not excluded.  Otherwise,
803      * return the unqualified <code>ClassDoc</code> name.
804      * @param cd the <code>ClassDoc</code> to check.
805      */
806     public String getClassName(ClassDoc cd) {
807         PackageDoc pd = cd.containingPackage();
808         if (pd != null && shouldExcludeQualifier(cd.containingPackage().name())) {
809             return cd.name();
810         } else {
811             return cd.qualifiedName();
812         }
813     }
814 
815     public String getText(String key) {
816         try {
817             //Check the doclet specific properties file.
818             return getDocletSpecificMsg().getText(key);
819         } catch (Exception e) {
820             //Check the shared properties file.
821             return message.getText(key);
822         }
823     }
824 
825     public String getText(String key, String a1) {
826         try {
827             //Check the doclet specific properties file.
828             return getDocletSpecificMsg().getText(key, a1);
829         } catch (Exception e) {
830             //Check the shared properties file.
831             return message.getText(key, a1);
832         }
833     }
834 
835     public String getText(String key, String a1, String a2) {
836         try {
837             //Check the doclet specific properties file.
838             return getDocletSpecificMsg().getText(key, a1, a2);
839         } catch (Exception e) {
840             //Check the shared properties file.
841             return message.getText(key, a1, a2);
842         }
843     }
844 
845     public String getText(String key, String a1, String a2, String a3) {
846         try {
847             //Check the doclet specific properties file.
848             return getDocletSpecificMsg().getText(key, a1, a2, a3);
849         } catch (Exception e) {
850             //Check the shared properties file.
851             return message.getText(key, a1, a2, a3);
852         }
853     }
854 
855     public abstract Content newContent();
856 
857     /**
858      * Get the configuration string as a content.
859      *
860      * @param key the key to look for in the configuration file
861      * @return a content tree for the text
862      */
863     public Content getResource(String key) {
864         Content c = newContent();
865         c.addContent(getText(key));
866         return c;
867     }
868 
869     /**
870      * Get the configuration string as a content.
871      *
872      * @param key the key to look for in the configuration file
873      * @param o   string or content argument added to configuration text
874      * @return a content tree for the text
875      */
876     public Content getResource(String key, Object o) {
877         return getResource(key, o, null, null);
878     }
879 
880     /**
881      * Get the configuration string as a content.
882      *
883      * @param key the key to look for in the configuration file
884      * @param o   string or content argument added to configuration text
885      * @return a content tree for the text
886      */
887     public Content getResource(String key, Object o1, Object o2) {
888         return getResource(key, o1, o2, null);
889     }
890 
891     /**
892      * Get the configuration string as a content.
893      *
894      * @param key the key to look for in the configuration file
895      * @param o1  string or content argument added to configuration text
896      * @param o2  string or content argument added to configuration text
897      * @return a content tree for the text
898      */
899     public Content getResource(String key, Object o0, Object o1, Object o2) {
900         Content c = newContent();
901         Pattern p = Pattern.compile("\\{([012])\\}");
902         String text = getText(key);
903         Matcher m = p.matcher(text);
904         int start = 0;
905         while (m.find(start)) {
906             c.addContent(text.substring(start, m.start()));
907 
908             Object o = null;
909             switch (m.group(1).charAt(0)) {
910                 case '0': o = o0; break;
911                 case '1': o = o1; break;
912                 case '2': o = o2; break;
913             }
914 
915             if (o == null) {
916                 c.addContent("{" + m.group(1) + "}");
917             } else if (o instanceof String) {
918                 c.addContent((String) o);
919             } else if (o instanceof Content) {
920                 c.addContent((Content) o);
921             }
922 
923             start = m.end();
924         }
925 
926         c.addContent(text.substring(start));
927         return c;
928     }
929 
930 
931     /**
932      * Return true if the ClassDoc element is getting documented, depending upon
933      * -nodeprecated option and the deprecation information. Return true if
934      * -nodeprecated is not used. Return false if -nodeprecated is used and if
935      * either ClassDoc element is deprecated or the containing package is deprecated.
936      *
937      * @param cd the ClassDoc for which the page generation is checked
938      */
939     public boolean isGeneratedDoc(ClassDoc cd) {
940         if (!nodeprecated) {
941             return true;
942         }
943         return !(Util.isDeprecated(cd) || Util.isDeprecated(cd.containingPackage()));
944     }
945 
946     /**
947      * Return the doclet specific instance of a writer factory.
948      * @return the {@link WriterFactory} for the doclet.
949      */
950     public abstract WriterFactory getWriterFactory();
951 
952     /**
953      * Return the input stream to the builder XML.
954      *
955      * @return the input steam to the builder XML.
956      * @throws FileNotFoundException when the given XML file cannot be found.
957      */
958     public InputStream getBuilderXML() throws IOException {
959         return builderXMLPath == null ?
960             Configuration.class.getResourceAsStream(DEFAULT_BUILDER_XML) :
961             DocFile.createFileForInput(this, builderXMLPath).openInputStream();
962     }
963 
964     /**
965      * Return the Locale for this document.
966      */
967     public abstract Locale getLocale();
968 
969     /**
970      * Return the current file manager.
971      */
972     public abstract JavaFileManager getFileManager();
973 
974     /**
975      * Return the comparator that will be used to sort member documentation.
976      * To no do any sorting, return null.
977      *
978      * @return the {@link java.util.Comparator} used to sort members.
979      */
980     public abstract Comparator<ProgramElementDoc> getMemberComparator();
981 
982     private void setTabWidth(int n) {
983         sourcetab = n;
984         tabSpaces = String.format("%" + n + "s", "");
985     }
986 
987     public abstract boolean showMessage(SourcePosition pos, String key);
988 }