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