AbstractIndexWriter.java revision 3233:b5d08bc0d224
1/*
2 * Copyright (c) 1998, 2016, 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
26package jdk.javadoc.internal.doclets.formats.html;
27
28import java.io.*;
29import java.nio.file.*;
30import java.util.*;
31import java.util.zip.*;
32
33import javax.lang.model.element.Element;
34import javax.lang.model.element.ExecutableElement;
35import javax.lang.model.element.PackageElement;
36import javax.lang.model.element.TypeElement;
37import javax.lang.model.util.SimpleElementVisitor9;
38
39import com.sun.source.doctree.DocTree;
40import com.sun.tools.javac.util.DefinedBy;
41import jdk.javadoc.internal.doclets.formats.html.markup.HtmlConstants;
42import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle;
43import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTag;
44import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTree;
45import jdk.javadoc.internal.doclets.formats.html.markup.StringContent;
46import jdk.javadoc.internal.doclets.toolkit.Content;
47import jdk.javadoc.internal.doclets.toolkit.util.DocFile;
48import jdk.javadoc.internal.doclets.toolkit.util.DocPath;
49import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;
50import jdk.javadoc.internal.doclets.toolkit.util.DocletAbortException;
51import jdk.javadoc.internal.doclets.toolkit.util.IndexBuilder;
52
53/**
54 * Generate Index for all the Member Names with Indexing in
55 * Unicode Order. This class is a base class for {@link SingleIndexWriter} and
56 * {@link SplitIndexWriter}. It uses the functionality from
57 * {@link HtmlDocletWriter} to generate the Index Contents.
58 *
59 *  <p><b>This is NOT part of any supported API.
60 *  If you write code that depends on this, you do so at your own risk.
61 *  This code and its internal interfaces are subject to change or
62 *  deletion without notice.</b>
63 *
64 * @see    IndexBuilder
65 * @author Atul M Dambalkar
66 * @author Bhavesh Patel (Modified)
67 */
68public class AbstractIndexWriter extends HtmlDocletWriter {
69
70    /**
71     * The index of all the members with unicode character.
72     */
73    protected IndexBuilder indexbuilder;
74
75    /**
76     * This constructor will be used by {@link SplitIndexWriter}. Initializes
77     * path to this file and relative path from this file.
78     *
79     * @param configuration  The current configuration
80     * @param path       Path to the file which is getting generated.
81     * @param indexbuilder Unicode based Index from {@link IndexBuilder}
82     */
83    protected AbstractIndexWriter(ConfigurationImpl configuration,
84                                  DocPath path,
85                                  IndexBuilder indexbuilder)
86                                  throws IOException {
87        super(configuration, path);
88        this.indexbuilder = indexbuilder;
89    }
90
91    /**
92     * Get the index label for navigation bar.
93     *
94     * @return a content tree for the tree label
95     */
96    protected Content getNavLinkIndex() {
97        Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, indexLabel);
98        return li;
99    }
100
101    /**
102     * Add the member information for the unicode character along with the
103     * list of the members.
104     *
105     * @param uc Unicode for which member list information to be generated
106     * @param memberlist List of members for the unicode character
107     * @param contentTree the content tree to which the information will be added
108     */
109    protected void addContents(Character uc, Collection<? extends Element> memberlist,
110            Content contentTree) {
111        addHeading(uc, contentTree);
112        // Display the list only if there are elements to be displayed.
113        if (!memberlist.isEmpty()) {
114            Content dl = new HtmlTree(HtmlTag.DL);
115            for (Element element : memberlist) {
116                addDescription(dl, element);
117            }
118            contentTree.addContent(dl);
119        }
120    }
121
122    protected void addSearchContents(Character uc, List<SearchIndexItem> searchList,
123            Content contentTree) {
124        addHeading(uc, contentTree);
125        // Display the list only if there are elements to be displayed.
126        if (!searchList.isEmpty()) {
127            Content dl = new HtmlTree(HtmlTag.DL);
128            for (SearchIndexItem sii : searchList) {
129                addDescription(sii, dl);
130            }
131            contentTree.addContent(dl);
132        }
133    }
134
135    protected void addContents(Character uc, List<? extends Element> memberlist,
136            List<SearchIndexItem> searchList, Content contentTree) {
137        addHeading(uc, contentTree);
138        int memberListSize = memberlist.size();
139        int searchListSize = searchList.size();
140        int i = 0;
141        int j = 0;
142        Content dl = new HtmlTree(HtmlTag.DL);
143        while (i < memberListSize && j < searchListSize) {
144            String name = utils.getSimpleName(memberlist.get(i));
145            if (name.compareTo(searchList.get(j).getLabel()) < 0) {
146                addDescription(dl, memberlist.get(i));
147                i++;
148            } else if (name.compareTo(searchList.get(j).getLabel()) > 0) {
149                addDescription(searchList.get(j), dl);
150                j++;
151            } else {
152                addDescription(dl, memberlist.get(i));
153                addDescription(searchList.get(j), dl);
154                j++;
155                i++;
156            }
157        }
158        if (i >= memberListSize) {
159            while (j < searchListSize) {
160                addDescription(searchList.get(j), dl);
161                j++;
162            }
163        }
164        if (j >= searchListSize) {
165            while (i < memberListSize) {
166                addDescription(dl, memberlist.get(i));
167                i++;
168            }
169        }
170        contentTree.addContent(dl);
171    }
172
173    protected void addHeading(Character uc, Content contentTree) {
174        String unicode = uc.toString();
175        contentTree.addContent(getMarkerAnchorForIndex(unicode));
176        Content headContent = new StringContent(unicode);
177        Content heading = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, false,
178                HtmlStyle.title, headContent);
179        contentTree.addContent(heading);
180    }
181
182    protected void addDescription(Content dl, Element element) {
183        SearchIndexItem si = new SearchIndexItem();
184        new SimpleElementVisitor9<Void, Void>() {
185
186            @Override @DefinedBy(DefinedBy.Api.LANGUAGE_MODEL)
187            public Void visitPackage(PackageElement e, Void p) {
188                addDescription(e, dl, si);
189                configuration.packageSearchIndex.add(si);
190                return null;
191            }
192
193            @Override @DefinedBy(DefinedBy.Api.LANGUAGE_MODEL)
194            public Void visitType(TypeElement e, Void p) {
195                addDescription(e, dl, si);
196                configuration.typeSearchIndex.add(si);
197                return null;
198            }
199
200            @Override @DefinedBy(DefinedBy.Api.LANGUAGE_MODEL)
201            protected Void defaultAction(Element e, Void p) {
202                addDescription(e, dl, si);
203                configuration.memberSearchIndex.add(si);
204                return null;
205            }
206
207        }.visit(element);
208    }
209
210    /**
211     * Add one line summary comment for the package.
212     *
213     * @param pkg the package to be documented
214     * @param dlTree the content tree to which the description will be added
215     */
216    protected void addDescription(PackageElement pkg, Content dlTree, SearchIndexItem si) {
217        Content link = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg)));
218        si.setLabel(utils.getPackageName(pkg));
219        si.setCategory(getResource("doclet.Packages").toString());
220        Content dt = HtmlTree.DT(link);
221        dt.addContent(" - ");
222        dt.addContent(getResource("doclet.package"));
223        dt.addContent(" " + utils.getPackageName(pkg));
224        dlTree.addContent(dt);
225        Content dd = new HtmlTree(HtmlTag.DD);
226        addSummaryComment(pkg, dd);
227        dlTree.addContent(dd);
228    }
229
230    /**
231     * Add one line summary comment for the class.
232     *
233     * @param typeElement the class being documented
234     * @param dlTree the content tree to which the description will be added
235     */
236    protected void addDescription(TypeElement typeElement, Content dlTree, SearchIndexItem si) {
237        Content link = getLink(new LinkInfoImpl(configuration,
238                        LinkInfoImpl.Kind.INDEX, typeElement).strong(true));
239        si.setContainingPackage(utils.getPackageName(utils.containingPackage(typeElement)));
240        si.setLabel(utils.getSimpleName(typeElement));
241        si.setCategory(getResource("doclet.Types").toString());
242        Content dt = HtmlTree.DT(link);
243        dt.addContent(" - ");
244        addClassInfo(typeElement, dt);
245        dlTree.addContent(dt);
246        Content dd = new HtmlTree(HtmlTag.DD);
247        addComment(typeElement, dd);
248        dlTree.addContent(dd);
249    }
250
251    /**
252     * Add the classkind (class, interface, exception), error of the class
253     * passed.
254     *
255     * @param te the class being documented
256     * @param contentTree the content tree to which the class info will be added
257     */
258    protected void addClassInfo(TypeElement te, Content contentTree) {
259        contentTree.addContent(getResource("doclet.in",
260                utils.getTypeElementName(te, false),
261                getPackageLink(utils.containingPackage(te),
262                    utils.getPackageName(utils.containingPackage(te)))
263                ));
264    }
265
266    /**
267     * Add description for Class, Field, Method or Constructor.
268     *
269     * @param member the member of the Class Kind
270     * @param dlTree the content tree to which the description will be added
271     * @param si search index item
272     */
273    protected void addDescription(Element member, Content dlTree, SearchIndexItem si) {
274
275        si.setContainingPackage(utils.getPackageName(utils.containingPackage(member)));
276        si.setContainingClass(utils.getSimpleName(utils.getEnclosingTypeElement(member)));
277        String name = utils.getSimpleName(member);
278        if (utils.isExecutableElement(member)) {
279            ExecutableElement ee = (ExecutableElement)member;
280            name = name + utils.flatSignature(ee);
281            si.setLabel(name);
282            if (!((utils.signature(ee)).equals(utils.flatSignature(ee)))) {
283                si.setUrl(getName(getAnchor(ee)));
284            }
285
286        }  else {
287            si.setLabel(name);
288        }
289        si.setCategory(getResource("doclet.Members").toString());
290        Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink,
291                getDocLink(LinkInfoImpl.Kind.INDEX, member, name));
292        Content dt = HtmlTree.DT(span);
293        dt.addContent(" - ");
294        addMemberDesc(member, dt);
295        dlTree.addContent(dt);
296        Content dd = new HtmlTree(HtmlTag.DD);
297        addComment(member, dd);
298        dlTree.addContent(dd);
299    }
300
301    protected void addDescription(SearchIndexItem sii, Content dlTree) {
302        String path = pathToRoot.isEmpty() ? "" : pathToRoot.getPath() + "/";
303        path += sii.getUrl();
304        HtmlTree labelLink = HtmlTree.A(path, new StringContent(sii.getLabel()));
305        Content dt = HtmlTree.DT(HtmlTree.SPAN(HtmlStyle.searchTagLink, labelLink));
306        dt.addContent(" - ");
307        dt.addContent(getResource("doclet.Search_tag_in", sii.getHolder()));
308        dlTree.addContent(dt);
309        Content dd = new HtmlTree(HtmlTag.DD);
310        if (sii.getDescription().isEmpty()) {
311            dd.addContent(getSpace());
312        } else {
313            dd.addContent(sii.getDescription());
314        }
315        dlTree.addContent(dd);
316    }
317
318    /**
319     * Add comment for each element in the index. If the element is deprecated
320     * and it has a @deprecated tag, use that comment. Else if the containing
321     * class for this element is deprecated, then add the word "Deprecated." at
322     * the start and then print the normal comment.
323     *
324     * @param element Index element
325     * @param contentTree the content tree to which the comment will be added
326     */
327    protected void addComment(Element element, Content contentTree) {
328        List<? extends DocTree> tags;
329        Content span = HtmlTree.SPAN(HtmlStyle.deprecatedLabel, deprecatedPhrase);
330        HtmlTree div = new HtmlTree(HtmlTag.DIV);
331        div.addStyle(HtmlStyle.block);
332        if (utils.isDeprecated(element)) {
333            div.addContent(span);
334            tags = utils.getBlockTags(element, DocTree.Kind.DEPRECATED);
335            if (!tags.isEmpty())
336                addInlineDeprecatedComment(element, tags.get(0), div);
337            contentTree.addContent(div);
338        } else {
339            TypeElement encl = utils.getEnclosingTypeElement(element);
340            while (encl != null) {
341                if (utils.isDeprecated(encl)) {
342                    div.addContent(span);
343                    contentTree.addContent(div);
344                    break;
345                }
346                encl = utils.getEnclosingTypeElement(encl);
347            }
348            addSummaryComment(element, contentTree);
349        }
350    }
351
352    /**
353     * Add description about the Static Variable/Method/Constructor for a
354     * member.
355     *
356     * @param member MemberDoc for the member within the Class Kind
357     * @param contentTree the content tree to which the member description will be added
358     */
359    protected void addMemberDesc(Element member, Content contentTree) {
360        TypeElement containing = utils.getEnclosingTypeElement(member);
361        String classdesc = utils.getTypeElementName(containing, true) + " ";
362        if (utils.isField(member)) {
363            Content resource = getResource(utils.isStatic(member)
364                    ? "doclet.Static_variable_in"
365                    : "doclet.Variable_in", classdesc);
366            contentTree.addContent(resource);
367        } else if (utils.isConstructor(member)) {
368            contentTree.addContent(
369                    getResource("doclet.Constructor_for", classdesc));
370        } else if (utils.isMethod(member)) {
371            Content resource = getResource(utils.isStatic(member)
372                    ? "doclet.Static_method_in"
373                    : "doclet.Method_in", classdesc);
374            contentTree.addContent(resource);
375        }
376        addPreQualifiedClassLink(LinkInfoImpl.Kind.INDEX, containing,
377                false, contentTree);
378    }
379
380    /**
381     * Get the marker anchor which will be added to the index documentation tree.
382     *
383     * @param anchorNameForIndex the anchor name attribute for index page
384     * @return a content tree for the marker anchor
385     */
386    public Content getMarkerAnchorForIndex(String anchorNameForIndex) {
387        return getMarkerAnchor(getNameForIndex(anchorNameForIndex), null);
388    }
389
390    /**
391     * Generate a valid HTML name for member index page.
392     *
393     * @param unicode the string that needs to be converted to valid HTML name.
394     * @return a valid HTML name string.
395     */
396    public String getNameForIndex(String unicode) {
397        return "I:" + getName(unicode);
398    }
399
400    protected void createSearchIndexFiles() {
401        createSearchIndexFile(DocPaths.PACKAGE_SEARCH_INDEX_JSON, DocPaths.PACKAGE_SEARCH_INDEX_ZIP,
402                configuration.packageSearchIndex);
403        createSearchIndexFile(DocPaths.TYPE_SEARCH_INDEX_JSON, DocPaths.TYPE_SEARCH_INDEX_ZIP,
404                configuration.typeSearchIndex);
405        createSearchIndexFile(DocPaths.MEMBER_SEARCH_INDEX_JSON, DocPaths.MEMBER_SEARCH_INDEX_ZIP,
406                configuration.memberSearchIndex);
407        createSearchIndexFile(DocPaths.TAG_SEARCH_INDEX_JSON, DocPaths.TAG_SEARCH_INDEX_ZIP,
408                configuration.tagSearchIndex);
409    }
410
411    protected void createSearchIndexFile(DocPath searchIndexFile, DocPath searchIndexZip,
412            List<SearchIndexItem> searchIndex) {
413        if (!searchIndex.isEmpty()) {
414            try {
415                StringBuilder searchVar = new StringBuilder("[");
416                boolean first = true;
417                DocFile searchFile = DocFile.createFileForOutput(configuration, searchIndexFile);
418                Path p = Paths.get(searchFile.getPath());
419                for (SearchIndexItem item : searchIndex) {
420                    if (first) {
421                        searchVar.append(item.toString());
422                        first = false;
423                    } else {
424                        searchVar.append(",").append(item.toString());
425                    }
426                }
427                searchVar.append("]");
428                Files.write(p, searchVar.toString().getBytes());
429                DocFile zipFile = DocFile.createFileForOutput(configuration, searchIndexZip);
430                try (FileOutputStream fos = new FileOutputStream(zipFile.getPath());
431                        ZipOutputStream zos = new ZipOutputStream(fos)) {
432                    zipFile(searchFile.getPath(), searchIndexFile, zos);
433                }
434                Files.delete(p);
435            } catch (IOException ie) {
436                throw new DocletAbortException(ie);
437            }
438        }
439    }
440
441    protected void zipFile(String inputFile, DocPath file, ZipOutputStream zos) {
442        try {
443            try {
444                ZipEntry ze = new ZipEntry(file.getPath());
445                zos.putNextEntry(ze);
446                try (FileInputStream fis = new FileInputStream(new File(inputFile))) {
447                    byte[] buf = new byte[2048];
448                    int len = fis.read(buf);
449                    while (len > 0) {
450                        zos.write(buf, 0, len);
451                        len = fis.read(buf);
452                    }
453                }
454            } finally {
455                zos.closeEntry();
456            }
457        } catch (IOException e) {
458            throw new DocletAbortException(e);
459        }
460    }
461}
462