file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
FieldWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/FieldWriterImpl.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Writes field documentation in HTML format.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Jamie Ho (rewrite)
* @author Bhavesh Patel (Modified)
*/
public class FieldWriterImpl extends AbstractMemberWriter
implements FieldWriter, MemberSummaryWriter {
public FieldWriterImpl(SubWriterHolderWriter writer, ClassDoc classdoc) {
super(writer, classdoc);
}
public FieldWriterImpl(SubWriterHolderWriter writer) {
super(writer);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(HtmlConstants.START_OF_FIELD_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* {@inheritDoc}
*/
public Content getFieldDetailsTreeHeader(ClassDoc classDoc,
Content memberDetailsTree) {
memberDetailsTree.addContent(HtmlConstants.START_OF_FIELD_DETAILS);
Content fieldDetailsTree = writer.getMemberTreeHeader();
fieldDetailsTree.addContent(writer.getMarkerAnchor("field_detail"));
Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
writer.fieldDetailsLabel);
fieldDetailsTree.addContent(heading);
return fieldDetailsTree;
}
/**
* {@inheritDoc}
*/
public Content getFieldDocTreeHeader(FieldDoc field,
Content fieldDetailsTree) {
fieldDetailsTree.addContent(
writer.getMarkerAnchor(field.name()));
Content fieldDocTree = writer.getMemberTreeHeader();
Content heading = new HtmlTree(HtmlConstants.MEMBER_HEADING);
heading.addContent(field.name());
fieldDocTree.addContent(heading);
return fieldDocTree;
}
/**
* {@inheritDoc}
*/
public Content getSignature(FieldDoc field) {
Content pre = new HtmlTree(HtmlTag.PRE);
writer.addAnnotationInfo(field, pre);
addModifiers(field, pre);
Content fieldlink = new RawHtml(writer.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
field.type())));
pre.addContent(fieldlink);
pre.addContent(" ");
if (configuration().linksource) {
Content fieldName = new StringContent(field.name());
writer.addSrcLink(field, fieldName, pre);
} else {
addName(field.name(), pre);
}
return pre;
}
/**
* {@inheritDoc}
*/
public void addDeprecated(FieldDoc field, Content fieldDocTree) {
addDeprecatedInfo(field, fieldDocTree);
}
/**
* {@inheritDoc}
*/
public void addComments(FieldDoc field, Content fieldDocTree) {
ClassDoc holder = field.containingClass();
if (field.inlineTags().length > 0) {
if (holder.equals(classdoc) ||
(! (holder.isPublic() || Util.isLinkable(holder, configuration())))) {
writer.addInlineComment(field, fieldDocTree);
} else {
Content link = new RawHtml(
writer.getDocLink(LinkInfoImpl.CONTEXT_FIELD_DOC_COPY,
holder, field,
holder.isIncluded() ?
holder.typeName() : holder.qualifiedTypeName(),
false));
Content codeLink = HtmlTree.CODE(link);
Content strong = HtmlTree.STRONG(holder.isClass()?
writer.descfrmClassLabel : writer.descfrmInterfaceLabel);
strong.addContent(writer.getSpace());
strong.addContent(codeLink);
fieldDocTree.addContent(HtmlTree.DIV(HtmlStyle.block, strong));
writer.addInlineComment(field, fieldDocTree);
}
}
}
/**
* {@inheritDoc}
*/
public void addTags(FieldDoc field, Content fieldDocTree) {
writer.addTagsInfo(field, fieldDocTree);
}
/**
* {@inheritDoc}
*/
public Content getFieldDetails(Content fieldDetailsTree) {
return getMemberTree(fieldDetailsTree);
}
/**
* {@inheritDoc}
*/
public Content getFieldDoc(Content fieldDocTree,
boolean isLastContent) {
return getMemberTree(fieldDocTree, isLastContent);
}
/**
* Close the writer.
*/
public void close() throws IOException {
writer.close();
}
public int getMemberKind() {
return VisibleMemberMap.FIELDS;
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Field_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Field_Summary"),
configuration().getText("doclet.fields"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Fields");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Field"),
configuration().getText("doclet.Description"))
};
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor("field_summary"));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
inheritedTree.addContent(writer.getMarkerAnchor(
"fields_inherited_from_class_" + configuration().getClassName(cd)));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
Content classLink = new RawHtml(writer.getPreQualifiedClassLink(
LinkInfoImpl.CONTEXT_MEMBER, cd, false));
Content label = new StringContent(cd.isClass() ?
configuration().getText("doclet.Fields_Inherited_From_Class") :
configuration().getText("doclet.Fields_Inherited_From_Interface"));
Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING,
label);
labelHeading.addContent(writer.getSpace());
labelHeading.addContent(classLink);
inheritedTree.addContent(labelHeading);
}
/**
* {@inheritDoc}
*/
protected void addSummaryLink(int context, ClassDoc cd, ProgramElementDoc member,
Content tdSummary) {
Content strong = HtmlTree.STRONG(new RawHtml(
writer.getDocLink(context, cd , (MemberDoc) member, member.name(), false)));
Content code = HtmlTree.CODE(strong);
tdSummary.addContent(code);
}
/**
* {@inheritDoc}
*/
protected void addInheritedSummaryLink(ClassDoc cd,
ProgramElementDoc member, Content linksTree) {
linksTree.addContent(new RawHtml(
writer.getDocLink(LinkInfoImpl.CONTEXT_MEMBER, cd, (MemberDoc)member,
member.name(), false)));
}
/**
* {@inheritDoc}
*/
protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) {
FieldDoc field = (FieldDoc)member;
addModifierAndType(field, field.type(), tdSummaryType);
}
/**
* {@inheritDoc}
*/
protected Content getDeprecatedLink(ProgramElementDoc member) {
return writer.getDocLink(LinkInfoImpl.CONTEXT_MEMBER,
(MemberDoc) member, ((FieldDoc)member).qualifiedName());
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", (cd == null)?
"field_summary":
"fields_inherited_from_class_" +
configuration().getClassName(cd),
writer.getResource("doclet.navField"));
} else {
return writer.getResource("doclet.navField");
}
}
/**
* {@inheritDoc}
*/
protected void addNavDetailLink(boolean link, Content liNav) {
if (link) {
liNav.addContent(writer.getHyperLink("", "field_detail",
writer.getResource("doclet.navField")));
} else {
liNav.addContent(writer.getResource("doclet.navField"));
}
}
}
| 10,396 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageIndexFrameWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageIndexFrameWriter.java | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Generate the package index for the left-hand frame in the generated output.
* A click on the package name in this frame will update the page in the bottom
* left hand frame with the listing of contents of the clicked package.
*
* @author Atul M Dambalkar
*/
public class PackageIndexFrameWriter extends AbstractPackageIndexWriter {
/**
* Construct the PackageIndexFrameWriter object.
*
* @param filename Name of the package index file to be generated.
*/
public PackageIndexFrameWriter(ConfigurationImpl configuration,
String filename) throws IOException {
super(configuration, filename);
}
/**
* Generate the package index file named "overview-frame.html".
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration) {
PackageIndexFrameWriter packgen;
String filename = "overview-frame.html";
try {
packgen = new PackageIndexFrameWriter(configuration, filename);
packgen.buildPackageIndexFile("doclet.Window_Overview", false);
packgen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* {@inheritDoc}
*/
protected void addPackagesList(PackageDoc[] packages, String text,
String tableSummary, Content body) {
Content heading = HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING, true,
packagesLabel);
Content div = HtmlTree.DIV(HtmlStyle.indexContainer, heading);
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addAttr(HtmlAttr.TITLE, packagesLabel.toString());
for(int i = 0; i < packages.length; i++) {
// Do not list the package if -nodeprecated option is set and the
// package is marked as deprecated.
if (packages[i] != null &&
(!(configuration.nodeprecated && Util.isDeprecated(packages[i])))) {
ul.addContent(getPackage(packages[i]));
}
}
div.addContent(ul);
body.addContent(div);
}
/**
* Gets each package name as a separate link.
*
* @param pd PackageDoc
* @return content for the package link
*/
protected Content getPackage(PackageDoc pd) {
Content packageLinkContent;
Content packageLabel;
if (pd.name().length() > 0) {
packageLabel = getPackageLabel(pd.name());
packageLinkContent = getHyperLink(pathString(pd,
"package-frame.html"), "", packageLabel, "",
"packageFrame");
} else {
packageLabel = new RawHtml("<unnamed package>");
packageLinkContent = getHyperLink("package-frame.html",
"", packageLabel, "", "packageFrame");
}
Content li = HtmlTree.LI(packageLinkContent);
return li;
}
/**
* {@inheritDoc}
*/
protected void addNavigationBarHeader(Content body) {
Content headerContent;
if (configuration.packagesheader.length() > 0) {
headerContent = new RawHtml(replaceDocRootDir(configuration.packagesheader));
} else {
headerContent = new RawHtml(replaceDocRootDir(configuration.header));
}
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.bar, headerContent);
body.addContent(heading);
}
/**
* Do nothing as there is no overview information in this page.
*/
protected void addOverviewHeader(Content body) {
}
/**
* Adds "All Classes" link for the top of the left-hand frame page to the
* documentation tree.
*
* @param body the Content object to which the all classes link should be added
*/
protected void addAllClassesLink(Content body) {
Content linkContent = getHyperLink("allclasses-frame.html", "",
allclassesLabel, "", "packageFrame");
Content div = HtmlTree.DIV(HtmlStyle.indexHeader, linkContent);
body.addContent(div);
}
/**
* {@inheritDoc}
*/
protected void addNavigationBarFooter(Content body) {
Content p = HtmlTree.P(getSpace());
body.addContent(p);
}
}
| 5,951 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ClassUseWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassUseWriter.java | /*
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate class usage information.
*
* @author Robert G. Field
* @author Bhavesh Patel (Modified)
*/
public class ClassUseWriter extends SubWriterHolderWriter {
final ClassDoc classdoc;
Set<PackageDoc> pkgToPackageAnnotations = null;
final Map<String,List<ProgramElementDoc>> pkgToClassTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToClassAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToMethodTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToMethodArgTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToMethodReturnTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToMethodAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToMethodParameterAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToFieldTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToFieldAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToSubclass;
final Map<String,List<ProgramElementDoc>> pkgToSubinterface;
final Map<String,List<ProgramElementDoc>> pkgToImplementingClass;
final Map<String,List<ProgramElementDoc>> pkgToField;
final Map<String,List<ProgramElementDoc>> pkgToMethodReturn;
final Map<String,List<ProgramElementDoc>> pkgToMethodArgs;
final Map<String,List<ProgramElementDoc>> pkgToMethodThrows;
final Map<String,List<ProgramElementDoc>> pkgToConstructorAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToConstructorParameterAnnotations;
final Map<String,List<ProgramElementDoc>> pkgToConstructorArgs;
final Map<String,List<ProgramElementDoc>> pkgToConstructorArgTypeParameter;
final Map<String,List<ProgramElementDoc>> pkgToConstructorThrows;
final SortedSet<PackageDoc> pkgSet;
final MethodWriterImpl methodSubWriter;
final ConstructorWriterImpl constrSubWriter;
final FieldWriterImpl fieldSubWriter;
final NestedClassWriterImpl classSubWriter;
// Summary for various use tables.
final String classUseTableSummary;
final String subclassUseTableSummary;
final String subinterfaceUseTableSummary;
final String fieldUseTableSummary;
final String methodUseTableSummary;
final String constructorUseTableSummary;
/**
* Constructor.
*
* @param filename the file to be generated.
* @throws IOException
* @throws DocletAbortException
*/
public ClassUseWriter(ConfigurationImpl configuration,
ClassUseMapper mapper, String path,
String filename, String relpath,
ClassDoc classdoc) throws IOException {
super(configuration, path, filename, relpath);
this.classdoc = classdoc;
if (mapper.classToPackageAnnotations.containsKey(classdoc.qualifiedName()))
pkgToPackageAnnotations = new HashSet<PackageDoc>(mapper.classToPackageAnnotations.get(classdoc.qualifiedName()));
configuration.currentcd = classdoc;
this.pkgSet = new TreeSet<PackageDoc>();
this.pkgToClassTypeParameter = pkgDivide(mapper.classToClassTypeParam);
this.pkgToClassAnnotations = pkgDivide(mapper.classToClassAnnotations);
this.pkgToMethodTypeParameter = pkgDivide(mapper.classToExecMemberDocTypeParam);
this.pkgToMethodArgTypeParameter = pkgDivide(mapper.classToExecMemberDocArgTypeParam);
this.pkgToFieldTypeParameter = pkgDivide(mapper.classToFieldDocTypeParam);
this.pkgToFieldAnnotations = pkgDivide(mapper.annotationToFieldDoc);
this.pkgToMethodReturnTypeParameter = pkgDivide(mapper.classToExecMemberDocReturnTypeParam);
this.pkgToMethodAnnotations = pkgDivide(mapper.classToExecMemberDocAnnotations);
this.pkgToMethodParameterAnnotations = pkgDivide(mapper.classToExecMemberDocParamAnnotation);
this.pkgToSubclass = pkgDivide(mapper.classToSubclass);
this.pkgToSubinterface = pkgDivide(mapper.classToSubinterface);
this.pkgToImplementingClass = pkgDivide(mapper.classToImplementingClass);
this.pkgToField = pkgDivide(mapper.classToField);
this.pkgToMethodReturn = pkgDivide(mapper.classToMethodReturn);
this.pkgToMethodArgs = pkgDivide(mapper.classToMethodArgs);
this.pkgToMethodThrows = pkgDivide(mapper.classToMethodThrows);
this.pkgToConstructorAnnotations = pkgDivide(mapper.classToConstructorAnnotations);
this.pkgToConstructorParameterAnnotations = pkgDivide(mapper.classToConstructorParamAnnotation);
this.pkgToConstructorArgs = pkgDivide(mapper.classToConstructorArgs);
this.pkgToConstructorArgTypeParameter = pkgDivide(mapper.classToConstructorDocArgTypeParam);
this.pkgToConstructorThrows = pkgDivide(mapper.classToConstructorThrows);
//tmp test
if (pkgSet.size() > 0 &&
mapper.classToPackage.containsKey(classdoc.qualifiedName()) &&
!pkgSet.equals(mapper.classToPackage.get(classdoc.qualifiedName()))) {
configuration.root.printWarning("Internal error: package sets don't match: " + pkgSet + " with: " +
mapper.classToPackage.get(classdoc.qualifiedName()));
}
methodSubWriter = new MethodWriterImpl(this);
constrSubWriter = new ConstructorWriterImpl(this);
fieldSubWriter = new FieldWriterImpl(this);
classSubWriter = new NestedClassWriterImpl(this);
classUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.classes"));
subclassUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.subclasses"));
subinterfaceUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.subinterfaces"));
fieldUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.fields"));
methodUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.methods"));
constructorUseTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.constructors"));
}
/**
* Write out class use pages.
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration,
ClassTree classtree) {
ClassUseMapper mapper = new ClassUseMapper(configuration.root, classtree);
ClassDoc[] classes = configuration.root.classes();
for (int i = 0; i < classes.length; i++) {
// If -nodeprecated option is set and the containing package is marked
// as deprecated, do not generate the class-use page. We will still generate
// the class-use page if the class is marked as deprecated but the containing
// package is not since it could still be linked from that package-use page.
if (!(configuration.nodeprecated &&
Util.isDeprecated(classes[i].containingPackage())))
ClassUseWriter.generate(configuration, mapper, classes[i]);
}
PackageDoc[] pkgs = configuration.packages;
for (int i = 0; i < pkgs.length; i++) {
// If -nodeprecated option is set and the package is marked
// as deprecated, do not generate the package-use page.
if (!(configuration.nodeprecated && Util.isDeprecated(pkgs[i])))
PackageUseWriter.generate(configuration, mapper, pkgs[i]);
}
}
private Map<String,List<ProgramElementDoc>> pkgDivide(Map<String,? extends List<? extends ProgramElementDoc>> classMap) {
Map<String,List<ProgramElementDoc>> map = new HashMap<String,List<ProgramElementDoc>>();
List<? extends ProgramElementDoc> list= classMap.get(classdoc.qualifiedName());
if (list != null) {
Collections.sort(list);
Iterator<? extends ProgramElementDoc> it = list.iterator();
while (it.hasNext()) {
ProgramElementDoc doc = it.next();
PackageDoc pkg = doc.containingPackage();
pkgSet.add(pkg);
List<ProgramElementDoc> inPkg = map.get(pkg.name());
if (inPkg == null) {
inPkg = new ArrayList<ProgramElementDoc>();
map.put(pkg.name(), inPkg);
}
inPkg.add(doc);
}
}
return map;
}
/**
* Generate a class page.
*/
public static void generate(ConfigurationImpl configuration,
ClassUseMapper mapper, ClassDoc classdoc) {
ClassUseWriter clsgen;
String path = DirectoryManager.getDirectoryPath(classdoc.
containingPackage());
path += "class-use" + DirectoryManager.URL_FILE_SEPARATOR;
String filename = classdoc.name() + ".html";
String pkgname = classdoc.containingPackage().name();
pkgname += (pkgname.length() > 0)? ".class-use": "class-use";
String relpath = DirectoryManager.getRelativePath(pkgname);
try {
clsgen = new ClassUseWriter(configuration,
mapper, path, filename,
relpath, classdoc);
clsgen.generateClassUseFile();
clsgen.close();
} catch (IOException exc) {
configuration.standardmessage.
error("doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the class use list.
*/
protected void generateClassUseFile() throws IOException {
Content body = getClassUseHeader();
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.classUseContainer);
if (pkgSet.size() > 0) {
addClassUse(div);
} else {
div.addContent(getResource("doclet.ClassUse_No.usage.of.0",
classdoc.qualifiedName()));
}
body.addContent(div);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Add the class use documentation.
*
* @param contentTree the content tree to which the class use information will be added
*/
protected void addClassUse(Content contentTree) throws IOException {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
if (configuration.packages.length > 1) {
addPackageList(ul);
addPackageAnnotationList(ul);
}
addClassList(ul);
contentTree.addContent(ul);
}
/**
* Add the packages list that use the given class.
*
* @param contentTree the content tree to which the packages list will be added
*/
protected void addPackageList(Content contentTree) throws IOException {
Content table = HtmlTree.TABLE(0, 3, 0, useTableSummary,
getTableCaption(configuration().getText(
"doclet.ClassUse_Packages.that.use.0",
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc,
false)))));
table.addContent(getSummaryTableHeader(packageTableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
Iterator<PackageDoc> it = pkgSet.iterator();
for (int i = 0; it.hasNext(); i++) {
PackageDoc pkg = it.next();
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
addPackageUse(pkg, tr);
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
contentTree.addContent(li);
}
/**
* Add the package annotation list.
*
* @param contentTree the content tree to which the package annotation list will be added
*/
protected void addPackageAnnotationList(Content contentTree) throws IOException {
if ((!classdoc.isAnnotationType()) ||
pkgToPackageAnnotations == null ||
pkgToPackageAnnotations.size() == 0) {
return;
}
Content table = HtmlTree.TABLE(0, 3, 0, useTableSummary,
getTableCaption(configuration().getText(
"doclet.ClassUse_PackageAnnotation",
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc,
false)))));
table.addContent(getSummaryTableHeader(packageTableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
Iterator<PackageDoc> it = pkgToPackageAnnotations.iterator();
for (int i = 0; it.hasNext(); i++) {
PackageDoc pkg = it.next();
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
Content tdFirst = HtmlTree.TD(HtmlStyle.colFirst,
getPackageLink(pkg, new StringContent(pkg.name())));
tr.addContent(tdFirst);
HtmlTree tdLast = new HtmlTree(HtmlTag.TD);
tdLast.addStyle(HtmlStyle.colLast);
addSummaryComment(pkg, tdLast);
tr.addContent(tdLast);
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
contentTree.addContent(li);
}
/**
* Add the class list that use the given class.
*
* @param contentTree the content tree to which the class list will be added
*/
protected void addClassList(Content contentTree) throws IOException {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
for (Iterator<PackageDoc> it = pkgSet.iterator(); it.hasNext();) {
PackageDoc pkg = it.next();
Content li = HtmlTree.LI(HtmlStyle.blockList, getMarkerAnchor(pkg.name()));
Content link = new RawHtml(
configuration.getText("doclet.ClassUse_Uses.of.0.in.1",
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CLASS_USE_HEADER,
classdoc, false)),
getPackageLinkString(pkg, Util.getPackageName(pkg), false)));
Content heading = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING, link);
li.addContent(heading);
addClassUse(pkg, li);
ul.addContent(li);
}
Content li = HtmlTree.LI(HtmlStyle.blockList, ul);
contentTree.addContent(li);
}
/**
* Add the package use information.
*
* @param pkg the package that uses the given class
* @param contentTree the content tree to which the package use information will be added
*/
protected void addPackageUse(PackageDoc pkg, Content contentTree) throws IOException {
Content tdFirst = HtmlTree.TD(HtmlStyle.colFirst,
getHyperLink("", pkg.name(), new StringContent(Util.getPackageName(pkg))));
contentTree.addContent(tdFirst);
HtmlTree tdLast = new HtmlTree(HtmlTag.TD);
tdLast.addStyle(HtmlStyle.colLast);
addSummaryComment(pkg, tdLast);
contentTree.addContent(tdLast);
}
/**
* Add the class use information.
*
* @param pkg the package that uses the given class
* @param contentTree the content tree to which the class use information will be added
*/
protected void addClassUse(PackageDoc pkg, Content contentTree) throws IOException {
String classLink = getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc, false));
String pkgLink = getPackageLinkString(pkg, Util.getPackageName(pkg), false);
classSubWriter.addUseInfo(pkgToClassAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_Annotation", classLink,
pkgLink), classUseTableSummary, contentTree);
classSubWriter.addUseInfo(pkgToClassTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_TypeParameter", classLink,
pkgLink), classUseTableSummary, contentTree);
classSubWriter.addUseInfo(pkgToSubclass.get(pkg.name()),
configuration.getText("doclet.ClassUse_Subclass", classLink,
pkgLink), subclassUseTableSummary, contentTree);
classSubWriter.addUseInfo(pkgToSubinterface.get(pkg.name()),
configuration.getText("doclet.ClassUse_Subinterface", classLink,
pkgLink), subinterfaceUseTableSummary, contentTree);
classSubWriter.addUseInfo(pkgToImplementingClass.get(pkg.name()),
configuration.getText("doclet.ClassUse_ImplementingClass", classLink,
pkgLink), classUseTableSummary, contentTree);
fieldSubWriter.addUseInfo(pkgToField.get(pkg.name()),
configuration.getText("doclet.ClassUse_Field", classLink,
pkgLink), fieldUseTableSummary, contentTree);
fieldSubWriter.addUseInfo(pkgToFieldAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_FieldAnnotations", classLink,
pkgLink), fieldUseTableSummary, contentTree);
fieldSubWriter.addUseInfo(pkgToFieldTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_FieldTypeParameter", classLink,
pkgLink), fieldUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodAnnotations", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodParameterAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodParameterAnnotations", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodTypeParameter", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodReturn.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodReturn", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodReturnTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodReturnTypeParameter", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodArgs.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodArgs", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodArgTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodArgsTypeParameters", classLink,
pkgLink), methodUseTableSummary, contentTree);
methodSubWriter.addUseInfo(pkgToMethodThrows.get(pkg.name()),
configuration.getText("doclet.ClassUse_MethodThrows", classLink,
pkgLink), methodUseTableSummary, contentTree);
constrSubWriter.addUseInfo(pkgToConstructorAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_ConstructorAnnotations", classLink,
pkgLink), constructorUseTableSummary, contentTree);
constrSubWriter.addUseInfo(pkgToConstructorParameterAnnotations.get(pkg.name()),
configuration.getText("doclet.ClassUse_ConstructorParameterAnnotations", classLink,
pkgLink), constructorUseTableSummary, contentTree);
constrSubWriter.addUseInfo(pkgToConstructorArgs.get(pkg.name()),
configuration.getText("doclet.ClassUse_ConstructorArgs", classLink,
pkgLink), constructorUseTableSummary, contentTree);
constrSubWriter.addUseInfo(pkgToConstructorArgTypeParameter.get(pkg.name()),
configuration.getText("doclet.ClassUse_ConstructorArgsTypeParameters", classLink,
pkgLink), constructorUseTableSummary, contentTree);
constrSubWriter.addUseInfo(pkgToConstructorThrows.get(pkg.name()),
configuration.getText("doclet.ClassUse_ConstructorThrows", classLink,
pkgLink), constructorUseTableSummary, contentTree);
}
/**
* Get the header for the class use Listing.
*
* @return a content tree representing the class use header
*/
protected Content getClassUseHeader() {
String cltype = configuration.getText(classdoc.isInterface()?
"doclet.Interface":"doclet.Class");
String clname = classdoc.qualifiedName();
String title = configuration.getText("doclet.Window_ClassUse_Header",
cltype, clname);
Content bodyTree = getBody(true, getWindowTitle(title));
addTop(bodyTree);
addNavLinks(true, bodyTree);
Content headContent = getResource("doclet.ClassUse_Title", cltype, clname);
Content heading = HtmlTree.HEADING(HtmlConstants.CLASS_PAGE_HEADING,
true, HtmlStyle.title, headContent);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
bodyTree.addContent(div);
return bodyTree;
}
/**
* Get this package link.
*
* @return a content tree for the package link
*/
protected Content getNavLinkPackage() {
Content linkContent = getHyperLink("../package-summary.html", "",
packageLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Get class page link.
*
* @return a content tree for the class page link
*/
protected Content getNavLinkClass() {
Content linkContent = new RawHtml(getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS_USE_HEADER, classdoc, "",
configuration.getText("doclet.Class"), false)));
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Get the use link.
*
* @return a content tree for the use link
*/
protected Content getNavLinkClassUse() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, useLabel);
return li;
}
/**
* Get the tree link.
*
* @return a content tree for the tree link
*/
protected Content getNavLinkTree() {
Content linkContent = classdoc.containingPackage().isIncluded() ?
getHyperLink("../package-tree.html", "", treeLabel) :
getHyperLink(relativePath + "overview-tree.html", "", treeLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
}
| 24,810 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlDocletWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.internal.toolkit.taglets.*;
/**
* Class for the Html Format Code Generation specific to JavaDoc.
* This Class contains methods related to the Html Code Generation which
* are used extensively while generating the entire documentation.
*
* @since 1.2
* @author Atul M Dambalkar
* @author Robert Field
* @author Bhavesh Patel (Modified)
*/
public class HtmlDocletWriter extends HtmlDocWriter {
/**
* Relative path from the file getting generated to the destination
* directory. For example, if the file getting generated is
* "java/lang/Object.html", then the relative path string is "../../".
* This string can be empty if the file getting generated is in
* the destination directory.
*/
public String relativePath = "";
/**
* Same as relativepath, but normalized to never be empty or
* end with a slash.
*/
public String relativepathNoSlash = "";
/**
* Platform-dependent directory path from the current or the
* destination directory to the file getting generated.
* Used when creating the file.
* For example, if the file getting generated is
* "java/lang/Object.html", then the path string is "java/lang".
*/
public String path = "";
/**
* Name of the file getting generated. If the file getting generated is
* "java/lang/Object.html", then the filename is "Object.html".
*/
public String filename = "";
/**
* The display length used for indentation while generating the class page.
*/
public int displayLength = 0;
/**
* The global configuration information for this run.
*/
public ConfigurationImpl configuration;
/**
* To check whether annotation heading is printed or not.
*/
protected boolean printedAnnotationHeading = false;
/**
* Constructor to construct the HtmlStandardWriter object.
*
* @param filename File to be generated.
*/
public HtmlDocletWriter(ConfigurationImpl configuration,
String filename) throws IOException {
super(configuration, filename);
this.configuration = configuration;
this.filename = filename;
}
/**
* Constructor to construct the HtmlStandardWriter object.
*
* @param path Platform-dependent {@link #path} used when
* creating file.
* @param filename Name of file to be generated.
* @param relativePath Value for the variable {@link #relativePath}.
*/
public HtmlDocletWriter(ConfigurationImpl configuration,
String path, String filename,
String relativePath) throws IOException {
super(configuration, path, filename);
this.configuration = configuration;
this.path = path;
this.relativePath = relativePath;
this.relativepathNoSlash =
DirectoryManager.getPathNoTrailingSlash(this.relativePath);
this.filename = filename;
}
/**
* Replace {@docRoot} tag used in options that accept HTML text, such
* as -header, -footer, -top and -bottom, and when converting a relative
* HREF where commentTagsToString inserts a {@docRoot} where one was
* missing. (Also see DocRootTaglet for {@docRoot} tags in doc
* comments.)
* <p>
* Replace {@docRoot} tag in htmlstr with the relative path to the
* destination directory from the directory where the file is being
* written, looping to handle all such tags in htmlstr.
* <p>
* For example, for "-d docs" and -header containing {@docRoot}, when
* the HTML page for source file p/C1.java is being generated, the
* {@docRoot} tag would be inserted into the header as "../",
* the relative path from docs/p/ to docs/ (the document root).
* <p>
* Note: This doc comment was written with '&#064;' representing '@'
* to prevent the inline tag from being interpreted.
*/
public String replaceDocRootDir(String htmlstr) {
// Return if no inline tags exist
int index = htmlstr.indexOf("{@");
if (index < 0) {
return htmlstr;
}
String lowerHtml = htmlstr.toLowerCase();
// Return index of first occurrence of {@docroot}
// Note: {@docRoot} is not case sensitive when passed in w/command line option
index = lowerHtml.indexOf("{@docroot}", index);
if (index < 0) {
return htmlstr;
}
StringBuilder buf = new StringBuilder();
int previndex = 0;
while (true) {
if (configuration.docrootparent.length() > 0) {
// Search for lowercase version of {@docRoot}/..
index = lowerHtml.indexOf("{@docroot}/..", previndex);
// If next {@docRoot}/.. pattern not found, append rest of htmlstr and exit loop
if (index < 0) {
buf.append(htmlstr.substring(previndex));
break;
}
// If next {@docroot}/.. pattern found, append htmlstr up to start of tag
buf.append(htmlstr.substring(previndex, index));
previndex = index + 13; // length for {@docroot}/.. string
// Insert docrootparent absolute path where {@docRoot}/.. was located
buf.append(configuration.docrootparent);
// Append slash if next character is not a slash
if (previndex < htmlstr.length() && htmlstr.charAt(previndex) != '/') {
buf.append(DirectoryManager.URL_FILE_SEPARATOR);
}
} else {
// Search for lowercase version of {@docRoot}
index = lowerHtml.indexOf("{@docroot}", previndex);
// If next {@docRoot} tag not found, append rest of htmlstr and exit loop
if (index < 0) {
buf.append(htmlstr.substring(previndex));
break;
}
// If next {@docroot} tag found, append htmlstr up to start of tag
buf.append(htmlstr.substring(previndex, index));
previndex = index + 10; // length for {@docroot} string
// Insert relative path where {@docRoot} was located
buf.append(relativepathNoSlash);
// Append slash if next character is not a slash
if (relativepathNoSlash.length() > 0 && previndex < htmlstr.length() &&
htmlstr.charAt(previndex) != '/') {
buf.append(DirectoryManager.URL_FILE_SEPARATOR);
}
}
}
return buf.toString();
}
/**
* Print Html Hyper Link, with target frame. This
* link will only appear if page is not in a frame.
*
* @param link String name of the file.
* @param where Position in the file
* @param target Name of the target frame.
* @param label Tag for the link.
* @param strong Whether the label should be strong or not?
*/
public void printNoFramesTargetHyperLink(String link, String where,
String target, String label,
boolean strong) {
script();
println(" <!--");
println(" if(window==top) {");
println(" document.writeln('"
+ getHyperLinkString(link, where, label, strong, "", "", target) + "');");
println(" }");
println(" //-->");
scriptEnd();
noScript();
println(" " + getHyperLinkString(link, where, label, strong, "", "", target));
noScriptEnd();
println(DocletConstants.NL);
}
/**
* Get the script to show or hide the All classes link.
*
* @param id id of the element to show or hide
* @return a content tree for the script
*/
public Content getAllClassesLinkScript(String id) {
HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
script.addAttr(HtmlAttr.TYPE, "text/javascript");
String scriptCode = "<!--" + DocletConstants.NL +
" allClassesLink = document.getElementById(\"" + id + "\");" + DocletConstants.NL +
" if(window==top) {" + DocletConstants.NL +
" allClassesLink.style.display = \"block\";" + DocletConstants.NL +
" }" + DocletConstants.NL +
" else {" + DocletConstants.NL +
" allClassesLink.style.display = \"none\";" + DocletConstants.NL +
" }" + DocletConstants.NL +
" //-->" + DocletConstants.NL;
Content scriptContent = new RawHtml(scriptCode);
script.addContent(scriptContent);
Content div = HtmlTree.DIV(script);
return div;
}
/**
* Add method information.
*
* @param method the method to be documented
* @param dl the content tree to which the method information will be added
*/
private void addMethodInfo(MethodDoc method, Content dl) {
ClassDoc[] intfacs = method.containingClass().interfaces();
MethodDoc overriddenMethod = method.overriddenMethod();
// Check whether there is any implementation or overridden info to be
// printed. If no overridden or implementation info needs to be
// printed, do not print this section.
if ((intfacs.length > 0 &&
new ImplementedMethods(method, this.configuration).build().length > 0) ||
overriddenMethod != null) {
MethodWriterImpl.addImplementsInfo(this, method, dl);
if (overriddenMethod != null) {
MethodWriterImpl.addOverridden(this,
method.overriddenType(), overriddenMethod, dl);
}
}
}
/**
* Adds the tags information.
*
* @param doc the doc for which the tags will be generated
* @param htmltree the documentation tree to which the tags will be added
*/
protected void addTagsInfo(Doc doc, Content htmltree) {
if (configuration.nocomment) {
return;
}
Content dl = new HtmlTree(HtmlTag.DL);
if (doc instanceof MethodDoc) {
addMethodInfo((MethodDoc) doc, dl);
}
TagletOutputImpl output = new TagletOutputImpl("");
TagletWriter.genTagOuput(configuration.tagletManager, doc,
configuration.tagletManager.getCustomTags(doc),
getTagletWriterInstance(false), output);
String outputString = output.toString().trim();
if (!outputString.isEmpty()) {
Content resultString = new RawHtml(outputString);
dl.addContent(resultString);
}
htmltree.addContent(dl);
}
/**
* Check whether there are any tags for Serialization Overview
* section to be printed.
*
* @param field the FieldDoc object to check for tags.
* @return true if there are tags to be printed else return false.
*/
protected boolean hasSerializationOverviewTags(FieldDoc field) {
TagletOutputImpl output = new TagletOutputImpl("");
TagletWriter.genTagOuput(configuration.tagletManager, field,
configuration.tagletManager.getCustomTags(field),
getTagletWriterInstance(false), output);
return (!output.toString().trim().isEmpty());
}
/**
* Returns a TagletWriter that knows how to write HTML.
*
* @return a TagletWriter that knows how to write HTML.
*/
public TagletWriter getTagletWriterInstance(boolean isFirstSentence) {
return new TagletWriterImpl(this, isFirstSentence);
}
protected void printTagsInfoHeader() {
dl();
}
protected void printTagsInfoFooter() {
dlEnd();
}
/**
* Get Package link, with target frame.
*
* @param pd The link will be to the "package-summary.html" page for this package
* @param target name of the target frame
* @param label tag for the link
* @return a content for the target package link
*/
public Content getTargetPackageLink(PackageDoc pd, String target,
Content label) {
return getHyperLink(pathString(pd, "package-summary.html"), "", label, "", target);
}
/**
* Print the html file header. Also print Html page title and stylesheet
* default properties.
*
* @param title String window title to go in the <TITLE> tag
* @param metakeywords Array of String keywords for META tag. Each element
* of the array is assigned to a separate META tag.
* Pass in null for no array.
* @param includeScript boolean true if printing windowtitle script.
* False for files that appear in the left-hand frames.
*/
public void printHtmlHeader(String title, String[] metakeywords,
boolean includeScript) {
println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 " +
"Transitional//EN\" " +
"\"http://www.w3.org/TR/html4/loose.dtd\">");
println("<!--NewPage-->");
html();
head();
if (! configuration.notimestamp) {
print("<!-- Generated by javadoc (build " + ConfigurationImpl.BUILD_DATE + ") on ");
print(today());
println(" -->");
}
if (configuration.charset.length() > 0) {
println("<META http-equiv=\"Content-Type\" content=\"text/html; "
+ "charset=" + configuration.charset + "\">");
}
if ( configuration.windowtitle.length() > 0 ) {
title += " (" + configuration.windowtitle + ")";
}
title(title);
println(title);
titleEnd();
println("");
if (! configuration.notimestamp) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
println("<META NAME=\"date\" "
+ "CONTENT=\"" + dateFormat.format(new Date()) + "\">");
}
if ( metakeywords != null ) {
for ( int i=0; i < metakeywords.length; i++ ) {
println("<META NAME=\"keywords\" "
+ "CONTENT=\"" + metakeywords[i] + "\">");
}
}
println("");
printStyleSheetProperties();
println("");
// Don't print windowtitle script for overview-frame, allclasses-frame
// and package-frame
if (includeScript) {
printWinTitleScript(title);
}
println("");
headEnd();
println("");
body("white", includeScript);
}
/**
* Generates the HTML document tree and prints it out.
*
* @param metakeywords Array of String keywords for META tag. Each element
* of the array is assigned to a separate META tag.
* Pass in null for no array
* @param includeScript true if printing windowtitle script
* false for files that appear in the left-hand frames
* @param body the body htmltree to be included in the document
*/
public void printHtmlDocument(String[] metakeywords, boolean includeScript,
Content body) {
Content htmlDocType = DocType.Transitional();
Content htmlComment = new Comment(configuration.getText("doclet.New_Page"));
Content head = new HtmlTree(HtmlTag.HEAD);
if (!configuration.notimestamp) {
Content headComment = new Comment("Generated by javadoc (version " +
ConfigurationImpl.BUILD_DATE + ") on " + today());
head.addContent(headComment);
}
if (configuration.charset.length() > 0) {
Content meta = HtmlTree.META("Content-Type", "text/html",
configuration.charset);
head.addContent(meta);
}
head.addContent(getTitle());
if (!configuration.notimestamp) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Content meta = HtmlTree.META("date", dateFormat.format(new Date()));
head.addContent(meta);
}
if (metakeywords != null) {
for (int i=0; i < metakeywords.length; i++) {
Content meta = HtmlTree.META("keywords", metakeywords[i]);
head.addContent(meta);
}
}
head.addContent(getStyleSheetProperties());
Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
head, body);
Content htmlDocument = new HtmlDocument(htmlDocType,
htmlComment, htmlTree);
print(htmlDocument.toString());
}
/**
* Get the window title.
*
* @param title the title string to construct the complete window title
* @return the window title string
*/
public String getWindowTitle(String title) {
if (configuration.windowtitle.length() > 0) {
title += " (" + configuration.windowtitle + ")";
}
return title;
}
/**
* Print user specified header and the footer.
*
* @param header if true print the user provided header else print the
* user provided footer.
*/
public void printUserHeaderFooter(boolean header) {
em();
if (header) {
print(replaceDocRootDir(configuration.header));
} else {
if (configuration.footer.length() != 0) {
print(replaceDocRootDir(configuration.footer));
} else {
print(replaceDocRootDir(configuration.header));
}
}
emEnd();
}
/**
* Get user specified header and the footer.
*
* @param header if true print the user provided header else print the
* user provided footer.
*/
public Content getUserHeaderFooter(boolean header) {
String content;
if (header) {
content = replaceDocRootDir(configuration.header);
} else {
if (configuration.footer.length() != 0) {
content = replaceDocRootDir(configuration.footer);
} else {
content = replaceDocRootDir(configuration.header);
}
}
Content rawContent = new RawHtml(content);
Content em = HtmlTree.EM(rawContent);
return em;
}
/**
* Print the user specified top.
*/
public void printTop() {
print(replaceDocRootDir(configuration.top));
hr();
}
/**
* Adds the user specified top.
*
* @param body the content tree to which user specified top will be added
*/
public void addTop(Content body) {
Content top = new RawHtml(replaceDocRootDir(configuration.top));
body.addContent(top);
}
/**
* Print the user specified bottom.
*/
public void printBottom() {
hr();
print(replaceDocRootDir(configuration.bottom));
}
/**
* Adds the user specified bottom.
*
* @param body the content tree to which user specified bottom will be added
*/
public void addBottom(Content body) {
Content bottom = new RawHtml(replaceDocRootDir(configuration.bottom));
Content small = HtmlTree.SMALL(bottom);
Content p = HtmlTree.P(HtmlStyle.legalCopy, small);
body.addContent(p);
}
/**
* Print the navigation bar for the Html page at the top and and the bottom.
*
* @param header If true print navigation bar at the top of the page else
* print the nevigation bar at the bottom.
*/
protected void navLinks(boolean header) {
println("");
if (!configuration.nonavbar) {
if (header) {
println(DocletConstants.NL + "<!-- ========= START OF TOP NAVBAR ======= -->");
anchor("navbar_top");
println();
print(getHyperLinkString("", "skip-navbar_top", "", false, "",
configuration.getText("doclet.Skip_navigation_links"), ""));
} else {
println(DocletConstants.NL + "<!-- ======= START OF BOTTOM NAVBAR ====== -->");
anchor("navbar_bottom");
println();
print(getHyperLinkString("", "skip-navbar_bottom", "", false, "",
configuration.getText("doclet.Skip_navigation_links"), ""));
}
table(0, "100%", 1, 0);
tr();
tdColspanBgcolorStyle(2, "#EEEEFF", "NavBarCell1");
println("");
if (header) {
anchor("navbar_top_firstrow");
} else {
anchor("navbar_bottom_firstrow");
}
table(0, 0, 3);
print(" ");
trAlignVAlign("center", "top");
if (configuration.createoverview) {
navLinkContents();
}
if (configuration.packages.length == 1) {
navLinkPackage(configuration.packages[0]);
} else if (configuration.packages.length > 1) {
navLinkPackage();
}
navLinkClass();
if(configuration.classuse) {
navLinkClassUse();
}
if(configuration.createtree) {
navLinkTree();
}
if(!(configuration.nodeprecated ||
configuration.nodeprecatedlist)) {
navLinkDeprecated();
}
if(configuration.createindex) {
navLinkIndex();
}
if (!configuration.nohelp) {
navLinkHelp();
}
print(" ");
trEnd();
tableEnd();
tdEnd();
tdAlignVAlignRowspan("right", "top", 3);
printUserHeaderFooter(header);
tdEnd();
trEnd();
println("");
tr();
tdBgcolorStyle("white", "NavBarCell2");
font("-2");
space();
navLinkPrevious();
space();
println("");
space();
navLinkNext();
fontEnd();
tdEnd();
tdBgcolorStyle("white", "NavBarCell2");
font("-2");
print(" ");
navShowLists();
print(" ");
space();
println("");
space();
navHideLists(filename);
print(" ");
space();
println("");
space();
navLinkClassIndex();
fontEnd();
tdEnd();
trEnd();
printSummaryDetailLinks();
tableEnd();
if (header) {
aName("skip-navbar_top");
aEnd();
println(DocletConstants.NL + "<!-- ========= END OF TOP NAVBAR ========= -->");
} else {
aName("skip-navbar_bottom");
aEnd();
println(DocletConstants.NL + "<!-- ======== END OF BOTTOM NAVBAR ======= -->");
}
println("");
}
}
/**
* Adds the navigation bar for the Html page at the top and and the bottom.
*
* @param header If true print navigation bar at the top of the page else
* @param body the HtmlTree to which the nav links will be added
*/
protected void addNavLinks(boolean header, Content body) {
if (!configuration.nonavbar) {
String allClassesId = "allclasses_";
HtmlTree navDiv = new HtmlTree(HtmlTag.DIV);
if (header) {
body.addContent(HtmlConstants.START_OF_TOP_NAVBAR);
navDiv.addStyle(HtmlStyle.topNav);
allClassesId += "navbar_top";
Content a = getMarkerAnchor("navbar_top");
navDiv.addContent(a);
Content skipLinkContent = getHyperLink("",
"skip-navbar_top", HtmlTree.EMPTY, configuration.getText(
"doclet.Skip_navigation_links"), "");
navDiv.addContent(skipLinkContent);
} else {
body.addContent(HtmlConstants.START_OF_BOTTOM_NAVBAR);
navDiv.addStyle(HtmlStyle.bottomNav);
allClassesId += "navbar_bottom";
Content a = getMarkerAnchor("navbar_bottom");
navDiv.addContent(a);
Content skipLinkContent = getHyperLink("",
"skip-navbar_bottom", HtmlTree.EMPTY, configuration.getText(
"doclet.Skip_navigation_links"), "");
navDiv.addContent(skipLinkContent);
}
if (header) {
navDiv.addContent(getMarkerAnchor("navbar_top_firstrow"));
} else {
navDiv.addContent(getMarkerAnchor("navbar_bottom_firstrow"));
}
HtmlTree navList = new HtmlTree(HtmlTag.UL);
navList.addStyle(HtmlStyle.navList);
navList.addAttr(HtmlAttr.TITLE, "Navigation");
if (configuration.createoverview) {
navList.addContent(getNavLinkContents());
}
if (configuration.packages.length == 1) {
navList.addContent(getNavLinkPackage(configuration.packages[0]));
} else if (configuration.packages.length > 1) {
navList.addContent(getNavLinkPackage());
}
navList.addContent(getNavLinkClass());
if(configuration.classuse) {
navList.addContent(getNavLinkClassUse());
}
if(configuration.createtree) {
navList.addContent(getNavLinkTree());
}
if(!(configuration.nodeprecated ||
configuration.nodeprecatedlist)) {
navList.addContent(getNavLinkDeprecated());
}
if(configuration.createindex) {
navList.addContent(getNavLinkIndex());
}
if (!configuration.nohelp) {
navList.addContent(getNavLinkHelp());
}
navDiv.addContent(navList);
Content aboutDiv = HtmlTree.DIV(HtmlStyle.aboutLanguage, getUserHeaderFooter(header));
navDiv.addContent(aboutDiv);
body.addContent(navDiv);
Content ulNav = HtmlTree.UL(HtmlStyle.navList, getNavLinkPrevious());
ulNav.addContent(getNavLinkNext());
Content subDiv = HtmlTree.DIV(HtmlStyle.subNav, ulNav);
Content ulFrames = HtmlTree.UL(HtmlStyle.navList, getNavShowLists());
ulFrames.addContent(getNavHideLists(filename));
subDiv.addContent(ulFrames);
HtmlTree ulAllClasses = HtmlTree.UL(HtmlStyle.navList, getNavLinkClassIndex());
ulAllClasses.addAttr(HtmlAttr.ID, allClassesId.toString());
subDiv.addContent(ulAllClasses);
subDiv.addContent(getAllClassesLinkScript(allClassesId.toString()));
addSummaryDetailLinks(subDiv);
if (header) {
subDiv.addContent(getMarkerAnchor("skip-navbar_top"));
body.addContent(subDiv);
body.addContent(HtmlConstants.END_OF_TOP_NAVBAR);
} else {
subDiv.addContent(getMarkerAnchor("skip-navbar_bottom"));
body.addContent(subDiv);
body.addContent(HtmlConstants.END_OF_BOTTOM_NAVBAR);
}
}
}
/**
* Print the word "NEXT" to indicate that no link is available. Override
* this method to customize next link.
*/
protected void navLinkNext() {
navLinkNext(null);
}
/**
* Get the word "NEXT" to indicate that no link is available. Override
* this method to customize next link.
*
* @return a content tree for the link
*/
protected Content getNavLinkNext() {
return getNavLinkNext(null);
}
/**
* Print the word "PREV" to indicate that no link is available. Override
* this method to customize prev link.
*/
protected void navLinkPrevious() {
navLinkPrevious(null);
}
/**
* Get the word "PREV" to indicate that no link is available. Override
* this method to customize prev link.
*
* @return a content tree for the link
*/
protected Content getNavLinkPrevious() {
return getNavLinkPrevious(null);
}
/**
* Do nothing. This is the default method.
*/
protected void printSummaryDetailLinks() {
}
/**
* Do nothing. This is the default method.
*/
protected void addSummaryDetailLinks(Content navDiv) {
}
/**
* Print link to the "overview-summary.html" page.
*/
protected void navLinkContents() {
navCellStart();
printHyperLink(relativePath + "overview-summary.html", "",
configuration.getText("doclet.Overview"), true, "NavBarFont1");
navCellEnd();
}
/**
* Get link to the "overview-summary.html" page.
*
* @return a content tree for the link
*/
protected Content getNavLinkContents() {
Content linkContent = getHyperLink(relativePath +
"overview-summary.html", "", overviewLabel, "", "");
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Description for a cell in the navigation bar.
*/
protected void navCellStart() {
print(" ");
tdBgcolorStyle("#EEEEFF", "NavBarCell1");
print(" ");
}
/**
* Description for a cell in the navigation bar, but with reverse
* high-light effect.
*/
protected void navCellRevStart() {
print(" ");
tdBgcolorStyle("#FFFFFF", "NavBarCell1Rev");
print(" ");
space();
}
/**
* Closing tag for navigation bar cell.
*/
protected void navCellEnd() {
space();
tdEnd();
}
/**
* Print link to the "package-summary.html" page for the package passed.
*
* @param pkg Package to which link will be generated.
*/
protected void navLinkPackage(PackageDoc pkg) {
navCellStart();
printPackageLink(pkg, configuration.getText("doclet.Package"), true,
"NavBarFont1");
navCellEnd();
}
/**
* Get link to the "package-summary.html" page for the package passed.
*
* @param pkg Package to which link will be generated
* @return a content tree for the link
*/
protected Content getNavLinkPackage(PackageDoc pkg) {
Content linkContent = getPackageLink(pkg,
packageLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Print the word "Package" in the navigation bar cell, to indicate that
* link is not available here.
*/
protected void navLinkPackage() {
navCellStart();
fontStyle("NavBarFont1");
printText("doclet.Package");
fontEnd();
navCellEnd();
}
/**
* Get the word "Package" , to indicate that link is not available here.
*
* @return a content tree for the link
*/
protected Content getNavLinkPackage() {
Content li = HtmlTree.LI(packageLabel);
return li;
}
/**
* Print the word "Use" in the navigation bar cell, to indicate that link
* is not available.
*/
protected void navLinkClassUse() {
navCellStart();
fontStyle("NavBarFont1");
printText("doclet.navClassUse");
fontEnd();
navCellEnd();
}
/**
* Get the word "Use", to indicate that link is not available.
*
* @return a content tree for the link
*/
protected Content getNavLinkClassUse() {
Content li = HtmlTree.LI(useLabel);
return li;
}
/**
* Print link for previous file.
*
* @param prev File name for the prev link.
*/
public void navLinkPrevious(String prev) {
String tag = configuration.getText("doclet.Prev");
if (prev != null) {
printHyperLink(prev, "", tag, true) ;
} else {
print(tag);
}
}
/**
* Get link for previous file.
*
* @param prev File name for the prev link
* @return a content tree for the link
*/
public Content getNavLinkPrevious(String prev) {
Content li;
if (prev != null) {
li = HtmlTree.LI(getHyperLink(prev, "", prevLabel, "", ""));
}
else
li = HtmlTree.LI(prevLabel);
return li;
}
/**
* Print link for next file. If next is null, just print the label
* without linking it anywhere.
*
* @param next File name for the next link.
*/
public void navLinkNext(String next) {
String tag = configuration.getText("doclet.Next");
if (next != null) {
printHyperLink(next, "", tag, true);
} else {
print(tag);
}
}
/**
* Get link for next file. If next is null, just print the label
* without linking it anywhere.
*
* @param next File name for the next link
* @return a content tree for the link
*/
public Content getNavLinkNext(String next) {
Content li;
if (next != null) {
li = HtmlTree.LI(getHyperLink(next, "", nextLabel, "", ""));
}
else
li = HtmlTree.LI(nextLabel);
return li;
}
/**
* Print "FRAMES" link, to switch to the frame version of the output.
*
* @param link File to be linked, "index.html".
*/
protected void navShowLists(String link) {
print(getHyperLinkString(link + "?" + path + filename, "",
configuration.getText("doclet.FRAMES"), true, "", "", "_top"));
}
/**
* Get "FRAMES" link, to switch to the frame version of the output.
*
* @param link File to be linked, "index.html"
* @return a content tree for the link
*/
protected Content getNavShowLists(String link) {
Content framesContent = getHyperLink(link + "?" + path +
filename, "", framesLabel, "", "_top");
Content li = HtmlTree.LI(framesContent);
return li;
}
/**
* Print "FRAMES" link, to switch to the frame version of the output.
*/
protected void navShowLists() {
navShowLists(relativePath + "index.html");
}
/**
* Get "FRAMES" link, to switch to the frame version of the output.
*
* @return a content tree for the link
*/
protected Content getNavShowLists() {
return getNavShowLists(relativePath + "index.html");
}
/**
* Print "NO FRAMES" link, to switch to the non-frame version of the output.
*
* @param link File to be linked.
*/
protected void navHideLists(String link) {
print(getHyperLinkString(link, "", configuration.getText("doclet.NO_FRAMES"),
true, "", "", "_top"));
}
/**
* Get "NO FRAMES" link, to switch to the non-frame version of the output.
*
* @param link File to be linked
* @return a content tree for the link
*/
protected Content getNavHideLists(String link) {
Content noFramesContent = getHyperLink(link, "", noframesLabel, "", "_top");
Content li = HtmlTree.LI(noFramesContent);
return li;
}
/**
* Print "Tree" link in the navigation bar. If there is only one package
* specified on the command line, then the "Tree" link will be to the
* only "package-tree.html" file otherwise it will be to the
* "overview-tree.html" file.
*/
protected void navLinkTree() {
navCellStart();
PackageDoc[] packages = configuration.root.specifiedPackages();
if (packages.length == 1 && configuration.root.specifiedClasses().length == 0) {
printHyperLink(pathString(packages[0], "package-tree.html"), "",
configuration.getText("doclet.Tree"), true, "NavBarFont1");
} else {
printHyperLink(relativePath + "overview-tree.html", "",
configuration.getText("doclet.Tree"), true, "NavBarFont1");
}
navCellEnd();
}
/**
* Get "Tree" link in the navigation bar. If there is only one package
* specified on the command line, then the "Tree" link will be to the
* only "package-tree.html" file otherwise it will be to the
* "overview-tree.html" file.
*
* @return a content tree for the link
*/
protected Content getNavLinkTree() {
Content treeLinkContent;
PackageDoc[] packages = configuration.root.specifiedPackages();
if (packages.length == 1 && configuration.root.specifiedClasses().length == 0) {
treeLinkContent = getHyperLink(pathString(packages[0],
"package-tree.html"), "", treeLabel,
"", "");
} else {
treeLinkContent = getHyperLink(relativePath + "overview-tree.html",
"", treeLabel, "", "");
}
Content li = HtmlTree.LI(treeLinkContent);
return li;
}
/**
* Get the overview tree link for the main tree.
*
* @param label the label for the link
* @return a content tree for the link
*/
protected Content getNavLinkMainTree(String label) {
Content mainTreeContent = getHyperLink(relativePath + "overview-tree.html",
new StringContent(label));
Content li = HtmlTree.LI(mainTreeContent);
return li;
}
/**
* Print the word "Class" in the navigation bar cell, to indicate that
* class link is not available.
*/
protected void navLinkClass() {
navCellStart();
fontStyle("NavBarFont1");
printText("doclet.Class");
fontEnd();
navCellEnd();
}
/**
* Get the word "Class", to indicate that class link is not available.
*
* @return a content tree for the link
*/
protected Content getNavLinkClass() {
Content li = HtmlTree.LI(classLabel);
return li;
}
/**
* Print "Deprecated" API link in the navigation bar.
*/
protected void navLinkDeprecated() {
navCellStart();
printHyperLink(relativePath + "deprecated-list.html", "",
configuration.getText("doclet.navDeprecated"), true, "NavBarFont1");
navCellEnd();
}
/**
* Get "Deprecated" API link in the navigation bar.
*
* @return a content tree for the link
*/
protected Content getNavLinkDeprecated() {
Content linkContent = getHyperLink(relativePath +
"deprecated-list.html", "", deprecatedLabel, "", "");
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Print link for generated index. If the user has used "-splitindex"
* command line option, then link to file "index-files/index-1.html" is
* generated otherwise link to file "index-all.html" is generated.
*/
protected void navLinkClassIndex() {
printNoFramesTargetHyperLink(relativePath +
AllClassesFrameWriter.OUTPUT_FILE_NAME_NOFRAMES,
"", "", configuration.getText("doclet.All_Classes"), true);
}
/**
* Get link for generated index. If the user has used "-splitindex"
* command line option, then link to file "index-files/index-1.html" is
* generated otherwise link to file "index-all.html" is generated.
*
* @return a content tree for the link
*/
protected Content getNavLinkClassIndex() {
Content allClassesContent = getHyperLink(relativePath +
AllClassesFrameWriter.OUTPUT_FILE_NAME_NOFRAMES, "",
allclassesLabel, "", "");
Content li = HtmlTree.LI(allClassesContent);
return li;
}
/**
* Print link for generated class index.
*/
protected void navLinkIndex() {
navCellStart();
printHyperLink(relativePath +
(configuration.splitindex?
DirectoryManager.getPath("index-files") +
fileseparator: "") +
(configuration.splitindex?
"index-1.html" : "index-all.html"), "",
configuration.getText("doclet.Index"), true, "NavBarFont1");
navCellEnd();
}
/**
* Get link for generated class index.
*
* @return a content tree for the link
*/
protected Content getNavLinkIndex() {
Content linkContent = getHyperLink(relativePath +(configuration.splitindex?
DirectoryManager.getPath("index-files") + fileseparator: "") +
(configuration.splitindex?"index-1.html" : "index-all.html"), "",
indexLabel, "", "");
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Print help file link. If user has provided a help file, then generate a
* link to the user given file, which is already copied to current or
* destination directory.
*/
protected void navLinkHelp() {
String helpfilenm = configuration.helpfile;
if (helpfilenm.equals("")) {
helpfilenm = "help-doc.html";
} else {
int lastsep;
if ((lastsep = helpfilenm.lastIndexOf(File.separatorChar)) != -1) {
helpfilenm = helpfilenm.substring(lastsep + 1);
}
}
navCellStart();
printHyperLink(relativePath + helpfilenm, "",
configuration.getText("doclet.Help"), true, "NavBarFont1");
navCellEnd();
}
/**
* Get help file link. If user has provided a help file, then generate a
* link to the user given file, which is already copied to current or
* destination directory.
*
* @return a content tree for the link
*/
protected Content getNavLinkHelp() {
String helpfilenm = configuration.helpfile;
if (helpfilenm.equals("")) {
helpfilenm = "help-doc.html";
} else {
int lastsep;
if ((lastsep = helpfilenm.lastIndexOf(File.separatorChar)) != -1) {
helpfilenm = helpfilenm.substring(lastsep + 1);
}
}
Content linkContent = getHyperLink(relativePath + helpfilenm, "",
helpLabel, "", "");
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Print the word "Detail" in the navigation bar. No link is available.
*/
protected void navDetail() {
printText("doclet.Detail");
}
/**
* Print the word "Summary" in the navigation bar. No link is available.
*/
protected void navSummary() {
printText("doclet.Summary");
}
/**
* Print the Html table tag for the index summary tables. The table tag
* printed is
* <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
*/
public void tableIndexSummary() {
table(1, "100%", 3, 0);
}
/**
* Print the Html table tag for the index summary tables.
*
* @param summary the summary for the table tag summary attribute.
*/
public void tableIndexSummary(String summary) {
table(1, "100%", 3, 0, summary);
}
/**
* Same as {@link #tableIndexSummary()}.
*/
public void tableIndexDetail() {
table(1, "100%", 3, 0);
}
/**
* Print Html tag for table elements. The tag printed is
* <TD ALIGN="right" VALIGN="top" WIDTH="1%">.
*/
public void tdIndex() {
print("<TD ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\">");
}
/**
* Print table caption.
*/
public void tableCaptionStart() {
captionStyle("TableCaption");
}
/**
* Print table sub-caption.
*/
public void tableSubCaptionStart() {
captionStyle("TableSubCaption");
}
/**
* Print table caption end tags.
*/
public void tableCaptionEnd() {
captionEnd();
}
/**
* Print summary table header.
*/
public void summaryTableHeader(String[] header, String scope) {
tr();
for ( int i=0; i < header.length; i++ ) {
thScopeNoWrap("TableHeader", scope);
print(header[i]);
thEnd();
}
trEnd();
}
/**
* Get summary table header.
*
* @param header the header for the table
* @param scope the scope of the headers
* @return a content tree for the header
*/
public Content getSummaryTableHeader(String[] header, String scope) {
Content tr = new HtmlTree(HtmlTag.TR);
int size = header.length;
Content tableHeader;
if (size == 1) {
tableHeader = new StringContent(header[0]);
tr.addContent(HtmlTree.TH(HtmlStyle.colOne, scope, tableHeader));
return tr;
}
for (int i = 0; i < size; i++) {
tableHeader = new StringContent(header[i]);
if(i == 0)
tr.addContent(HtmlTree.TH(HtmlStyle.colFirst, scope, tableHeader));
else if(i == (size - 1))
tr.addContent(HtmlTree.TH(HtmlStyle.colLast, scope, tableHeader));
else
tr.addContent(HtmlTree.TH(scope, tableHeader));
}
return tr;
}
/**
* Get table caption.
*
* @param rawText the caption for the table which could be raw Html
* @return a content tree for the caption
*/
public Content getTableCaption(String rawText) {
Content title = new RawHtml(rawText);
Content captionSpan = HtmlTree.SPAN(title);
Content space = getSpace();
Content tabSpan = HtmlTree.SPAN(HtmlStyle.tabEnd, space);
Content caption = HtmlTree.CAPTION(captionSpan);
caption.addContent(tabSpan);
return caption;
}
/**
* Get the marker anchor which will be added to the documentation tree.
*
* @param anchorName the anchor name attribute
* @return a content tree for the marker anchor
*/
public Content getMarkerAnchor(String anchorName) {
return getMarkerAnchor(anchorName, null);
}
/**
* Get the marker anchor which will be added to the documentation tree.
*
* @param anchorName the anchor name attribute
* @param anchorContent the content that should be added to the anchor
* @return a content tree for the marker anchor
*/
public Content getMarkerAnchor(String anchorName, Content anchorContent) {
if (anchorContent == null)
anchorContent = new Comment(" ");
Content markerAnchor = HtmlTree.A_NAME(anchorName, anchorContent);
return markerAnchor;
}
/**
* Returns a packagename content.
*
* @param packageDoc the package to check
* @return package name content
*/
public Content getPackageName(PackageDoc packageDoc) {
return packageDoc == null || packageDoc.name().length() == 0 ?
defaultPackageLabel :
getPackageLabel(packageDoc.name());
}
/**
* Returns a package name label.
*
* @param parsedName the package name
* @return the package name content
*/
public Content getPackageLabel(String packageName) {
return new StringContent(packageName);
}
/**
* Add package deprecation information to the documentation tree
*
* @param deprPkgs list of deprecated packages
* @param headingKey the caption for the deprecated package table
* @param tableSummary the summary for the deprecated package table
* @param tableHeader table headers for the deprecated package table
* @param contentTree the content tree to which the deprecated package table will be added
*/
protected void addPackageDeprecatedAPI(List<Doc> deprPkgs, String headingKey,
String tableSummary, String[] tableHeader, Content contentTree) {
if (deprPkgs.size() > 0) {
Content table = HtmlTree.TABLE(0, 3, 0, tableSummary,
getTableCaption(configuration().getText(headingKey)));
table.addContent(getSummaryTableHeader(tableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
for (int i = 0; i < deprPkgs.size(); i++) {
PackageDoc pkg = (PackageDoc) deprPkgs.get(i);
HtmlTree td = HtmlTree.TD(HtmlStyle.colOne,
getPackageLink(pkg, getPackageName(pkg)));
if (pkg.tags("deprecated").length > 0) {
addInlineDeprecatedComment(pkg, pkg.tags("deprecated")[0], td);
}
HtmlTree tr = HtmlTree.TR(td);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
Content ul = HtmlTree.UL(HtmlStyle.blockList, li);
contentTree.addContent(ul);
}
}
/**
* Prine table header information about color, column span and the font.
*
* @param color Background color.
* @param span Column span.
*/
public void tableHeaderStart(String color, int span) {
trBgcolorStyle(color, "TableHeadingColor");
thAlignColspan("left", span);
font("+2");
}
/**
* Print table header for the inherited members summary tables. Print the
* background color information.
*
* @param color Background color.
*/
public void tableInheritedHeaderStart(String color) {
trBgcolorStyle(color, "TableSubHeadingColor");
thAlign("left");
}
/**
* Print "Use" table header. Print the background color and the column span.
*
* @param color Background color.
*/
public void tableUseInfoHeaderStart(String color) {
trBgcolorStyle(color, "TableSubHeadingColor");
thAlignColspan("left", 2);
}
/**
* Print table header with the background color with default column span 2.
*
* @param color Background color.
*/
public void tableHeaderStart(String color) {
tableHeaderStart(color, 2);
}
/**
* Print table header with the column span, with the default color #CCCCFF.
*
* @param span Column span.
*/
public void tableHeaderStart(int span) {
tableHeaderStart("#CCCCFF", span);
}
/**
* Print table header with default column span 2 and default color #CCCCFF.
*/
public void tableHeaderStart() {
tableHeaderStart(2);
}
/**
* Print table header end tags for font, column and row.
*/
public void tableHeaderEnd() {
fontEnd();
thEnd();
trEnd();
}
/**
* Print table header end tags in inherited tables for column and row.
*/
public void tableInheritedHeaderEnd() {
thEnd();
trEnd();
}
/**
* Print the summary table row cell attribute width.
*
* @param width Width of the table cell.
*/
public void summaryRow(int width) {
if (width != 0) {
tdWidth(width + "%");
} else {
td();
}
}
/**
* Print the summary table row cell end tag.
*/
public void summaryRowEnd() {
tdEnd();
}
/**
* Print the heading in Html <H2> format.
*
* @param str The Header string.
*/
public void printIndexHeading(String str) {
h2();
print(str);
h2End();
}
/**
* Print Html tag <FRAMESET=arg>.
*
* @param arg Argument for the tag.
*/
public void frameSet(String arg) {
println("<FRAMESET " + arg + ">");
}
/**
* Print Html closing tag </FRAMESET>.
*/
public void frameSetEnd() {
println("</FRAMESET>");
}
/**
* Print Html tag <FRAME=arg>.
*
* @param arg Argument for the tag.
*/
public void frame(String arg) {
println("<FRAME " + arg + ">");
}
/**
* Print Html closing tag </FRAME>.
*/
public void frameEnd() {
println("</FRAME>");
}
/**
* Return path to the class page for a classdoc. For example, the class
* name is "java.lang.Object" and if the current file getting generated is
* "java/io/File.html", then the path string to the class, returned is
* "../../java/lang.Object.html".
*
* @param cd Class to which the path is requested.
*/
protected String pathToClass(ClassDoc cd) {
return pathString(cd.containingPackage(), cd.name() + ".html");
}
/**
* Return the path to the class page for a classdoc. Works same as
* {@link #pathToClass(ClassDoc)}.
*
* @param cd Class to which the path is requested.
* @param name Name of the file(doesn't include path).
*/
protected String pathString(ClassDoc cd, String name) {
return pathString(cd.containingPackage(), name);
}
/**
* Return path to the given file name in the given package. So if the name
* passed is "Object.html" and the name of the package is "java.lang", and
* if the relative path is "../.." then returned string will be
* "../../java/lang/Object.html"
*
* @param pd Package in which the file name is assumed to be.
* @param name File name, to which path string is.
*/
protected String pathString(PackageDoc pd, String name) {
StringBuffer buf = new StringBuffer(relativePath);
buf.append(DirectoryManager.getPathToPackage(pd, name));
return buf.toString();
}
/**
* Print the link to the given package.
*
* @param pkg the package to link to.
* @param label the label for the link.
* @param isStrong true if the label should be strong.
*/
public void printPackageLink(PackageDoc pkg, String label, boolean isStrong) {
print(getPackageLinkString(pkg, label, isStrong));
}
/**
* Print the link to the given package.
*
* @param pkg the package to link to.
* @param label the label for the link.
* @param isStrong true if the label should be strong.
* @param style the font of the package link label.
*/
public void printPackageLink(PackageDoc pkg, String label, boolean isStrong,
String style) {
print(getPackageLinkString(pkg, label, isStrong, style));
}
/**
* Return the link to the given package.
*
* @param pkg the package to link to.
* @param label the label for the link.
* @param isStrong true if the label should be strong.
* @return the link to the given package.
*/
public String getPackageLinkString(PackageDoc pkg, String label,
boolean isStrong) {
return getPackageLinkString(pkg, label, isStrong, "");
}
/**
* Return the link to the given package.
*
* @param pkg the package to link to.
* @param label the label for the link.
* @param isStrong true if the label should be strong.
* @param style the font of the package link label.
* @return the link to the given package.
*/
public String getPackageLinkString(PackageDoc pkg, String label, boolean isStrong,
String style) {
boolean included = pkg != null && pkg.isIncluded();
if (! included) {
PackageDoc[] packages = configuration.packages;
for (int i = 0; i < packages.length; i++) {
if (packages[i].equals(pkg)) {
included = true;
break;
}
}
}
if (included || pkg == null) {
return getHyperLinkString(pathString(pkg, "package-summary.html"),
"", label, isStrong, style);
} else {
String crossPkgLink = getCrossPackageLink(Util.getPackageName(pkg));
if (crossPkgLink != null) {
return getHyperLinkString(crossPkgLink, "", label, isStrong, style);
} else {
return label;
}
}
}
/**
* Return the link to the given package.
*
* @param pkg the package to link to.
* @param label the label for the link.
* @return a content tree for the package link.
*/
public Content getPackageLink(PackageDoc pkg, Content label) {
boolean included = pkg != null && pkg.isIncluded();
if (! included) {
PackageDoc[] packages = configuration.packages;
for (int i = 0; i < packages.length; i++) {
if (packages[i].equals(pkg)) {
included = true;
break;
}
}
}
if (included || pkg == null) {
return getHyperLink(pathString(pkg, "package-summary.html"),
"", label);
} else {
String crossPkgLink = getCrossPackageLink(Util.getPackageName(pkg));
if (crossPkgLink != null) {
return getHyperLink(crossPkgLink, "", label);
} else {
return label;
}
}
}
public String italicsClassName(ClassDoc cd, boolean qual) {
String name = (qual)? cd.qualifiedName(): cd.name();
return (cd.isInterface())? italicsText(name): name;
}
public void printSrcLink(ProgramElementDoc d, String label) {
if (d == null) {
return;
}
ClassDoc cd = d.containingClass();
if (cd == null) {
//d must be a class doc since in has no containing class.
cd = (ClassDoc) d;
}
String href = relativePath + DocletConstants.SOURCE_OUTPUT_DIR_NAME
+ DirectoryManager.getDirectoryPath(cd.containingPackage())
+ cd.name() + ".html#" + SourceToHTMLConverter.getAnchorName(d);
printHyperLink(href, "", label, true);
}
/**
* Add the link to the content tree.
*
* @param doc program element doc for which the link will be added
* @param label label for the link
* @param htmltree the content tree to which the link will be added
*/
public void addSrcLink(ProgramElementDoc doc, Content label, Content htmltree) {
if (doc == null) {
return;
}
ClassDoc cd = doc.containingClass();
if (cd == null) {
//d must be a class doc since in has no containing class.
cd = (ClassDoc) doc;
}
String href = relativePath + DocletConstants.SOURCE_OUTPUT_DIR_NAME
+ DirectoryManager.getDirectoryPath(cd.containingPackage())
+ cd.name() + ".html#" + SourceToHTMLConverter.getAnchorName(doc);
Content linkContent = getHyperLink(href, "", label, "", "");
htmltree.addContent(linkContent);
}
/**
* Return the link to the given class.
*
* @param linkInfo the information about the link.
*
* @return the link for the given class.
*/
public String getLink(LinkInfoImpl linkInfo) {
LinkFactoryImpl factory = new LinkFactoryImpl(this);
String link = ((LinkOutputImpl) factory.getLinkOutput(linkInfo)).toString();
displayLength += linkInfo.displayLength;
return link;
}
/**
* Return the type parameters for the given class.
*
* @param linkInfo the information about the link.
* @return the type for the given class.
*/
public String getTypeParameterLinks(LinkInfoImpl linkInfo) {
LinkFactoryImpl factory = new LinkFactoryImpl(this);
return ((LinkOutputImpl)
factory.getTypeParameterLinks(linkInfo, false)).toString();
}
/**
* Print the link to the given class.
*/
public void printLink(LinkInfoImpl linkInfo) {
print(getLink(linkInfo));
}
/*************************************************************
* Return a class cross link to external class documentation.
* The name must be fully qualified to determine which package
* the class is in. The -link option does not allow users to
* link to external classes in the "default" package.
*
* @param qualifiedClassName the qualified name of the external class.
* @param refMemName the name of the member being referenced. This should
* be null or empty string if no member is being referenced.
* @param label the label for the external link.
* @param strong true if the link should be strong.
* @param style the style of the link.
* @param code true if the label should be code font.
*/
public String getCrossClassLink(String qualifiedClassName, String refMemName,
String label, boolean strong, String style,
boolean code) {
String className = "",
packageName = qualifiedClassName == null ? "" : qualifiedClassName;
int periodIndex;
while((periodIndex = packageName.lastIndexOf('.')) != -1) {
className = packageName.substring(periodIndex + 1, packageName.length()) +
(className.length() > 0 ? "." + className : "");
String defaultLabel = code ? getCode() + className + getCodeEnd() : className;
packageName = packageName.substring(0, periodIndex);
if (getCrossPackageLink(packageName) != null) {
//The package exists in external documentation, so link to the external
//class (assuming that it exists). This is definitely a limitation of
//the -link option. There are ways to determine if an external package
//exists, but no way to determine if the external class exists. We just
//have to assume that it does.
return getHyperLinkString(
configuration.extern.getExternalLink(packageName, relativePath,
className + ".html?is-external=true"),
refMemName == null ? "" : refMemName,
label == null || label.length() == 0 ? defaultLabel : label,
strong, style,
configuration.getText("doclet.Href_Class_Or_Interface_Title", packageName),
"");
}
}
return null;
}
public boolean isClassLinkable(ClassDoc cd) {
if (cd.isIncluded()) {
return configuration.isGeneratedDoc(cd);
}
return configuration.extern.isExternal(cd);
}
public String getCrossPackageLink(String pkgName) {
return configuration.extern.getExternalLink(pkgName, relativePath,
"package-summary.html?is-external=true");
}
/**
* Get the class link.
*
* @param context the id of the context where the link will be added
* @param cd the class doc to link to
* @return a content tree for the link
*/
public Content getQualifiedClassLink(int context, ClassDoc cd) {
return new RawHtml(getLink(new LinkInfoImpl(context, cd,
configuration.getClassName(cd), "")));
}
/**
* Add the class link.
*
* @param context the id of the context where the link will be added
* @param cd the class doc to link to
* @param contentTree the content tree to which the link will be added
*/
public void addPreQualifiedClassLink(int context, ClassDoc cd, Content contentTree) {
addPreQualifiedClassLink(context, cd, false, contentTree);
}
/**
* Retrieve the class link with the package portion of the label in
* plain text. If the qualifier is excluded, it willnot be included in the
* link label.
*
* @param cd the class to link to.
* @param isStrong true if the link should be strong.
* @return the link with the package portion of the label in plain text.
*/
public String getPreQualifiedClassLink(int context,
ClassDoc cd, boolean isStrong) {
String classlink = "";
PackageDoc pd = cd.containingPackage();
if(pd != null && ! configuration.shouldExcludeQualifier(pd.name())) {
classlink = getPkgName(cd);
}
classlink += getLink(new LinkInfoImpl(context, cd, cd.name(), isStrong));
return classlink;
}
/**
* Add the class link with the package portion of the label in
* plain text. If the qualifier is excluded, it will not be included in the
* link label.
*
* @param context the id of the context where the link will be added
* @param cd the class to link to
* @param isStrong true if the link should be strong
* @param contentTree the content tree to which the link with be added
*/
public void addPreQualifiedClassLink(int context,
ClassDoc cd, boolean isStrong, Content contentTree) {
PackageDoc pd = cd.containingPackage();
if(pd != null && ! configuration.shouldExcludeQualifier(pd.name())) {
contentTree.addContent(getPkgName(cd));
}
contentTree.addContent(new RawHtml(getLink(new LinkInfoImpl(
context, cd, cd.name(), isStrong))));
}
/**
* Add the class link, with only class name as the strong link and prefixing
* plain package name.
*
* @param context the id of the context where the link will be added
* @param cd the class to link to
* @param contentTree the content tree to which the link with be added
*/
public void addPreQualifiedStrongClassLink(int context, ClassDoc cd, Content contentTree) {
addPreQualifiedClassLink(context, cd, true, contentTree);
}
public void printText(String key) {
print(configuration.getText(key));
}
public void printText(String key, String a1) {
print(configuration.getText(key, a1));
}
public void printText(String key, String a1, String a2) {
print(configuration.getText(key, a1, a2));
}
public void strongText(String key) {
strong(configuration.getText(key));
}
public void strongText(String key, String a1) {
strong(configuration.getText(key, a1));
}
public void strongText(String key, String a1, String a2) {
strong(configuration.getText(key, a1, a2));
}
/**
* Get the link for the given member.
*
* @param context the id of the context where the link will be added
* @param doc the member being linked to
* @param label the label for the link
* @return a content tree for the doc link
*/
public Content getDocLink(int context, MemberDoc doc, String label) {
return getDocLink(context, doc.containingClass(), doc, label);
}
/**
* Print the link for the given member.
*
* @param context the id of the context where the link will be printed.
* @param classDoc the classDoc that we should link to. This is not
* necessarily equal to doc.containingClass(). We may be
* inheriting comments.
* @param doc the member being linked to.
* @param label the label for the link.
* @param strong true if the link should be strong.
*/
public void printDocLink(int context, ClassDoc classDoc, MemberDoc doc,
String label, boolean strong) {
print(getDocLink(context, classDoc, doc, label, strong));
}
/**
* Return the link for the given member.
*
* @param context the id of the context where the link will be printed.
* @param doc the member being linked to.
* @param label the label for the link.
* @param strong true if the link should be strong.
* @return the link for the given member.
*/
public String getDocLink(int context, MemberDoc doc, String label,
boolean strong) {
return getDocLink(context, doc.containingClass(), doc, label, strong);
}
/**
* Return the link for the given member.
*
* @param context the id of the context where the link will be printed.
* @param classDoc the classDoc that we should link to. This is not
* necessarily equal to doc.containingClass(). We may be
* inheriting comments.
* @param doc the member being linked to.
* @param label the label for the link.
* @param strong true if the link should be strong.
* @return the link for the given member.
*/
public String getDocLink(int context, ClassDoc classDoc, MemberDoc doc,
String label, boolean strong) {
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration()))) {
return label;
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc)doc;
return getLink(new LinkInfoImpl(context, classDoc,
getAnchor(emd), label, strong));
} else if (doc instanceof MemberDoc) {
return getLink(new LinkInfoImpl(context, classDoc,
doc.name(), label, strong));
} else {
return label;
}
}
/**
* Return the link for the given member.
*
* @param context the id of the context where the link will be added
* @param classDoc the classDoc that we should link to. This is not
* necessarily equal to doc.containingClass(). We may be
* inheriting comments
* @param doc the member being linked to
* @param label the label for the link
* @return the link for the given member
*/
public Content getDocLink(int context, ClassDoc classDoc, MemberDoc doc,
String label) {
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration()))) {
return new StringContent(label);
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc)doc;
return new RawHtml(getLink(new LinkInfoImpl(context, classDoc,
getAnchor(emd), label, false)));
} else if (doc instanceof MemberDoc) {
return new RawHtml(getLink(new LinkInfoImpl(context, classDoc,
doc.name(), label, false)));
} else {
return new StringContent(label);
}
}
public void anchor(ExecutableMemberDoc emd) {
anchor(getAnchor(emd));
}
public String getAnchor(ExecutableMemberDoc emd) {
StringBuilder signature = new StringBuilder(emd.signature());
StringBuilder signatureParsed = new StringBuilder();
int counter = 0;
for (int i = 0; i < signature.length(); i++) {
char c = signature.charAt(i);
if (c == '<') {
counter++;
} else if (c == '>') {
counter--;
} else if (counter == 0) {
signatureParsed.append(c);
}
}
return emd.name() + signatureParsed.toString();
}
public String seeTagToString(SeeTag see) {
String tagName = see.name();
if (! (tagName.startsWith("@link") || tagName.equals("@see"))) {
return "";
}
StringBuffer result = new StringBuffer();
boolean isplaintext = tagName.toLowerCase().equals("@linkplain");
String label = see.label();
label = (label.length() > 0)?
((isplaintext) ? label :
getCode() + label + getCodeEnd()):"";
String seetext = replaceDocRootDir(see.text());
//Check if @see is an href or "string"
if (seetext.startsWith("<") || seetext.startsWith("\"")) {
result.append(seetext);
return result.toString();
}
//The text from the @see tag. We will output this text when a label is not specified.
String text = (isplaintext) ? seetext : getCode() + seetext + getCodeEnd();
ClassDoc refClass = see.referencedClass();
String refClassName = see.referencedClassName();
MemberDoc refMem = see.referencedMember();
String refMemName = see.referencedMemberName();
if (refClass == null) {
//@see is not referencing an included class
PackageDoc refPackage = see.referencedPackage();
if (refPackage != null && refPackage.isIncluded()) {
//@see is referencing an included package
String packageName = isplaintext ? refPackage.name() :
getCode() + refPackage.name() + getCodeEnd();
result.append(getPackageLinkString(refPackage,
label.length() == 0 ? packageName : label, false));
} else {
//@see is not referencing an included class or package. Check for cross links.
String classCrossLink, packageCrossLink = getCrossPackageLink(refClassName);
if (packageCrossLink != null) {
//Package cross link found
result.append(getHyperLinkString(packageCrossLink, "",
(label.length() == 0)? text : label, false));
} else if ((classCrossLink = getCrossClassLink(refClassName,
refMemName, label, false, "", ! isplaintext)) != null) {
//Class cross link found (possiblly to a member in the class)
result.append(classCrossLink);
} else {
//No cross link found so print warning
configuration.getDocletSpecificMsg().warning(see.position(), "doclet.see.class_or_package_not_found",
tagName, seetext);
result.append((label.length() == 0)? text: label);
}
}
} else if (refMemName == null) {
// Must be a class reference since refClass is not null and refMemName is null.
if (label.length() == 0) {
label = (isplaintext) ? refClass.name() : getCode() + refClass.name() + getCodeEnd();
result.append(getLink(new LinkInfoImpl(refClass, label)));
} else {
result.append(getLink(new LinkInfoImpl(refClass, label)));
}
} else if (refMem == null) {
// Must be a member reference since refClass is not null and refMemName is not null.
// However, refMem is null, so this referenced member does not exist.
result.append((label.length() == 0)? text: label);
} else {
// Must be a member reference since refClass is not null and refMemName is not null.
// refMem is not null, so this @see tag must be referencing a valid member.
ClassDoc containing = refMem.containingClass();
if (see.text().trim().startsWith("#") &&
! (containing.isPublic() ||
Util.isLinkable(containing, configuration()))) {
// Since the link is relative and the holder is not even being
// documented, this must be an inherited link. Redirect it.
// The current class either overrides the referenced member or
// inherits it automatically.
if (this instanceof ClassWriterImpl) {
containing = ((ClassWriterImpl) this).getClassDoc();
} else if (!containing.isPublic()){
configuration.getDocletSpecificMsg().warning(
see.position(), "doclet.see.class_or_package_not_accessible",
tagName, containing.qualifiedName());
} else {
configuration.getDocletSpecificMsg().warning(
see.position(), "doclet.see.class_or_package_not_found",
tagName, seetext);
}
}
if (configuration.currentcd != containing) {
refMemName = containing.name() + "." + refMemName;
}
if (refMem instanceof ExecutableMemberDoc) {
if (refMemName.indexOf('(') < 0) {
refMemName += ((ExecutableMemberDoc)refMem).signature();
}
}
text = (isplaintext) ?
refMemName : getCode() + Util.escapeHtmlChars(refMemName) + getCodeEnd();
result.append(getDocLink(LinkInfoImpl.CONTEXT_SEE_TAG, containing,
refMem, (label.length() == 0)? text: label, false));
}
return result.toString();
}
public void printInlineComment(Doc doc, Tag tag) {
printCommentTags(doc, tag.inlineTags(), false, false);
}
/**
* Add the inline comment.
*
* @param doc the doc for which the inline comment will be added
* @param tag the inline tag to be added
* @param htmltree the content tree to which the comment will be added
*/
public void addInlineComment(Doc doc, Tag tag, Content htmltree) {
addCommentTags(doc, tag.inlineTags(), false, false, htmltree);
}
public void printInlineDeprecatedComment(Doc doc, Tag tag) {
printCommentTags(doc, tag.inlineTags(), true, false);
}
/**
* Add the inline deprecated comment.
*
* @param doc the doc for which the inline deprecated comment will be added
* @param tag the inline tag to be added
* @param htmltree the content tree to which the comment will be added
*/
public void addInlineDeprecatedComment(Doc doc, Tag tag, Content htmltree) {
addCommentTags(doc, tag.inlineTags(), true, false, htmltree);
}
public void printSummaryComment(Doc doc) {
printSummaryComment(doc, doc.firstSentenceTags());
}
/**
* Adds the summary content.
*
* @param doc the doc for which the summary will be generated
* @param htmltree the documentation tree to which the summary will be added
*/
public void addSummaryComment(Doc doc, Content htmltree) {
addSummaryComment(doc, doc.firstSentenceTags(), htmltree);
}
public void printSummaryComment(Doc doc, Tag[] firstSentenceTags) {
printCommentTags(doc, firstSentenceTags, false, true);
}
/**
* Adds the summary content.
*
* @param doc the doc for which the summary will be generated
* @param firstSentenceTags the first sentence tags for the doc
* @param htmltree the documentation tree to which the summary will be added
*/
public void addSummaryComment(Doc doc, Tag[] firstSentenceTags, Content htmltree) {
addCommentTags(doc, firstSentenceTags, false, true, htmltree);
}
public void printSummaryDeprecatedComment(Doc doc) {
printCommentTags(doc, doc.firstSentenceTags(), true, true);
}
public void printSummaryDeprecatedComment(Doc doc, Tag tag) {
printCommentTags(doc, tag.firstSentenceTags(), true, true);
}
public void addSummaryDeprecatedComment(Doc doc, Tag tag, Content htmltree) {
addCommentTags(doc, tag.firstSentenceTags(), true, true, htmltree);
}
public void printInlineComment(Doc doc) {
printCommentTags(doc, doc.inlineTags(), false, false);
p();
}
/**
* Adds the inline comment.
*
* @param doc the doc for which the inline comments will be generated
* @param htmltree the documentation tree to which the inline comments will be added
*/
public void addInlineComment(Doc doc, Content htmltree) {
addCommentTags(doc, doc.inlineTags(), false, false, htmltree);
}
public void printInlineDeprecatedComment(Doc doc) {
printCommentTags(doc, doc.inlineTags(), true, false);
}
private void printCommentTags(Doc doc, Tag[] tags, boolean depr, boolean first) {
if(configuration.nocomment){
return;
}
if (depr) {
italic();
}
String result = commentTagsToString(null, doc, tags, first);
print(result);
if (depr) {
italicEnd();
}
if (tags.length == 0) {
space();
}
}
/**
* Adds the comment tags.
*
* @param doc the doc for which the comment tags will be generated
* @param tags the first sentence tags for the doc
* @param depr true if it is deprecated
* @param first true if the first sentenge tags should be added
* @param htmltree the documentation tree to which the comment tags will be added
*/
private void addCommentTags(Doc doc, Tag[] tags, boolean depr,
boolean first, Content htmltree) {
if(configuration.nocomment){
return;
}
Content div;
Content result = new RawHtml(commentTagsToString(null, doc, tags, first));
if (depr) {
Content italic = HtmlTree.I(result);
div = HtmlTree.DIV(HtmlStyle.block, italic);
htmltree.addContent(div);
}
else {
div = HtmlTree.DIV(HtmlStyle.block, result);
htmltree.addContent(div);
}
if (tags.length == 0) {
htmltree.addContent(getSpace());
}
}
/**
* Converts inline tags and text to text strings, expanding the
* inline tags along the way. Called wherever text can contain
* an inline tag, such as in comments or in free-form text arguments
* to non-inline tags.
*
* @param holderTag specific tag where comment resides
* @param doc specific doc where comment resides
* @param tags array of text tags and inline tags (often alternating)
* present in the text of interest for this doc
* @param isFirstSentence true if text is first sentence
*/
public String commentTagsToString(Tag holderTag, Doc doc, Tag[] tags,
boolean isFirstSentence) {
StringBuilder result = new StringBuilder();
boolean textTagChange = false;
// Array of all possible inline tags for this javadoc run
configuration.tagletManager.checkTags(doc, tags, true);
for (int i = 0; i < tags.length; i++) {
Tag tagelem = tags[i];
String tagName = tagelem.name();
if (tagelem instanceof SeeTag) {
result.append(seeTagToString((SeeTag)tagelem));
} else if (! tagName.equals("Text")) {
int originalLength = result.length();
TagletOutput output = TagletWriter.getInlineTagOuput(
configuration.tagletManager, holderTag,
tagelem, getTagletWriterInstance(isFirstSentence));
result.append(output == null ? "" : output.toString());
if (originalLength == 0 && isFirstSentence && tagelem.name().equals("@inheritDoc") && result.length() > 0) {
break;
} else if (configuration.docrootparent.length() > 0 &&
tagelem.name().equals("@docRoot") &&
((tags[i + 1]).text()).startsWith("/..")) {
//If Xdocrootparent switch ON, set the flag to remove the /.. occurance after
//{@docRoot} tag in the very next Text tag.
textTagChange = true;
continue;
} else {
continue;
}
} else {
String text = tagelem.text();
//If Xdocrootparent switch ON, remove the /.. occurance after {@docRoot} tag.
if (textTagChange) {
text = text.replaceFirst("/..", "");
textTagChange = false;
}
//This is just a regular text tag. The text may contain html links (<a>)
//or inline tag {@docRoot}, which will be handled as special cases.
text = redirectRelativeLinks(tagelem.holder(), text);
// Replace @docRoot only if not represented by an instance of DocRootTaglet,
// that is, only if it was not present in a source file doc comment.
// This happens when inserted by the doclet (a few lines
// above in this method). [It might also happen when passed in on the command
// line as a text argument to an option (like -header).]
text = replaceDocRootDir(text);
if (isFirstSentence) {
text = removeNonInlineHtmlTags(text);
}
StringTokenizer lines = new StringTokenizer(text, "\r\n", true);
StringBuffer textBuff = new StringBuffer();
while (lines.hasMoreTokens()) {
StringBuilder line = new StringBuilder(lines.nextToken());
Util.replaceTabs(configuration.sourcetab, line);
textBuff.append(line.toString());
}
result.append(textBuff);
}
}
return result.toString();
}
/**
* Return true if relative links should not be redirected.
*
* @return Return true if a relative link should not be redirected.
*/
private boolean shouldNotRedirectRelativeLinks() {
return this instanceof AnnotationTypeWriter ||
this instanceof ClassWriter ||
this instanceof PackageSummaryWriter;
}
/**
* Suppose a piece of documentation has a relative link. When you copy
* that documetation to another place such as the index or class-use page,
* that relative link will no longer work. We should redirect those links
* so that they will work again.
* <p>
* Here is the algorithm used to fix the link:
* <p>
* <relative link> => docRoot + <relative path to file> + <relative link>
* <p>
* For example, suppose com.sun.javadoc.RootDoc has this link:
* <a href="package-summary.html">The package Page</a>
* <p>
* If this link appeared in the index, we would redirect
* the link like this:
*
* <a href="./com/sun/javadoc/package-summary.html">The package Page</a>
*
* @param doc the Doc object whose documentation is being written.
* @param text the text being written.
*
* @return the text, with all the relative links redirected to work.
*/
private String redirectRelativeLinks(Doc doc, String text) {
if (doc == null || shouldNotRedirectRelativeLinks()) {
return text;
}
String redirectPathFromRoot;
if (doc instanceof ClassDoc) {
redirectPathFromRoot = DirectoryManager.getDirectoryPath(((ClassDoc) doc).containingPackage());
} else if (doc instanceof MemberDoc) {
redirectPathFromRoot = DirectoryManager.getDirectoryPath(((MemberDoc) doc).containingPackage());
} else if (doc instanceof PackageDoc) {
redirectPathFromRoot = DirectoryManager.getDirectoryPath((PackageDoc) doc);
} else {
return text;
}
if (! redirectPathFromRoot.endsWith(DirectoryManager.URL_FILE_SEPARATOR)) {
redirectPathFromRoot += DirectoryManager.URL_FILE_SEPARATOR;
}
//Redirect all relative links.
int end, begin = text.toLowerCase().indexOf("<a");
if(begin >= 0){
StringBuffer textBuff = new StringBuffer(text);
while(begin >=0){
if (textBuff.length() > begin + 2 && ! Character.isWhitespace(textBuff.charAt(begin+2))) {
begin = textBuff.toString().toLowerCase().indexOf("<a", begin + 1);
continue;
}
begin = textBuff.indexOf("=", begin) + 1;
end = textBuff.indexOf(">", begin +1);
if(begin == 0){
//Link has no equal symbol.
configuration.root.printWarning(
doc.position(),
configuration.getText("doclet.malformed_html_link_tag", text));
break;
}
if (end == -1) {
//Break without warning. This <a> tag is not necessarily malformed. The text
//might be missing '>' character because the href has an inline tag.
break;
}
if(textBuff.substring(begin, end).indexOf("\"") != -1){
begin = textBuff.indexOf("\"", begin) + 1;
end = textBuff.indexOf("\"", begin +1);
if(begin == 0 || end == -1){
//Link is missing a quote.
break;
}
}
String relativeLink = textBuff.substring(begin, end);
if(!(relativeLink.toLowerCase().startsWith("mailto:") ||
relativeLink.toLowerCase().startsWith("http:") ||
relativeLink.toLowerCase().startsWith("https:") ||
relativeLink.toLowerCase().startsWith("file:"))){
relativeLink = "{@"+(new DocRootTaglet()).getName() + "}"
+ redirectPathFromRoot
+ relativeLink;
textBuff.replace(begin, end, relativeLink);
}
begin = textBuff.toString().toLowerCase().indexOf("<a", begin + 1);
}
return textBuff.toString();
}
return text;
}
public String removeNonInlineHtmlTags(String text) {
if (text.indexOf('<') < 0) {
return text;
}
String noninlinetags[] = { "<ul>", "</ul>", "<ol>", "</ol>",
"<dl>", "</dl>", "<table>", "</table>",
"<tr>", "</tr>", "<td>", "</td>",
"<th>", "</th>", "<p>", "</p>",
"<li>", "</li>", "<dd>", "</dd>",
"<dir>", "</dir>", "<dt>", "</dt>",
"<h1>", "</h1>", "<h2>", "</h2>",
"<h3>", "</h3>", "<h4>", "</h4>",
"<h5>", "</h5>", "<h6>", "</h6>",
"<pre>", "</pre>", "<menu>", "</menu>",
"<listing>", "</listing>", "<hr>",
"<blockquote>", "</blockquote>",
"<center>", "</center>",
"<UL>", "</UL>", "<OL>", "</OL>",
"<DL>", "</DL>", "<TABLE>", "</TABLE>",
"<TR>", "</TR>", "<TD>", "</TD>",
"<TH>", "</TH>", "<P>", "</P>",
"<LI>", "</LI>", "<DD>", "</DD>",
"<DIR>", "</DIR>", "<DT>", "</DT>",
"<H1>", "</H1>", "<H2>", "</H2>",
"<H3>", "</H3>", "<H4>", "</H4>",
"<H5>", "</H5>", "<H6>", "</H6>",
"<PRE>", "</PRE>", "<MENU>", "</MENU>",
"<LISTING>", "</LISTING>", "<HR>",
"<BLOCKQUOTE>", "</BLOCKQUOTE>",
"<CENTER>", "</CENTER>"
};
for (int i = 0; i < noninlinetags.length; i++) {
text = replace(text, noninlinetags[i], "");
}
return text;
}
public String replace(String text, String tobe, String by) {
while (true) {
int startindex = text.indexOf(tobe);
if (startindex < 0) {
return text;
}
int endindex = startindex + tobe.length();
StringBuilder replaced = new StringBuilder();
if (startindex > 0) {
replaced.append(text.substring(0, startindex));
}
replaced.append(by);
if (text.length() > endindex) {
replaced.append(text.substring(endindex));
}
text = replaced.toString();
}
}
public void printStyleSheetProperties() {
String filename = configuration.stylesheetfile;
if (filename.length() > 0) {
File stylefile = new File(filename);
String parent = stylefile.getParent();
filename = (parent == null)?
filename:
filename.substring(parent.length() + 1);
} else {
filename = "stylesheet.css";
}
filename = relativePath + filename;
link("REL =\"stylesheet\" TYPE=\"text/css\" HREF=\"" +
filename + "\" " + "TITLE=\"Style\"");
}
/**
* Returns a link to the stylesheet file.
*
* @return an HtmlTree for the lINK tag which provides the stylesheet location
*/
public HtmlTree getStyleSheetProperties() {
String filename = configuration.stylesheetfile;
if (filename.length() > 0) {
File stylefile = new File(filename);
String parent = stylefile.getParent();
filename = (parent == null)?
filename:
filename.substring(parent.length() + 1);
} else {
filename = "stylesheet.css";
}
filename = relativePath + filename;
HtmlTree link = HtmlTree.LINK("stylesheet", "text/css", filename, "Style");
return link;
}
/**
* According to
* <cite>The Java™ Language Specification</cite>,
* all the outer classes and static nested classes are core classes.
*/
public boolean isCoreClass(ClassDoc cd) {
return cd.containingClass() == null || cd.isStatic();
}
/**
* Write the annotatation types for the given packageDoc.
*
* @param packageDoc the package to write annotations for.
*/
public void writeAnnotationInfo(PackageDoc packageDoc) {
writeAnnotationInfo(packageDoc, packageDoc.annotations());
}
/**
* Adds the annotatation types for the given packageDoc.
*
* @param packageDoc the package to write annotations for.
* @param htmltree the documentation tree to which the annotation info will be
* added
*/
public void addAnnotationInfo(PackageDoc packageDoc, Content htmltree) {
addAnnotationInfo(packageDoc, packageDoc.annotations(), htmltree);
}
/**
* Write the annotatation types for the given doc.
*
* @param doc the doc to write annotations for.
*/
public void writeAnnotationInfo(ProgramElementDoc doc) {
writeAnnotationInfo(doc, doc.annotations());
}
/**
* Adds the annotatation types for the given doc.
*
* @param packageDoc the package to write annotations for
* @param htmltree the content tree to which the annotation types will be added
*/
public void addAnnotationInfo(ProgramElementDoc doc, Content htmltree) {
addAnnotationInfo(doc, doc.annotations(), htmltree);
}
/**
* Write the annotatation types for the given doc and parameter.
*
* @param indent the number of spaced to indent the parameters.
* @param doc the doc to write annotations for.
* @param param the parameter to write annotations for.
*/
public boolean writeAnnotationInfo(int indent, Doc doc, Parameter param) {
return writeAnnotationInfo(indent, doc, param.annotations(), false);
}
/**
* Add the annotatation types for the given doc and parameter.
*
* @param indent the number of spaces to indent the parameters.
* @param doc the doc to write annotations for.
* @param param the parameter to write annotations for.
* @param tree the content tree to which the annotation types will be added
*/
public boolean addAnnotationInfo(int indent, Doc doc, Parameter param,
Content tree) {
return addAnnotationInfo(indent, doc, param.annotations(), false, tree);
}
/**
* Write the annotatation types for the given doc.
*
* @param doc the doc to write annotations for.
* @param descList the array of {@link AnnotationDesc}.
*/
private void writeAnnotationInfo(Doc doc, AnnotationDesc[] descList) {
writeAnnotationInfo(0, doc, descList, true);
}
/**
* Adds the annotatation types for the given doc.
*
* @param doc the doc to write annotations for.
* @param descList the array of {@link AnnotationDesc}.
* @param htmltree the documentation tree to which the annotation info will be
* added
*/
private void addAnnotationInfo(Doc doc, AnnotationDesc[] descList,
Content htmltree) {
addAnnotationInfo(0, doc, descList, true, htmltree);
}
/**
* Write the annotatation types for the given doc.
*
* @param indent the number of extra spaces to indent the annotations.
* @param doc the doc to write annotations for.
* @param descList the array of {@link AnnotationDesc}.
*/
private boolean writeAnnotationInfo(int indent, Doc doc, AnnotationDesc[] descList, boolean lineBreak) {
List<String> annotations = getAnnotations(indent, descList, lineBreak);
if (annotations.size() == 0) {
return false;
}
fontNoNewLine("-1");
for (Iterator<String> iter = annotations.iterator(); iter.hasNext();) {
print(iter.next());
}
fontEnd();
return true;
}
/**
* Adds the annotatation types for the given doc.
*
* @param indent the number of extra spaces to indent the annotations.
* @param doc the doc to write annotations for.
* @param descList the array of {@link AnnotationDesc}.
* @param htmltree the documentation tree to which the annotation info will be
* added
*/
private boolean addAnnotationInfo(int indent, Doc doc,
AnnotationDesc[] descList, boolean lineBreak, Content htmltree) {
List<String> annotations = getAnnotations(indent, descList, lineBreak);
if (annotations.size() == 0) {
return false;
}
Content annotationContent;
for (Iterator<String> iter = annotations.iterator(); iter.hasNext();) {
annotationContent = new RawHtml(iter.next());
htmltree.addContent(annotationContent);
}
return true;
}
/**
* Return the string representations of the annotation types for
* the given doc.
*
* @param indent the number of extra spaces to indent the annotations.
* @param descList the array of {@link AnnotationDesc}.
* @param linkBreak if true, add new line between each member value.
* @return an array of strings representing the annotations being
* documented.
*/
private List<String> getAnnotations(int indent, AnnotationDesc[] descList, boolean linkBreak) {
List<String> results = new ArrayList<String>();
StringBuffer annotation;
for (int i = 0; i < descList.length; i++) {
AnnotationTypeDoc annotationDoc = descList[i].annotationType();
if (! Util.isDocumentedAnnotation(annotationDoc)){
continue;
}
annotation = new StringBuffer();
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_ANNOTATION, annotationDoc);
linkInfo.label = "@" + annotationDoc.name();
annotation.append(getLink(linkInfo));
AnnotationDesc.ElementValuePair[] pairs = descList[i].elementValues();
if (pairs.length > 0) {
annotation.append('(');
for (int j = 0; j < pairs.length; j++) {
if (j > 0) {
annotation.append(",");
if (linkBreak) {
annotation.append(DocletConstants.NL);
int spaces = annotationDoc.name().length() + 2;
for (int k = 0; k < (spaces + indent); k++) {
annotation.append(' ');
}
}
}
annotation.append(getDocLink(LinkInfoImpl.CONTEXT_ANNOTATION,
pairs[j].element(), pairs[j].element().name(), false));
annotation.append('=');
AnnotationValue annotationValue = pairs[j].value();
List<AnnotationValue> annotationTypeValues = new ArrayList<AnnotationValue>();
if (annotationValue.value() instanceof AnnotationValue[]) {
AnnotationValue[] annotationArray =
(AnnotationValue[]) annotationValue.value();
for (int k = 0; k < annotationArray.length; k++) {
annotationTypeValues.add(annotationArray[k]);
}
} else {
annotationTypeValues.add(annotationValue);
}
annotation.append(annotationTypeValues.size() == 1 ? "" : "{");
for (Iterator<AnnotationValue> iter = annotationTypeValues.iterator(); iter.hasNext(); ) {
annotation.append(annotationValueToString(iter.next()));
annotation.append(iter.hasNext() ? "," : "");
}
annotation.append(annotationTypeValues.size() == 1 ? "" : "}");
}
annotation.append(")");
}
annotation.append(linkBreak ? DocletConstants.NL : "");
results.add(annotation.toString());
}
return results;
}
private String annotationValueToString(AnnotationValue annotationValue) {
if (annotationValue.value() instanceof Type) {
Type type = (Type) annotationValue.value();
if (type.asClassDoc() != null) {
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_ANNOTATION, type);
linkInfo.label = (type.asClassDoc().isIncluded() ?
type.typeName() :
type.qualifiedTypeName()) + type.dimension() + ".class";
return getLink(linkInfo);
} else {
return type.typeName() + type.dimension() + ".class";
}
} else if (annotationValue.value() instanceof AnnotationDesc) {
List<String> list = getAnnotations(0,
new AnnotationDesc[]{(AnnotationDesc) annotationValue.value()},
false);
StringBuffer buf = new StringBuffer();
for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) {
buf.append(iter.next());
}
return buf.toString();
} else if (annotationValue.value() instanceof MemberDoc) {
return getDocLink(LinkInfoImpl.CONTEXT_ANNOTATION,
(MemberDoc) annotationValue.value(),
((MemberDoc) annotationValue.value()).name(), false);
} else {
return annotationValue.toString();
}
}
/**
* Return the configuation for this doclet.
*
* @return the configuration for this doclet.
*/
public Configuration configuration() {
return configuration;
}
}
| 105,717 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlDoclet.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDoclet.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.builders.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.javadoc.*;
import java.util.*;
import java.io.*;
/**
* The class with "start" method, calls individual Writers.
*
* @author Atul M Dambalkar
* @author Robert Field
* @author Jamie Ho
*
*/
public class HtmlDoclet extends AbstractDoclet {
public HtmlDoclet() {
configuration = (ConfigurationImpl) configuration();
}
/**
* The global configuration information for this run.
*/
public ConfigurationImpl configuration;
/**
* The "start" method as required by Javadoc.
*
* @param root the root of the documentation tree.
* @see com.sun.javadoc.RootDoc
* @return true if the doclet ran without encountering any errors.
*/
public static boolean start(RootDoc root) {
try {
HtmlDoclet doclet = new HtmlDoclet();
return doclet.start(doclet, root);
} finally {
ConfigurationImpl.reset();
}
}
/**
* Create the configuration instance.
* Override this method to use a different
* configuration.
*/
public Configuration configuration() {
return ConfigurationImpl.getInstance();
}
/**
* Start the generation of files. Call generate methods in the individual
* writers, which will in turn genrate the documentation files. Call the
* TreeWriter generation first to ensure the Class Hierarchy is built
* first and then can be used in the later generation.
*
* For new format.
*
* @see com.sun.javadoc.RootDoc
*/
protected void generateOtherFiles(RootDoc root, ClassTree classtree)
throws Exception {
super.generateOtherFiles(root, classtree);
if (configuration.linksource) {
if (configuration.destDirName.length() > 0) {
SourceToHTMLConverter.convertRoot(configuration,
root, configuration.destDirName + File.separator
+ DocletConstants.SOURCE_OUTPUT_DIR_NAME);
} else {
SourceToHTMLConverter.convertRoot(configuration,
root, DocletConstants.SOURCE_OUTPUT_DIR_NAME);
}
}
if (configuration.topFile.length() == 0) {
configuration.standardmessage.
error("doclet.No_Non_Deprecated_Classes_To_Document");
return;
}
boolean nodeprecated = configuration.nodeprecated;
String configdestdir = configuration.destDirName;
String confighelpfile = configuration.helpfile;
String configstylefile = configuration.stylesheetfile;
performCopy(configdestdir, confighelpfile);
performCopy(configdestdir, configstylefile);
Util.copyResourceFile(configuration, "background.gif", false);
Util.copyResourceFile(configuration, "tab.gif", false);
Util.copyResourceFile(configuration, "titlebar.gif", false);
Util.copyResourceFile(configuration, "titlebar_end.gif", false);
// do early to reduce memory footprint
if (configuration.classuse) {
ClassUseWriter.generate(configuration, classtree);
}
IndexBuilder indexbuilder = new IndexBuilder(configuration, nodeprecated);
if (configuration.createtree) {
TreeWriter.generate(configuration, classtree);
}
if (configuration.createindex) {
if (configuration.splitindex) {
SplitIndexWriter.generate(configuration, indexbuilder);
} else {
SingleIndexWriter.generate(configuration, indexbuilder);
}
}
if (!(configuration.nodeprecatedlist || nodeprecated)) {
DeprecatedListWriter.generate(configuration);
}
AllClassesFrameWriter.generate(configuration,
new IndexBuilder(configuration, nodeprecated, true));
FrameOutputWriter.generate(configuration);
if (configuration.createoverview) {
PackageIndexWriter.generate(configuration);
}
if (configuration.helpfile.length() == 0 &&
!configuration.nohelp) {
HelpWriter.generate(configuration);
}
// If a stylesheet file is not specified, copy the default stylesheet
// and replace newline with platform-specific newline.
if (configuration.stylesheetfile.length() == 0) {
Util.copyFile(configuration, "stylesheet.css", Util.RESOURCESDIR,
(configdestdir.isEmpty()) ?
System.getProperty("user.dir") : configdestdir, false, true);
}
}
/**
* {@inheritDoc}
*/
protected void generateClassFiles(ClassDoc[] arr, ClassTree classtree) {
Arrays.sort(arr);
for(int i = 0; i < arr.length; i++) {
if (!(configuration.isGeneratedDoc(arr[i]) && arr[i].isIncluded())) {
continue;
}
ClassDoc prev = (i == 0)?
null:
arr[i-1];
ClassDoc curr = arr[i];
ClassDoc next = (i+1 == arr.length)?
null:
arr[i+1];
try {
if (curr.isAnnotationType()) {
AbstractBuilder annotationTypeBuilder =
configuration.getBuilderFactory()
.getAnnotationTypeBuilder((AnnotationTypeDoc) curr,
prev, next);
annotationTypeBuilder.build();
} else {
AbstractBuilder classBuilder =
configuration.getBuilderFactory()
.getClassBuilder(curr, prev, next, classtree);
classBuilder.build();
}
} catch (Exception e) {
e.printStackTrace();
throw new DocletAbortException();
}
}
}
/**
* {@inheritDoc}
*/
protected void generatePackageFiles(ClassTree classtree) throws Exception {
PackageDoc[] packages = configuration.packages;
if (packages.length > 1) {
PackageIndexFrameWriter.generate(configuration);
}
PackageDoc prev = null, next;
for (int i = 0; i < packages.length; i++) {
// if -nodeprecated option is set and the package is marked as
// deprecated, do not generate the package-summary.html, package-frame.html
// and package-tree.html pages for that package.
if (!(configuration.nodeprecated && Util.isDeprecated(packages[i]))) {
PackageFrameWriter.generate(configuration, packages[i]);
next = (i + 1 < packages.length &&
packages[i + 1].name().length() > 0) ? packages[i + 1] : null;
//If the next package is unnamed package, skip 2 ahead if possible
next = (i + 2 < packages.length && next == null) ? packages[i + 2] : next;
AbstractBuilder packageSummaryBuilder =
configuration.getBuilderFactory().getPackageSummaryBuilder(
packages[i], prev, next);
packageSummaryBuilder.build();
if (configuration.createtree) {
PackageTreeWriter.generate(configuration,
packages[i], prev, next,
configuration.nodeprecated);
}
prev = packages[i];
}
}
}
/**
* Check for doclet added options here.
*
* @return number of arguments to option. Zero return means
* option not known. Negative value means error occurred.
*/
public static int optionLength(String option) {
// Construct temporary configuration for check
return (ConfigurationImpl.getInstance()).optionLength(option);
}
/**
* Check that options have the correct arguments here.
* <P>
* This method is not required and will default gracefully
* (to true) if absent.
* <P>
* Printing option related error messages (using the provided
* DocErrorReporter) is the responsibility of this method.
*
* @return true if the options are valid.
*/
public static boolean validOptions(String options[][],
DocErrorReporter reporter) {
// Construct temporary configuration for check
return (ConfigurationImpl.getInstance()).validOptions(options, reporter);
}
private void performCopy(String configdestdir, String filename) {
try {
String destdir = (configdestdir.length() > 0) ?
configdestdir + File.separatorChar: "";
if (filename.length() > 0) {
File helpstylefile = new File(filename);
String parent = helpstylefile.getParent();
String helpstylefilename = (parent == null)?
filename:
filename.substring(parent.length() + 1);
File desthelpfile = new File(destdir + helpstylefilename);
if (!desthelpfile.getCanonicalPath().equals(
helpstylefile.getCanonicalPath())) {
configuration.message.
notice((SourcePosition) null,
"doclet.Copying_File_0_To_File_1",
helpstylefile.toString(), desthelpfile.toString());
Util.copyFile(desthelpfile, helpstylefile);
}
}
} catch (IOException exc) {
configuration.message.
error((SourcePosition) null,
"doclet.perform_copy_exception_encountered",
exc.toString());
throw new DocletAbortException();
}
}
}
| 11,254 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TreeWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/TreeWriter.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate Class Hierarchy page for all the Classes in this run. Use
* ClassTree for building the Tree. The name of
* the generated file is "overview-tree.html" and it is generated in the
* current or the destination directory.
*
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class TreeWriter extends AbstractTreeWriter {
/**
* Packages in this run.
*/
private PackageDoc[] packages;
/**
* True if there are no packages specified on the command line,
* False otherwise.
*/
private boolean classesonly;
/**
* Constructor to construct TreeWriter object.
*
* @param configuration the current configuration of the doclet.
* @param filename String filename
* @param classtree the tree being built.
*/
public TreeWriter(ConfigurationImpl configuration,
String filename, ClassTree classtree)
throws IOException {
super(configuration, filename, classtree);
packages = configuration.packages;
classesonly = packages.length == 0;
}
/**
* Create a TreeWriter object and use it to generate the
* "overview-tree.html" file.
*
* @param classtree the class tree being documented.
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration,
ClassTree classtree) {
TreeWriter treegen;
String filename = "overview-tree.html";
try {
treegen = new TreeWriter(configuration, filename, classtree);
treegen.generateTreeFile();
treegen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the interface hierarchy and class hierarchy.
*/
public void generateTreeFile() throws IOException {
Content body = getTreeHeader();
Content headContent = getResource("doclet.Hierarchy_For_All_Packages");
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, false,
HtmlStyle.title, headContent);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
addPackageTreeLinks(div);
body.addContent(div);
HtmlTree divTree = new HtmlTree(HtmlTag.DIV);
divTree.addStyle(HtmlStyle.contentContainer);
addTree(classtree.baseclasses(), "doclet.Class_Hierarchy", divTree);
addTree(classtree.baseinterfaces(), "doclet.Interface_Hierarchy", divTree);
addTree(classtree.baseAnnotationTypes(), "doclet.Annotation_Type_Hierarchy", divTree);
addTree(classtree.baseEnums(), "doclet.Enum_Hierarchy", divTree);
body.addContent(divTree);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Add the links to all the package tree files.
*
* @param contentTree the content tree to which the links will be added
*/
protected void addPackageTreeLinks(Content contentTree) {
//Do nothing if only unnamed package is used
if (packages.length == 1 && packages[0].name().length() == 0) {
return;
}
if (!classesonly) {
Content span = HtmlTree.SPAN(HtmlStyle.strong,
getResource("doclet.Package_Hierarchies"));
contentTree.addContent(span);
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.horizontal);
for (int i = 0; i < packages.length; i++) {
// If the package name length is 0 or if -nodeprecated option
// is set and the package is marked as deprecated, do not include
// the page in the list of package hierarchies.
if (packages[i].name().length() == 0 ||
(configuration.nodeprecated && Util.isDeprecated(packages[i]))) {
continue;
}
String link = pathString(packages[i], "package-tree.html");
Content li = HtmlTree.LI(getHyperLink(
link, "", new StringContent(packages[i].name())));
if (i < packages.length - 1) {
li.addContent(", ");
}
ul.addContent(li);
}
contentTree.addContent(ul);
}
}
/**
* Get the tree header.
*
* @return a content tree for the tree header
*/
protected Content getTreeHeader() {
String title = configuration.getText("doclet.Window_Class_Hierarchy");
Content bodyTree = getBody(true, getWindowTitle(title));
addTop(bodyTree);
addNavLinks(true, bodyTree);
return bodyTree;
}
}
| 6,386 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TagletWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletWriterImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.builders.SerializedFormBuilder;
import com.sun.tools.doclets.internal.toolkit.taglets.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* The taglet writer that writes HTML.
*
* @since 1.5
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
*/
public class TagletWriterImpl extends TagletWriter {
private HtmlDocletWriter htmlWriter;
public TagletWriterImpl(HtmlDocletWriter htmlWriter, boolean isFirstSentence) {
this.htmlWriter = htmlWriter;
this.isFirstSentence = isFirstSentence;
}
/**
* {@inheritDoc}
*/
public TagletOutput getOutputInstance() {
return new TagletOutputImpl("");
}
/**
* {@inheritDoc}
*/
public TagletOutput getDocRootOutput() {
if (htmlWriter.configuration.docrootparent.length() > 0)
return new TagletOutputImpl(htmlWriter.configuration.docrootparent);
else
return new TagletOutputImpl(htmlWriter.relativepathNoSlash);
}
/**
* {@inheritDoc}
*/
public TagletOutput deprecatedTagOutput(Doc doc) {
StringBuffer output = new StringBuffer();
Tag[] deprs = doc.tags("deprecated");
if (doc instanceof ClassDoc) {
if (Util.isDeprecated((ProgramElementDoc) doc)) {
output.append("<span class=\"strong\">" +
ConfigurationImpl.getInstance().
getText("doclet.Deprecated") + "</span> ");
if (deprs.length > 0) {
Tag[] commentTags = deprs[0].inlineTags();
if (commentTags.length > 0) {
output.append(commentTagsToOutput(null, doc,
deprs[0].inlineTags(), false).toString()
);
}
}
}
} else {
MemberDoc member = (MemberDoc) doc;
if (Util.isDeprecated((ProgramElementDoc) doc)) {
output.append("<span class=\"strong\">" +
ConfigurationImpl.getInstance().
getText("doclet.Deprecated") + "</span> ");
if (deprs.length > 0) {
output.append("<i>");
output.append(commentTagsToOutput(null, doc,
deprs[0].inlineTags(), false).toString());
output.append("</i>");
}
} else {
if (Util.isDeprecated(member.containingClass())) {
output.append("<span class=\"strong\">" +
ConfigurationImpl.getInstance().
getText("doclet.Deprecated") + "</span> ");
}
}
}
return new TagletOutputImpl(output.toString());
}
/**
* {@inheritDoc}
*/
public MessageRetriever getMsgRetriever() {
return htmlWriter.configuration.message;
}
/**
* {@inheritDoc}
*/
public TagletOutput getParamHeader(String header) {
StringBuffer result = new StringBuffer();
result.append("<dt>");
result.append("<span class=\"strong\">" + header + "</span></dt>");
return new TagletOutputImpl(result.toString());
}
/**
* {@inheritDoc}
*/
public TagletOutput paramTagOutput(ParamTag paramTag, String paramName) {
TagletOutput result = new TagletOutputImpl("<dd><code>" + paramName + "</code>"
+ " - " + htmlWriter.commentTagsToString(paramTag, null, paramTag.inlineTags(), false) + "</dd>");
return result;
}
/**
* {@inheritDoc}
*/
public TagletOutput returnTagOutput(Tag returnTag) {
TagletOutput result = new TagletOutputImpl(DocletConstants.NL + "<dt>" +
"<span class=\"strong\">" + htmlWriter.configuration.getText("doclet.Returns") +
"</span>" + "</dt>" + "<dd>" +
htmlWriter.commentTagsToString(returnTag, null, returnTag.inlineTags(),
false) + "</dd>");
return result;
}
/**
* {@inheritDoc}
*/
public TagletOutput seeTagOutput(Doc holder, SeeTag[] seeTags) {
String result = "";
if (seeTags.length > 0) {
result = addSeeHeader(result);
for (int i = 0; i < seeTags.length; ++i) {
if (i > 0) {
result += ", " + DocletConstants.NL;
}
result += htmlWriter.seeTagToString(seeTags[i]);
}
}
if (holder.isField() && ((FieldDoc)holder).constantValue() != null &&
htmlWriter instanceof ClassWriterImpl) {
//Automatically add link to constant values page for constant fields.
result = addSeeHeader(result);
result += htmlWriter.getHyperLinkString(htmlWriter.relativePath +
ConfigurationImpl.CONSTANTS_FILE_NAME
+ "#" + ((ClassWriterImpl) htmlWriter).getClassDoc().qualifiedName()
+ "." + ((FieldDoc) holder).name(),
htmlWriter.configuration.getText("doclet.Constants_Summary"));
}
if (holder.isClass() && ((ClassDoc)holder).isSerializable()) {
//Automatically add link to serialized form page for serializable classes.
if ((SerializedFormBuilder.serialInclude(holder) &&
SerializedFormBuilder.serialInclude(((ClassDoc)holder).containingPackage()))) {
result = addSeeHeader(result);
result += htmlWriter.getHyperLinkString(htmlWriter.relativePath + "serialized-form.html",
((ClassDoc)holder).qualifiedName(), htmlWriter.configuration.getText("doclet.Serialized_Form"), false);
}
}
return result.equals("") ? null : new TagletOutputImpl(result + "</dd>");
}
private String addSeeHeader(String result) {
if (result != null && result.length() > 0) {
return result + ", " + DocletConstants.NL;
} else {
return "<dt><span class=\"strong\">" +
htmlWriter.configuration().getText("doclet.See_Also") + "</span></dt><dd>";
}
}
/**
* {@inheritDoc}
*/
public TagletOutput simpleTagOutput(Tag[] simpleTags, String header) {
String result = "<dt><span class=\"strong\">" + header + "</span></dt>" + DocletConstants.NL +
" <dd>";
for (int i = 0; i < simpleTags.length; i++) {
if (i > 0) {
result += ", ";
}
result += htmlWriter.commentTagsToString(simpleTags[i], null, simpleTags[i].inlineTags(), false);
}
result += "</dd>" + DocletConstants.NL;
return new TagletOutputImpl(result);
}
/**
* {@inheritDoc}
*/
public TagletOutput simpleTagOutput(Tag simpleTag, String header) {
return new TagletOutputImpl("<dt><span class=\"strong\">" + header + "</span></dt>" + " <dd>"
+ htmlWriter.commentTagsToString(simpleTag, null, simpleTag.inlineTags(), false)
+ "</dd>" + DocletConstants.NL);
}
/**
* {@inheritDoc}
*/
public TagletOutput getThrowsHeader() {
return new TagletOutputImpl(DocletConstants.NL + "<dt>" + "<span class=\"strong\">" +
htmlWriter.configuration().getText("doclet.Throws") + "</span></dt>");
}
/**
* {@inheritDoc}
*/
public TagletOutput throwsTagOutput(ThrowsTag throwsTag) {
String result = DocletConstants.NL + "<dd>";
result += throwsTag.exceptionType() == null ?
htmlWriter.codeText(throwsTag.exceptionName()) :
htmlWriter.codeText(
htmlWriter.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
throwsTag.exceptionType())));
TagletOutput text = new TagletOutputImpl(
htmlWriter.commentTagsToString(throwsTag, null,
throwsTag.inlineTags(), false));
if (text != null && text.toString().length() > 0) {
result += " - " + text;
}
result += "</dd>";
return new TagletOutputImpl(result);
}
/**
* {@inheritDoc}
*/
public TagletOutput throwsTagOutput(Type throwsType) {
return new TagletOutputImpl(DocletConstants.NL + "<dd>" +
htmlWriter.codeText(htmlWriter.getLink(
new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER, throwsType))) + "</dd>");
}
/**
* {@inheritDoc}
*/
public TagletOutput valueTagOutput(FieldDoc field, String constantVal,
boolean includeLink) {
return new TagletOutputImpl(includeLink ?
htmlWriter.getDocLink(LinkInfoImpl.CONTEXT_VALUE_TAG, field,
constantVal, false) : constantVal);
}
/**
* {@inheritDoc}
*/
public TagletOutput commentTagsToOutput(Tag holderTag, Tag[] tags) {
return commentTagsToOutput(holderTag, null, tags, false);
}
/**
* {@inheritDoc}
*/
public TagletOutput commentTagsToOutput(Doc holderDoc, Tag[] tags) {
return commentTagsToOutput(null, holderDoc, tags, false);
}
/**
* {@inheritDoc}
*/
public TagletOutput commentTagsToOutput(Tag holderTag,
Doc holderDoc, Tag[] tags, boolean isFirstSentence) {
return new TagletOutputImpl(htmlWriter.commentTagsToString(
holderTag, holderDoc, tags, isFirstSentence));
}
/**
* {@inheritDoc}
*/
public Configuration configuration() {
return htmlWriter.configuration();
}
/**
* Return an instance of a TagletWriter that knows how to write HTML.
*
* @return an instance of a TagletWriter that knows how to write HTML.
*/
public TagletOutput getTagletOutputInstance() {
return new TagletOutputImpl("");
}
}
| 11,248 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractExecutableMemberWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractExecutableMemberWriter.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Print method and constructor info.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public abstract class AbstractExecutableMemberWriter extends AbstractMemberWriter {
public AbstractExecutableMemberWriter(SubWriterHolderWriter writer,
ClassDoc classdoc) {
super(writer, classdoc);
}
public AbstractExecutableMemberWriter(SubWriterHolderWriter writer) {
super(writer);
}
/**
* Add the type parameters for the executable member.
*
* @param member the member to write type parameters for.
* @param htmltree the content tree to which the parameters will be added.
* @return the display length required to write this information.
*/
protected int addTypeParameters(ExecutableMemberDoc member, Content htmltree) {
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_MEMBER_TYPE_PARAMS, member, false);
String typeParameters = writer.getTypeParameterLinks(linkInfo);
if (linkInfo.displayLength > 0) {
Content linkContent = new RawHtml(typeParameters);
htmltree.addContent(linkContent);
htmltree.addContent(writer.getSpace());
writer.displayLength += linkInfo.displayLength + 1;
}
return linkInfo.displayLength;
}
/**
* {@inheritDoc}
*/
protected Content getDeprecatedLink(ProgramElementDoc member) {
ExecutableMemberDoc emd = (ExecutableMemberDoc)member;
return writer.getDocLink(LinkInfoImpl.CONTEXT_MEMBER, (MemberDoc) emd,
emd.qualifiedName() + emd.flatSignature());
}
/**
* Add the summary link for the member.
*
* @param context the id of the context where the link will be printed
* @param classDoc the classDoc that we should link to
* @param member the member being linked to
* @param tdSummary the content tree to which the link will be added
*/
protected void addSummaryLink(int context, ClassDoc cd, ProgramElementDoc member,
Content tdSummary) {
ExecutableMemberDoc emd = (ExecutableMemberDoc)member;
String name = emd.name();
Content strong = HtmlTree.STRONG(new RawHtml(
writer.getDocLink(context, cd, (MemberDoc) emd,
name, false)));
Content code = HtmlTree.CODE(strong);
writer.displayLength = name.length();
addParameters(emd, false, code);
tdSummary.addContent(code);
}
/**
* Add the inherited summary link for the member.
*
* @param classDoc the classDoc that we should link to
* @param member the member being linked to
* @param linksTree the content tree to which the link will be added
*/
protected void addInheritedSummaryLink(ClassDoc cd,
ProgramElementDoc member, Content linksTree) {
linksTree.addContent(new RawHtml(
writer.getDocLink(LinkInfoImpl.CONTEXT_MEMBER, cd, (MemberDoc) member,
member.name(), false)));
}
/**
* Add the parameter for the executable member.
*
* @param member the member to write parameter for.
* @param param the parameter that needs to be written.
* @param isVarArg true if this is a link to var arg.
* @param tree the content tree to which the parameter information will be added.
*/
protected void addParam(ExecutableMemberDoc member, Parameter param,
boolean isVarArg, Content tree) {
if (param.type() != null) {
Content link = new RawHtml(writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_EXECUTABLE_MEMBER_PARAM, param.type(),
isVarArg)));
tree.addContent(link);
}
if(param.name().length() > 0) {
tree.addContent(writer.getSpace());
tree.addContent(param.name());
}
}
/**
* Add all the parameters for the executable member.
*
* @param member the member to write parameters for.
* @param tree the content tree to which the parameters information will be added.
*/
protected void addParameters(ExecutableMemberDoc member, Content htmltree) {
addParameters(member, true, htmltree);
}
/**
* Add all the parameters for the executable member.
*
* @param member the member to write parameters for.
* @param includeAnnotations true if annotation information needs to be added.
* @param tree the content tree to which the parameters information will be added.
*/
protected void addParameters(ExecutableMemberDoc member,
boolean includeAnnotations, Content htmltree) {
htmltree.addContent("(");
Parameter[] params = member.parameters();
String indent = makeSpace(writer.displayLength);
if (configuration().linksource) {
//add spaces to offset indentation changes caused by link.
indent+= makeSpace(member.name().length());
}
int paramstart;
for (paramstart = 0; paramstart < params.length; paramstart++) {
Parameter param = params[paramstart];
if (!param.name().startsWith("this$")) {
if (includeAnnotations) {
boolean foundAnnotations =
writer.addAnnotationInfo(indent.length(),
member, param, htmltree);
if (foundAnnotations) {
htmltree.addContent(DocletConstants.NL);
htmltree.addContent(indent);
}
}
addParam(member, param,
(paramstart == params.length - 1) && member.isVarArgs(), htmltree);
break;
}
}
for (int i = paramstart + 1; i < params.length; i++) {
htmltree.addContent(",");
htmltree.addContent(DocletConstants.NL);
htmltree.addContent(indent);
if (includeAnnotations) {
boolean foundAnnotations =
writer.addAnnotationInfo(indent.length(), member, params[i],
htmltree);
if (foundAnnotations) {
htmltree.addContent(DocletConstants.NL);
htmltree.addContent(indent);
}
}
addParam(member, params[i], (i == params.length - 1) && member.isVarArgs(),
htmltree);
}
htmltree.addContent(")");
}
/**
* Add exceptions for the executable member.
*
* @param member the member to write exceptions for.
* @param htmltree the content tree to which the exceptions information will be added.
*/
protected void addExceptions(ExecutableMemberDoc member, Content htmltree) {
Type[] exceptions = member.thrownExceptionTypes();
if(exceptions.length > 0) {
LinkInfoImpl memberTypeParam = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_MEMBER, member, false);
int retlen = getReturnTypeLength(member);
writer.getTypeParameterLinks(memberTypeParam);
retlen += memberTypeParam.displayLength == 0 ?
0 : memberTypeParam.displayLength + 1;
String indent = makeSpace(modifierString(member).length() +
member.name().length() + retlen - 4);
htmltree.addContent(DocletConstants.NL);
htmltree.addContent(indent);
htmltree.addContent("throws ");
indent += " ";
Content link = new RawHtml(writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_MEMBER, exceptions[0])));
htmltree.addContent(link);
for(int i = 1; i < exceptions.length; i++) {
htmltree.addContent(",");
htmltree.addContent(DocletConstants.NL);
htmltree.addContent(indent);
Content exceptionLink = new RawHtml(writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_MEMBER, exceptions[i])));
htmltree.addContent(exceptionLink);
}
}
}
protected int getReturnTypeLength(ExecutableMemberDoc member) {
if (member instanceof MethodDoc) {
MethodDoc method = (MethodDoc)member;
Type rettype = method.returnType();
if (rettype.isPrimitive()) {
return rettype.typeName().length() +
rettype.dimension().length();
} else {
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_MEMBER, rettype);
writer.getLink(linkInfo);
return linkInfo.displayLength;
}
} else { // it's a constructordoc
return -1;
}
}
protected ClassDoc implementsMethodInIntfac(MethodDoc method,
ClassDoc[] intfacs) {
for (int i = 0; i < intfacs.length; i++) {
MethodDoc[] methods = intfacs[i].methods();
if (methods.length > 0) {
for (int j = 0; j < methods.length; j++) {
if (methods[j].name().equals(method.name()) &&
methods[j].signature().equals(method.signature())) {
return intfacs[i];
}
}
}
}
return null;
}
/**
* For backward compatibility, include an anchor using the erasures of the
* parameters. NOTE: We won't need this method anymore after we fix
* see tags so that they use the type instead of the erasure.
*
* @param emd the ExecutableMemberDoc to anchor to.
* @return the 1.4.x style anchor for the ExecutableMemberDoc.
*/
protected String getErasureAnchor(ExecutableMemberDoc emd) {
StringBuffer buf = new StringBuffer(emd.name() + "(");
Parameter[] params = emd.parameters();
boolean foundTypeVariable = false;
for (int i = 0; i < params.length; i++) {
if (i > 0) {
buf.append(",");
}
Type t = params[i].type();
foundTypeVariable = foundTypeVariable || t.asTypeVariable() != null;
buf.append(t.isPrimitive() ?
t.typeName() : t.asClassDoc().qualifiedName());
buf.append(t.dimension());
}
buf.append(")");
return foundTypeVariable ? buf.toString() : null;
}
}
| 12,104 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SingleIndexWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/SingleIndexWriter.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate only one index file for all the Member Names with Indexing in
* Unicode Order. The name of the generated file is "index-all.html" and it is
* generated in current or the destination directory.
*
* @see java.lang.Character
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class SingleIndexWriter extends AbstractIndexWriter {
/**
* Construct the SingleIndexWriter with filename "index-all.html" and the
* {@link IndexBuilder}
*
* @param filename Name of the index file to be generated.
* @param indexbuilder Unicode based Index from {@link IndexBuilder}
*/
public SingleIndexWriter(ConfigurationImpl configuration,
String filename,
IndexBuilder indexbuilder) throws IOException {
super(configuration, filename, indexbuilder);
relativepathNoSlash = ".";
relativePath = "./";
}
/**
* Generate single index file, for all Unicode characters.
*
* @param indexbuilder IndexBuilder built by {@link IndexBuilder}
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration,
IndexBuilder indexbuilder) {
SingleIndexWriter indexgen;
String filename = "index-all.html";
try {
indexgen = new SingleIndexWriter(configuration,
filename, indexbuilder);
indexgen.generateIndexFile();
indexgen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the contents of each index file, with Header, Footer,
* Member Field, Method and Constructor Description.
*/
protected void generateIndexFile() throws IOException {
String title = configuration.getText("doclet.Window_Single_Index");
Content body = getBody(true, getWindowTitle(title));
addTop(body);
addNavLinks(true, body);
HtmlTree divTree = new HtmlTree(HtmlTag.DIV);
divTree.addStyle(HtmlStyle.contentContainer);
addLinksForIndexes(divTree);
for (int i = 0; i < indexbuilder.elements().length; i++) {
Character unicode = (Character)((indexbuilder.elements())[i]);
addContents(unicode, indexbuilder.getMemberList(unicode), divTree);
}
addLinksForIndexes(divTree);
body.addContent(divTree);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Add links for all the Index Files per unicode character.
*
* @param contentTree the content tree to which the links for indexes will be added
*/
protected void addLinksForIndexes(Content contentTree) {
for (int i = 0; i < indexbuilder.elements().length; i++) {
String unicode = (indexbuilder.elements())[i].toString();
contentTree.addContent(
getHyperLink("#_" + unicode + "_", new StringContent(unicode)));
contentTree.addContent(getSpace());
}
}
}
| 4,767 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeOptionalMemberWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeOptionalMemberWriterImpl.java | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Writes annotation type optional member documentation in HTML format.
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
*/
public class AnnotationTypeOptionalMemberWriterImpl extends
AnnotationTypeRequiredMemberWriterImpl
implements AnnotationTypeOptionalMemberWriter, MemberSummaryWriter {
/**
* Construct a new AnnotationTypeOptionalMemberWriterImpl.
*
* @param writer the writer that will write the output.
* @param annotationType the AnnotationType that holds this member.
*/
public AnnotationTypeOptionalMemberWriterImpl(SubWriterHolderWriter writer,
AnnotationTypeDoc annotationType) {
super(writer, annotationType);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(
HtmlConstants.START_OF_ANNOTATION_TYPE_OPTIONAL_MEMBER_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* {@inheritDoc}
*/
public void addDefaultValueInfo(MemberDoc member, Content annotationDocTree) {
if (((AnnotationTypeElementDoc) member).defaultValue() != null) {
Content dt = HtmlTree.DT(writer.getResource("doclet.Default"));
Content dl = HtmlTree.DL(dt);
Content dd = HtmlTree.DD(new StringContent(
((AnnotationTypeElementDoc) member).defaultValue().toString()));
dl.addContent(dd);
annotationDocTree.addContent(dl);
}
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
writer.close();
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Annotation_Type_Optional_Member_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Annotation_Type_Optional_Member_Summary"),
configuration().getText("doclet.annotation_type_optional_members"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Annotation_Type_Optional_Members");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Annotation_Type_Optional_Member"),
configuration().getText("doclet.Description"))
};
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor(
"annotation_type_optional_element_summary"));
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", "annotation_type_optional_element_summary",
writer.getResource("doclet.navAnnotationTypeOptionalMember"));
} else {
return writer.getResource("doclet.navAnnotationTypeOptionalMember");
}
}
}
| 5,058 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
LinkFactoryImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/LinkFactoryImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.tools.doclets.internal.toolkit.util.links.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* A factory that returns a link given the information about it.
*
* @author Jamie Ho
* @since 1.5
*/
public class LinkFactoryImpl extends LinkFactory {
private HtmlDocletWriter m_writer;
public LinkFactoryImpl(HtmlDocletWriter writer) {
m_writer = writer;
}
/**
* {@inheritDoc}
*/
protected LinkOutput getOutputInstance() {
return new LinkOutputImpl();
}
/**
* {@inheritDoc}
*/
protected LinkOutput getClassLink(LinkInfo linkInfo) {
LinkInfoImpl classLinkInfo = (LinkInfoImpl) linkInfo;
boolean noLabel = linkInfo.label == null || linkInfo.label.length() == 0;
ClassDoc classDoc = classLinkInfo.classDoc;
//Create a tool tip if we are linking to a class or interface. Don't
//create one if we are linking to a member.
String title =
(classLinkInfo.where == null || classLinkInfo.where.length() == 0) ?
getClassToolTip(classDoc,
classLinkInfo.type != null &&
!classDoc.qualifiedTypeName().equals(classLinkInfo.type.qualifiedTypeName())) :
"";
StringBuffer label = new StringBuffer(
classLinkInfo.getClassLinkLabel(m_writer.configuration));
classLinkInfo.displayLength += label.length();
Configuration configuration = ConfigurationImpl.getInstance();
LinkOutputImpl linkOutput = new LinkOutputImpl();
if (classDoc.isIncluded()) {
if (configuration.isGeneratedDoc(classDoc)) {
String filename = pathString(classLinkInfo);
if (linkInfo.linkToSelf ||
!(linkInfo.classDoc.name() + ".html").equals(m_writer.filename)) {
linkOutput.append(m_writer.getHyperLinkString(filename,
classLinkInfo.where, label.toString(),
classLinkInfo.isStrong, classLinkInfo.styleName,
title, classLinkInfo.target));
if (noLabel && !classLinkInfo.excludeTypeParameterLinks) {
linkOutput.append(getTypeParameterLinks(linkInfo).toString());
}
return linkOutput;
}
}
} else {
String crossLink = m_writer.getCrossClassLink(
classDoc.qualifiedName(), classLinkInfo.where,
label.toString(), classLinkInfo.isStrong, classLinkInfo.styleName,
true);
if (crossLink != null) {
linkOutput.append(crossLink);
if (noLabel && !classLinkInfo.excludeTypeParameterLinks) {
linkOutput.append(getTypeParameterLinks(linkInfo).toString());
}
return linkOutput;
}
}
// Can't link so just write label.
linkOutput.append(label.toString());
if (noLabel && !classLinkInfo.excludeTypeParameterLinks) {
linkOutput.append(getTypeParameterLinks(linkInfo).toString());
}
return linkOutput;
}
/**
* {@inheritDoc}
*/
protected LinkOutput getTypeParameterLink(LinkInfo linkInfo,
Type typeParam) {
LinkInfoImpl typeLinkInfo = new LinkInfoImpl(linkInfo.getContext(),
typeParam);
typeLinkInfo.excludeTypeBounds = linkInfo.excludeTypeBounds;
typeLinkInfo.excludeTypeParameterLinks = linkInfo.excludeTypeParameterLinks;
typeLinkInfo.linkToSelf = linkInfo.linkToSelf;
LinkOutput output = getLinkOutput(typeLinkInfo);
((LinkInfoImpl) linkInfo).displayLength += typeLinkInfo.displayLength;
return output;
}
/**
* Given a class, return the appropriate tool tip.
*
* @param classDoc the class to get the tool tip for.
* @return the tool tip for the appropriate class.
*/
private String getClassToolTip(ClassDoc classDoc, boolean isTypeLink) {
Configuration configuration = ConfigurationImpl.getInstance();
if (isTypeLink) {
return configuration.getText("doclet.Href_Type_Param_Title",
classDoc.name());
} else if (classDoc.isInterface()){
return configuration.getText("doclet.Href_Interface_Title",
Util.getPackageName(classDoc.containingPackage()));
} else if (classDoc.isAnnotationType()) {
return configuration.getText("doclet.Href_Annotation_Title",
Util.getPackageName(classDoc.containingPackage()));
} else if (classDoc.isEnum()) {
return configuration.getText("doclet.Href_Enum_Title",
Util.getPackageName(classDoc.containingPackage()));
} else {
return configuration.getText("doclet.Href_Class_Title",
Util.getPackageName(classDoc.containingPackage()));
}
}
/**
* Return path to the given file name in the given package. So if the name
* passed is "Object.html" and the name of the package is "java.lang", and
* if the relative path is "../.." then returned string will be
* "../../java/lang/Object.html"
*
* @param linkInfo the information about the link.
* @param fileName the file name, to which path string is.
*/
private String pathString(LinkInfoImpl linkInfo) {
if (linkInfo.context == LinkInfoImpl.PACKAGE_FRAME) {
//Not really necessary to do this but we want to be consistent
//with 1.4.2 output.
return linkInfo.classDoc.name() + ".html";
}
StringBuffer buf = new StringBuffer(m_writer.relativePath);
buf.append(DirectoryManager.getPathToPackage(
linkInfo.classDoc.containingPackage(),
linkInfo.classDoc.name() + ".html"));
return buf.toString();
}
}
| 7,341 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractIndexWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate Index for all the Member Names with Indexing in
* Unicode Order. This class is a base class for {@link SingleIndexWriter} and
* {@link SplitIndexWriter}. It uses the functionality from
* {@link HtmlDocletWriter} to generate the Index Contents.
*
* @see IndexBuilder
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class AbstractIndexWriter extends HtmlDocletWriter {
/**
* The index of all the members with unicode character.
*/
protected IndexBuilder indexbuilder;
/**
* This constructor will be used by {@link SplitIndexWriter}. Initialises
* path to this file and relative path from this file.
*
* @param path Path to the file which is getting generated.
* @param filename Name of the file which is getting genrated.
* @param relpath Relative path from this file to the current directory.
* @param indexbuilder Unicode based Index from {@link IndexBuilder}
*/
protected AbstractIndexWriter(ConfigurationImpl configuration,
String path, String filename,
String relpath, IndexBuilder indexbuilder)
throws IOException {
super(configuration, path, filename, relpath);
this.indexbuilder = indexbuilder;
}
/**
* This Constructor will be used by {@link SingleIndexWriter}.
*
* @param filename Name of the file which is getting genrated.
* @param indexbuilder Unicode based Index form {@link IndexBuilder}
*/
protected AbstractIndexWriter(ConfigurationImpl configuration,
String filename, IndexBuilder indexbuilder)
throws IOException {
super(configuration, filename);
this.indexbuilder = indexbuilder;
}
/**
* Get the index label for navigation bar.
*
* @return a content tree for the tree label
*/
protected Content getNavLinkIndex() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, indexLabel);
return li;
}
/**
* Add the member information for the unicode character along with the
* list of the members.
*
* @param unicode Unicode for which member list information to be generated
* @param memberlist List of members for the unicode character
* @param contentTree the content tree to which the information will be added
*/
protected void addContents(Character unicode, List<? extends Doc> memberlist,
Content contentTree) {
contentTree.addContent(getMarkerAnchor("_" + unicode + "_"));
Content headContent = new StringContent(unicode.toString());
Content heading = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, false,
HtmlStyle.title, headContent);
contentTree.addContent(heading);
int memberListSize = memberlist.size();
// Display the list only if there are elements to be displayed.
if (memberListSize > 0) {
Content dl = new HtmlTree(HtmlTag.DL);
for (int i = 0; i < memberListSize; i++) {
Doc element = memberlist.get(i);
if (element instanceof MemberDoc) {
addDescription((MemberDoc)element, dl);
} else if (element instanceof ClassDoc) {
addDescription((ClassDoc)element, dl);
} else if (element instanceof PackageDoc) {
addDescription((PackageDoc)element, dl);
}
}
contentTree.addContent(dl);
}
}
/**
* Add one line summary comment for the package.
*
* @param pkg the package to be documented
* @param dlTree the content tree to which the description will be added
*/
protected void addDescription(PackageDoc pkg, Content dlTree) {
Content link = getPackageLink(pkg, new StringContent(Util.getPackageName(pkg)));
Content dt = HtmlTree.DT(link);
dt.addContent(" - ");
dt.addContent(getResource("doclet.package"));
dt.addContent(" " + pkg.name());
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addSummaryComment(pkg, dd);
dlTree.addContent(dd);
}
/**
* Add one line summary comment for the class.
*
* @param cd the class being documented
* @param dlTree the content tree to which the description will be added
*/
protected void addDescription(ClassDoc cd, Content dlTree) {
Content link = new RawHtml(
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_INDEX, cd, true)));
Content dt = HtmlTree.DT(link);
dt.addContent(" - ");
addClassInfo(cd, dt);
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addComment(cd, dd);
dlTree.addContent(dd);
}
/**
* Add the classkind(class, interface, exception, error of the class
* passed.
*
* @param cd the class being documented
* @param contentTree the content tree to which the class info will be added
*/
protected void addClassInfo(ClassDoc cd, Content contentTree) {
contentTree.addContent(getResource("doclet.in",
Util.getTypeName(configuration, cd, false),
getPackageLinkString(cd.containingPackage(),
Util.getPackageName(cd.containingPackage()), false)));
}
/**
* Add description for Class, Field, Method or Constructor.
*
* @param member MemberDoc for the member of the Class Kind
* @param dlTree the content tree to which the description will be added
*/
protected void addDescription(MemberDoc member, Content dlTree) {
String name = (member instanceof ExecutableMemberDoc)?
member.name() + ((ExecutableMemberDoc)member).flatSignature() :
member.name();
if (name.indexOf("<") != -1 || name.indexOf(">") != -1) {
name = Util.escapeHtmlChars(name);
}
Content span = HtmlTree.SPAN(HtmlStyle.strong,
getDocLink(LinkInfoImpl.CONTEXT_INDEX, member, name));
Content dt = HtmlTree.DT(span);
dt.addContent(" - ");
addMemberDesc(member, dt);
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addComment(member, dd);
dlTree.addContent(dd);
}
/**
* Add comment for each element in the index. If the element is deprecated
* and it has a @deprecated tag, use that comment. Else if the containing
* class for this element is deprecated, then add the word "Deprecated." at
* the start and then print the normal comment.
*
* @param element Index element
* @param contentTree the content tree to which the comment will be added
*/
protected void addComment(ProgramElementDoc element, Content contentTree) {
Tag[] tags;
Content span = HtmlTree.SPAN(HtmlStyle.strong, deprecatedPhrase);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.block);
if (Util.isDeprecated(element)) {
div.addContent(span);
if ((tags = element.tags("deprecated")).length > 0)
addInlineDeprecatedComment(element, tags[0], div);
contentTree.addContent(div);
} else {
ClassDoc cont = element.containingClass();
while (cont != null) {
if (Util.isDeprecated(cont)) {
div.addContent(span);
contentTree.addContent(div);
break;
}
cont = cont.containingClass();
}
addSummaryComment(element, contentTree);
}
}
/**
* Add description about the Static Varible/Method/Constructor for a
* member.
*
* @param member MemberDoc for the member within the Class Kind
* @param contentTree the content tree to which the member description will be added
*/
protected void addMemberDesc(MemberDoc member, Content contentTree) {
ClassDoc containing = member.containingClass();
String classdesc = Util.getTypeName(
configuration, containing, true) + " ";
if (member.isField()) {
if (member.isStatic()) {
contentTree.addContent(
getResource("doclet.Static_variable_in", classdesc));
} else {
contentTree.addContent(
getResource("doclet.Variable_in", classdesc));
}
} else if (member.isConstructor()) {
contentTree.addContent(
getResource("doclet.Constructor_for", classdesc));
} else if (member.isMethod()) {
if (member.isStatic()) {
contentTree.addContent(
getResource("doclet.Static_method_in", classdesc));
} else {
contentTree.addContent(
getResource("doclet.Method_in", classdesc));
}
}
addPreQualifiedClassLink(LinkInfoImpl.CONTEXT_INDEX, containing,
false, contentTree);
}
}
| 10,776 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SerializedFormWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/SerializedFormWriterImpl.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate the Serialized Form Information Page.
*
* @author Atul M Dambalkar
*/
public class SerializedFormWriterImpl extends SubWriterHolderWriter
implements com.sun.tools.doclets.internal.toolkit.SerializedFormWriter {
private static final String FILE_NAME = "serialized-form.html";
/**
* @throws IOException
* @throws DocletAbortException
*/
public SerializedFormWriterImpl() throws IOException {
super(ConfigurationImpl.getInstance(), FILE_NAME);
}
/**
* Writes the given header.
*
* @param header the header to write.
*/
public void writeHeader(String header) {
printHtmlHeader(header, null, true);
printTop();
navLinks(true);
hr();
center();
h1();
print(header);
h1End();
centerEnd();
}
/**
* Get the given header.
*
* @param header the header to write
* @return the body content tree
*/
public Content getHeader(String header) {
Content bodyTree = getBody(true, getWindowTitle(header));
addTop(bodyTree);
addNavLinks(true, bodyTree);
Content h1Content = new StringContent(header);
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, h1Content);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
bodyTree.addContent(div);
return bodyTree;
}
/**
* Get the serialized form summaries header.
*
* @return the serialized form summary header tree
*/
public Content getSerializedSummariesHeader() {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
return ul;
}
/**
* Get the package serialized form header.
*
* @return the package serialized form header tree
*/
public Content getPackageSerializedHeader() {
HtmlTree li = new HtmlTree(HtmlTag.LI);
li.addStyle(HtmlStyle.blockList);
return li;
}
/**
* Get the given package header.
*
* @param packageName the package header to write
* @return a content tree for the package header
*/
public Content getPackageHeader(String packageName) {
Content heading = HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING, true,
packageLabel);
heading.addContent(getSpace());
heading.addContent(packageName);
return heading;
}
/**
* Get the serialized class header.
*
* @return a content tree for the serialized class header
*/
public Content getClassSerializedHeader() {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
return ul;
}
/**
* Get the serializable class heading.
*
* @param classDoc the class being processed
* @return a content tree for the class header
*/
public Content getClassHeader(ClassDoc classDoc) {
String classLink = (classDoc.isPublic() || classDoc.isProtected())?
getLink(new LinkInfoImpl(classDoc,
configuration.getClassName(classDoc))):
classDoc.qualifiedName();
Content li = HtmlTree.LI(HtmlStyle.blockList, getMarkerAnchor(
classDoc.qualifiedName()));
String superClassLink =
classDoc.superclassType() != null ?
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_SERIALIZED_FORM,
classDoc.superclassType())) :
null;
//Print the heading.
String className = superClassLink == null ?
configuration.getText(
"doclet.Class_0_implements_serializable", classLink) :
configuration.getText(
"doclet.Class_0_extends_implements_serializable", classLink,
superClassLink);
Content classNameContent = new RawHtml(className);
li.addContent(HtmlTree.HEADING(HtmlConstants.SERIALIZED_MEMBER_HEADING,
classNameContent));
return li;
}
/**
* Get the serial UID info header.
*
* @return a content tree for the serial uid info header
*/
public Content getSerialUIDInfoHeader() {
HtmlTree dl = new HtmlTree(HtmlTag.DL);
dl.addStyle(HtmlStyle.nameValue);
return dl;
}
/**
* Adds the serial UID info.
*
* @param header the header that will show up before the UID.
* @param serialUID the serial UID to print.
* @param serialUidTree the serial UID content tree to which the serial UID
* content will be added
*/
public void addSerialUIDInfo(String header, String serialUID,
Content serialUidTree) {
Content headerContent = new StringContent(header);
serialUidTree.addContent(HtmlTree.DT(headerContent));
Content serialContent = new StringContent(serialUID);
serialUidTree.addContent(HtmlTree.DD(serialContent));
}
/**
* Get the class serialize content header.
*
* @return a content tree for the class serialize content header
*/
public Content getClassContentHeader() {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
return ul;
}
/**
* Get the serialized content tree section.
*
* @param serializedTreeContent the serialized content tree to be added
* @return a div content tree
*/
public Content getSerializedContent(Content serializedTreeContent) {
Content divContent = HtmlTree.DIV(HtmlStyle.serializedFormContainer,
serializedTreeContent);
return divContent;
}
/**
* Add the footer.
*
* @param serializedTree the serialized tree to be added
*/
public void addFooter(Content serializedTree) {
addNavLinks(false, serializedTree);
addBottom(serializedTree);
}
/**
* {@inheritDoc}
*/
public void printDocument(Content serializedTree) {
printHtmlDocument(null, true, serializedTree);
}
private void tableHeader() {
tableIndexSummary();
trBgcolorStyle("#CCCCFF", "TableSubHeadingColor");
}
private void tableFooter() {
fontEnd();
thEnd(); trEnd(); tableEnd();
}
/**
* Return an instance of a SerialFieldWriter.
*
* @return an instance of a SerialFieldWriter.
*/
public SerialFieldWriter getSerialFieldWriter(ClassDoc classDoc) {
return new HtmlSerialFieldWriter(this, classDoc);
}
/**
* Return an instance of a SerialMethodWriter.
*
* @return an instance of a SerialMethodWriter.
*/
public SerialMethodWriter getSerialMethodWriter(ClassDoc classDoc) {
return new HtmlSerialMethodWriter(this, classDoc);
}
}
| 8,288 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractMemberWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.util.*;
import java.lang.reflect.Modifier;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.internal.toolkit.taglets.*;
/**
* The base class for member writers.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Jamie Ho (Re-write)
* @author Bhavesh Patel (Modified)
*/
public abstract class AbstractMemberWriter {
protected boolean printedSummaryHeader = false;
protected final SubWriterHolderWriter writer;
protected final ClassDoc classdoc;
public final boolean nodepr;
public AbstractMemberWriter(SubWriterHolderWriter writer,
ClassDoc classdoc) {
this.writer = writer;
this.nodepr = configuration().nodeprecated;
this.classdoc = classdoc;
}
public AbstractMemberWriter(SubWriterHolderWriter writer) {
this(writer, null);
}
/*** abstracts ***/
/**
* Add the summary label for the member.
*
* @param memberTree the content tree to which the label will be added
*/
public abstract void addSummaryLabel(Content memberTree);
/**
* Get the summary for the member summary table.
*
* @return a string for the table summary
*/
public abstract String getTableSummary();
/**
* Get the caption for the member summary table.
*
* @return a string for the table caption
*/
public abstract String getCaption();
/**
* Get the summary table header for the member.
*
* @param member the member to be documented
* @return the summary table header
*/
public abstract String[] getSummaryTableHeader(ProgramElementDoc member);
/**
* Add inherited summary lable for the member.
*
* @param cd the class doc to which to link to
* @param inheritedTree the content tree to which the inherited summary label will be added
*/
public abstract void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree);
/**
* Add the anchor for the summary section of the member.
*
* @param cd the class doc to be documented
* @param memberTree the content tree to which the summary anchor will be added
*/
public abstract void addSummaryAnchor(ClassDoc cd, Content memberTree);
/**
* Add the anchor for the inherited summary section of the member.
*
* @param cd the class doc to be documented
* @param inheritedTree the content tree to which the inherited summary anchor will be added
*/
public abstract void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree);
/**
* Add the summary type for the member.
*
* @param member the member to be documented
* @param tdSummaryType the content tree to which the type will be added
*/
protected abstract void addSummaryType(ProgramElementDoc member,
Content tdSummaryType);
/**
* Add the summary link for the member.
*
* @param cd the class doc to be documented
* @param member the member to be documented
* @param tdSummary the content tree to which the link will be added
*/
protected void addSummaryLink(ClassDoc cd, ProgramElementDoc member,
Content tdSummary) {
addSummaryLink(LinkInfoImpl.CONTEXT_MEMBER, cd, member, tdSummary);
}
/**
* Add the summary link for the member.
*
* @param context the id of the context where the link will be printed
* @param cd the class doc to be documented
* @param member the member to be documented
* @param tdSummary the content tree to which the summary link will be added
*/
protected abstract void addSummaryLink(int context,
ClassDoc cd, ProgramElementDoc member, Content tdSummary);
/**
* Add the inherited summary link for the member.
*
* @param cd the class doc to be documented
* @param member the member to be documented
* @param linksTree the content tree to which the inherited summary link will be added
*/
protected abstract void addInheritedSummaryLink(ClassDoc cd,
ProgramElementDoc member, Content linksTree);
/**
* Get the deprecated link.
*
* @param member the member being linked to
* @return a content tree representing the link
*/
protected abstract Content getDeprecatedLink(ProgramElementDoc member);
/**
* Get the navigation summary link.
*
* @param cd the class doc to be documented
* @param link true if its a link else the label to be printed
* @return a content tree for the navigation summary link.
*/
protected abstract Content getNavSummaryLink(ClassDoc cd, boolean link);
/**
* Add the navigation detail link.
*
* @param link true if its a link else the label to be printed
* @param liNav the content tree to which the navigation detail link will be added
*/
protected abstract void addNavDetailLink(boolean link, Content liNav);
/*** ***/
protected void print(String str) {
writer.print(str);
writer.displayLength += str.length();
}
protected void print(char ch) {
writer.print(ch);
writer.displayLength++;
}
protected void strong(String str) {
writer.strong(str);
writer.displayLength += str.length();
}
/**
* Add the member name to the content tree and modifies the display length.
*
* @param name the member name to be added to the content tree.
* @param htmltree the content tree to which the name will be added.
*/
protected void addName(String name, Content htmltree) {
htmltree.addContent(name);
writer.displayLength += name.length();
}
/**
* Return a string describing the access modifier flags.
* Don't include native or synchronized.
*
* The modifier names are returned in canonical order, as
* specified by <em>The Java Language Specification</em>.
*/
protected String modifierString(MemberDoc member) {
int ms = member.modifierSpecifier();
int no = Modifier.NATIVE | Modifier.SYNCHRONIZED;
return Modifier.toString(ms & ~no);
}
protected String typeString(MemberDoc member) {
String type = "";
if (member instanceof MethodDoc) {
type = ((MethodDoc)member).returnType().toString();
} else if (member instanceof FieldDoc) {
type = ((FieldDoc)member).type().toString();
}
return type;
}
/**
* Add the modifier for the member.
*
* @param member the member for which teh modifier will be added.
* @param htmltree the content tree to which the modifier information will be added.
*/
protected void addModifiers(MemberDoc member, Content htmltree) {
String mod = modifierString(member);
// According to JLS, we should not be showing public modifier for
// interface methods.
if ((member.isField() || member.isMethod()) &&
writer instanceof ClassWriterImpl &&
((ClassWriterImpl) writer).getClassDoc().isInterface()) {
mod = Util.replaceText(mod, "public", "").trim();
}
if(mod.length() > 0) {
htmltree.addContent(mod);
htmltree.addContent(writer.getSpace());
}
}
protected String makeSpace(int len) {
if (len <= 0) {
return "";
}
StringBuffer sb = new StringBuffer(len);
for(int i = 0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
/**
* Add the modifier and type for the member in the member summary.
*
* @param member the member to add the type for
* @param type the type to add
* @param tdSummaryType the content tree to which the modified and type will be added
*/
protected void addModifierAndType(ProgramElementDoc member, Type type,
Content tdSummaryType) {
HtmlTree code = new HtmlTree(HtmlTag.CODE);
addModifier(member, code);
if (type == null) {
if (member.isClass()) {
code.addContent("class");
} else {
code.addContent("interface");
}
code.addContent(writer.getSpace());
} else {
if (member instanceof ExecutableMemberDoc &&
((ExecutableMemberDoc) member).typeParameters().length > 0) {
//Code to avoid ugly wrapping in member summary table.
int displayLength = ((AbstractExecutableMemberWriter) this).addTypeParameters(
(ExecutableMemberDoc) member, code);
if (displayLength > 10) {
code.addContent(new HtmlTree(HtmlTag.BR));
}
code.addContent(new RawHtml(
writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_SUMMARY_RETURN_TYPE, type))));
} else {
code.addContent(new RawHtml(
writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_SUMMARY_RETURN_TYPE, type))));
}
}
tdSummaryType.addContent(code);
}
private void printModifier(ProgramElementDoc member) {
if (member.isProtected()) {
print("protected ");
} else if (member.isPrivate()) {
print("private ");
} else if (!member.isPublic()) { // Package private
writer.printText("doclet.Package_private");
print(" ");
}
if (member.isMethod() && ((MethodDoc)member).isAbstract()) {
print("abstract ");
}
if (member.isStatic()) {
print("static");
}
}
/**
* Add the modifier for the member.
*
* @param member the member to add the type for
* @param code the content tree to which the modified will be added
*/
private void addModifier(ProgramElementDoc member, Content code) {
if (member.isProtected()) {
code.addContent("protected ");
} else if (member.isPrivate()) {
code.addContent("private ");
} else if (!member.isPublic()) { // Package private
code.addContent(configuration().getText("doclet.Package_private"));
code.addContent(" ");
}
if (member.isMethod() && ((MethodDoc)member).isAbstract()) {
code.addContent("abstract ");
}
if (member.isStatic()) {
code.addContent("static ");
}
}
/**
* Add the deprecated information for the given member.
*
* @param member the member being documented.
* @param contentTree the content tree to which the deprecated information will be added.
*/
protected void addDeprecatedInfo(ProgramElementDoc member, Content contentTree) {
String output = (new DeprecatedTaglet()).getTagletOutput(member,
writer.getTagletWriterInstance(false)).toString().trim();
if (!output.isEmpty()) {
Content deprecatedContent = new RawHtml(output);
Content div = HtmlTree.DIV(HtmlStyle.block, deprecatedContent);
contentTree.addContent(div);
}
}
/**
* Add the comment for the given member.
*
* @param member the member being documented.
* @param contentTree the content tree to which the comment will be added.
*/
protected void addComment(ProgramElementDoc member, Content htmltree) {
if (member.inlineTags().length > 0) {
writer.addInlineComment(member, htmltree);
}
}
protected String name(ProgramElementDoc member) {
return member.name();
}
/**
* Get the header for the section.
*
* @param member the member being documented.
* @return a header content for the section.
*/
protected Content getHead(MemberDoc member) {
Content memberContent = new RawHtml(member.name());
Content heading = HtmlTree.HEADING(HtmlConstants.MEMBER_HEADING, memberContent);
return heading;
}
/**
* Return true if the given <code>ProgramElement</code> is inherited
* by the class that is being documented.
*
* @param ped The <code>ProgramElement</code> being checked.
* return true if the <code>ProgramElement</code> is being inherited and
* false otherwise.
*/
protected boolean isInherited(ProgramElementDoc ped){
if(ped.isPrivate() || (ped.isPackagePrivate() &&
! ped.containingPackage().equals(classdoc.containingPackage()))){
return false;
}
return true;
}
/**
* Add deprecated information to the documentation tree
*
* @param deprmembers list of deprecated members
* @param headingKey the caption for the deprecated members table
* @param tableSummary the summary for the deprecated members table
* @param tableHeader table headers for the deprecated members table
* @param contentTree the content tree to which the deprecated members table will be added
*/
protected void addDeprecatedAPI(List<Doc> deprmembers, String headingKey,
String tableSummary, String[] tableHeader, Content contentTree) {
if (deprmembers.size() > 0) {
Content table = HtmlTree.TABLE(0, 3, 0, tableSummary,
writer.getTableCaption(configuration().getText(headingKey)));
table.addContent(writer.getSummaryTableHeader(tableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
for (int i = 0; i < deprmembers.size(); i++) {
ProgramElementDoc member =(ProgramElementDoc)deprmembers.get(i);
HtmlTree td = HtmlTree.TD(HtmlStyle.colOne, getDeprecatedLink(member));
if (member.tags("deprecated").length > 0)
writer.addInlineDeprecatedComment(member,
member.tags("deprecated")[0], td);
HtmlTree tr = HtmlTree.TR(td);
if (i%2 == 0)
tr.addStyle(HtmlStyle.altColor);
else
tr.addStyle(HtmlStyle.rowColor);
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
Content ul = HtmlTree.UL(HtmlStyle.blockList, li);
contentTree.addContent(ul);
}
}
/**
* Add use information to the documentation tree.
*
* @param mems list of program elements for which the use information will be added
* @param heading the section heading
* @param tableSummary the summary for the use table
* @param contentTree the content tree to which the use information will be added
*/
protected void addUseInfo(List<? extends ProgramElementDoc> mems,
String heading, String tableSummary, Content contentTree) {
if (mems == null) {
return;
}
List<? extends ProgramElementDoc> members = mems;
boolean printedUseTableHeader = false;
if (members.size() > 0) {
Content table = HtmlTree.TABLE(0, 3, 0, tableSummary,
writer.getTableCaption(heading));
Content tbody = new HtmlTree(HtmlTag.TBODY);
Iterator<? extends ProgramElementDoc> it = members.iterator();
for (int i = 0; it.hasNext(); i++) {
ProgramElementDoc pgmdoc = it.next();
ClassDoc cd = pgmdoc.containingClass();
if (!printedUseTableHeader) {
table.addContent(writer.getSummaryTableHeader(
this.getSummaryTableHeader(pgmdoc), "col"));
printedUseTableHeader = true;
}
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
HtmlTree tdFirst = new HtmlTree(HtmlTag.TD);
tdFirst.addStyle(HtmlStyle.colFirst);
writer.addSummaryType(this, pgmdoc, tdFirst);
tr.addContent(tdFirst);
HtmlTree tdLast = new HtmlTree(HtmlTag.TD);
tdLast.addStyle(HtmlStyle.colLast);
if (cd != null && !(pgmdoc instanceof ConstructorDoc)
&& !(pgmdoc instanceof ClassDoc)) {
HtmlTree name = new HtmlTree(HtmlTag.SPAN);
name.addStyle(HtmlStyle.strong);
name.addContent(cd.name() + ".");
tdLast.addContent(name);
}
addSummaryLink(pgmdoc instanceof ClassDoc ?
LinkInfoImpl.CONTEXT_CLASS_USE : LinkInfoImpl.CONTEXT_MEMBER,
cd, pgmdoc, tdLast);
writer.addSummaryLinkComment(this, pgmdoc, tdLast);
tr.addContent(tdLast);
tbody.addContent(tr);
}
table.addContent(tbody);
contentTree.addContent(table);
}
}
/**
* Add the navigation detail link.
*
* @param members the members to be linked
* @param liNav the content tree to which the navigation detail link will be added
*/
protected void addNavDetailLink(List<?> members, Content liNav) {
addNavDetailLink(members.size() > 0 ? true : false, liNav);
}
/**
* Add the navigation summary link.
*
* @param members members to be linked
* @param visibleMemberMap the visible inherited members map
* @param liNav the content tree to which the navigation summary link will be added
*/
protected void addNavSummaryLink(List<?> members,
VisibleMemberMap visibleMemberMap, Content liNav) {
if (members.size() > 0) {
liNav.addContent(getNavSummaryLink(null, true));
return;
}
ClassDoc icd = classdoc.superclass();
while (icd != null) {
List<?> inhmembers = visibleMemberMap.getMembersFor(icd);
if (inhmembers.size() > 0) {
liNav.addContent(getNavSummaryLink(icd, true));
return;
}
icd = icd.superclass();
}
liNav.addContent(getNavSummaryLink(null, false));
}
protected void serialWarning(SourcePosition pos, String key, String a1, String a2) {
if (configuration().serialwarn) {
ConfigurationImpl.getInstance().getDocletSpecificMsg().warning(pos, key, a1, a2);
}
}
public ProgramElementDoc[] eligibleMembers(ProgramElementDoc[] members) {
return nodepr? Util.excludeDeprecatedMembers(members): members;
}
public ConfigurationImpl configuration() {
return writer.configuration;
}
/**
* Add the member summary for the given class.
*
* @param classDoc the class that is being documented
* @param member the member being documented
* @param firstSentenceTags the first sentence tags to be added to the summary
* @param tableTree the content tree to which the documentation will be added
* @param counter the counter for determing style for the table row
*/
public void addMemberSummary(ClassDoc classDoc, ProgramElementDoc member,
Tag[] firstSentenceTags, Content tableTree, int counter) {
HtmlTree tdSummaryType = new HtmlTree(HtmlTag.TD);
tdSummaryType.addStyle(HtmlStyle.colFirst);
writer.addSummaryType(this, member, tdSummaryType);
HtmlTree tdSummary = new HtmlTree(HtmlTag.TD);
setSummaryColumnStyle(tdSummary);
addSummaryLink(classDoc, member, tdSummary);
writer.addSummaryLinkComment(this, member, firstSentenceTags, tdSummary);
HtmlTree tr = HtmlTree.TR(tdSummaryType);
tr.addContent(tdSummary);
if (counter%2 == 0)
tr.addStyle(HtmlStyle.altColor);
else
tr.addStyle(HtmlStyle.rowColor);
tableTree.addContent(tr);
}
/**
* Set the style for the summary column.
*
* @param tdTree the column for which the style will be set
*/
public void setSummaryColumnStyle(HtmlTree tdTree) {
tdTree.addStyle(HtmlStyle.colLast);
}
/**
* Add inherited member summary for the given class and member.
*
* @param classDoc the class the inherited member belongs to
* @param nestedClass the inherited member that is summarized
* @param isFirst true if this is the first member in the list
* @param isLast true if this is the last member in the list
* @param linksTree the content tree to which the summary will be added
*/
public void addInheritedMemberSummary(ClassDoc classDoc,
ProgramElementDoc nestedClass, boolean isFirst, boolean isLast,
Content linksTree) {
writer.addInheritedMemberSummary(this, classDoc, nestedClass, isFirst,
linksTree);
}
/**
* Get the inherited summary header for the given class.
*
* @param classDoc the class the inherited member belongs to
* @return a content tree for the inherited summary header
*/
public Content getInheritedSummaryHeader(ClassDoc classDoc) {
Content inheritedTree = writer.getMemberTreeHeader();
writer.addInheritedSummaryHeader(this, classDoc, inheritedTree);
return inheritedTree;
}
/**
* Get the inherited summary links tree.
*
* @return a content tree for the inherited summary links
*/
public Content getInheritedSummaryLinksTree() {
return new HtmlTree(HtmlTag.CODE);
}
/**
* Get the summary table tree for the given class.
*
* @param classDoc the class for which the summary table is generated
* @return a content tree for the summary table
*/
public Content getSummaryTableTree(ClassDoc classDoc) {
return writer.getSummaryTableTree(this, classDoc);
}
/**
* Get the member tree to be documented.
*
* @param memberTree the content tree of member to be documented
* @return a content tree that will be added to the class documentation
*/
public Content getMemberTree(Content memberTree) {
return writer.getMemberTree(memberTree);
}
/**
* Get the member tree to be documented.
*
* @param memberTree the content tree of member to be documented
* @param isLastContent true if the content to be added is the last content
* @return a content tree that will be added to the class documentation
*/
public Content getMemberTree(Content memberTree, boolean isLastContent) {
if (isLastContent)
return HtmlTree.UL(HtmlStyle.blockListLast, memberTree);
else
return HtmlTree.UL(HtmlStyle.blockList, memberTree);
}
}
| 24,506 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AbstractPackageIndexWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractPackageIndexWriter.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Abstract class to generate the overview files in
* Frame and Non-Frame format. This will be sub-classed by to
* generate overview-frame.html as well as overview-summary.html.
*
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public abstract class AbstractPackageIndexWriter extends HtmlDocletWriter {
/**
* Array of Packages to be documented.
*/
protected PackageDoc[] packages;
/**
* Constructor. Also initialises the packages variable.
*
* @param filename Name of the package index file to be generated.
*/
public AbstractPackageIndexWriter(ConfigurationImpl configuration,
String filename) throws IOException {
super(configuration, filename);
this.relativepathNoSlash = ".";
packages = configuration.packages;
}
/**
* Adds the navigation bar header to the documentation tree.
*
* @param body the document tree to which the navigation bar header will be added
*/
protected abstract void addNavigationBarHeader(Content body);
/**
* Adds the navigation bar footer to the documentation tree.
*
* @param body the document tree to which the navigation bar footer will be added
*/
protected abstract void addNavigationBarFooter(Content body);
/**
* Adds the overview header to the documentation tree.
*
* @param body the document tree to which the overview header will be added
*/
protected abstract void addOverviewHeader(Content body);
/**
* Adds the packages list to the documentation tree.
*
* @param packages an array of packagedoc objects
* @param text caption for the table
* @param tableSummary summary for the table
* @param body the document tree to which the packages list will be added
*/
protected abstract void addPackagesList(PackageDoc[] packages, String text,
String tableSummary, Content body);
/**
* Generate and prints the contents in the package index file. Call appropriate
* methods from the sub-class in order to generate Frame or Non
* Frame format.
*
* @param title the title of the window.
* @param includeScript boolean set true if windowtitle script is to be included
*/
protected void buildPackageIndexFile(String title, boolean includeScript) throws IOException {
String windowOverview = configuration.getText(title);
Content body = getBody(includeScript, getWindowTitle(windowOverview));
addNavigationBarHeader(body);
addOverviewHeader(body);
addIndex(body);
addOverview(body);
addNavigationBarFooter(body);
printHtmlDocument(configuration.metakeywords.getOverviewMetaKeywords(title,
configuration.doctitle), includeScript, body);
}
/**
* Default to no overview, override to add overview.
*
* @param body the document tree to which the overview will be added
*/
protected void addOverview(Content body) throws IOException {
}
/**
* Adds the frame or non-frame package index to the documentation tree.
*
* @param body the document tree to which the index will be added
*/
protected void addIndex(Content body) {
addIndexContents(packages, "doclet.Package_Summary",
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Package_Summary"),
configuration.getText("doclet.packages")), body);
}
/**
* Adds package index contents. Call appropriate methods from
* the sub-classes. Adds it to the body HtmlTree
*
* @param packages array of packages to be documented
* @param text string which will be used as the heading
* @param tableSummary summary for the table
* @param body the document tree to which the index contents will be added
*/
protected void addIndexContents(PackageDoc[] packages, String text,
String tableSummary, Content body) {
if (packages.length > 0) {
Arrays.sort(packages);
addAllClassesLink(body);
addPackagesList(packages, text, tableSummary, body);
}
}
/**
* Adds the doctitle to the documentation tree, if it is specified on the command line.
*
* @param body the document tree to which the title will be added
*/
protected void addConfigurationTitle(Content body) {
if (configuration.doctitle.length() > 0) {
Content title = new RawHtml(configuration.doctitle);
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING,
HtmlStyle.title, title);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
body.addContent(div);
}
}
/**
* Returns highlighted "Overview", in the navigation bar as this is the
* overview page.
*
* @return a Content object to be added to the documentation tree
*/
protected Content getNavLinkContents() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, overviewLabel);
return li;
}
/**
* Do nothing. This will be overridden in PackageIndexFrameWriter.
*
* @param body the document tree to which the all classes link will be added
*/
protected void addAllClassesLink(Content body) {
}
}
| 6,877 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageTreeWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageTreeWriter.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Class to generate Tree page for a package. The name of the file generated is
* "package-tree.html" and it is generated in the respective package directory.
*
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class PackageTreeWriter extends AbstractTreeWriter {
/**
* Package for which tree is to be generated.
*/
protected PackageDoc packagedoc;
/**
* The previous package name in the alpha-order list.
*/
protected PackageDoc prev;
/**
* The next package name in the alpha-order list.
*/
protected PackageDoc next;
/**
* Constructor.
* @throws IOException
* @throws DocletAbortException
*/
public PackageTreeWriter(ConfigurationImpl configuration,
String path, String filename,
PackageDoc packagedoc,
PackageDoc prev, PackageDoc next)
throws IOException {
super(configuration, path, filename,
new ClassTree(
configuration.classDocCatalog.allClasses(packagedoc),
configuration),
packagedoc);
this.packagedoc = packagedoc;
this.prev = prev;
this.next = next;
}
/**
* Construct a PackageTreeWriter object and then use it to generate the
* package tree page.
*
* @param pkg Package for which tree file is to be generated.
* @param prev Previous package in the alpha-ordered list.
* @param next Next package in the alpha-ordered list.
* @param noDeprecated If true, do not generate any information for
* deprecated classe or interfaces.
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration,
PackageDoc pkg, PackageDoc prev,
PackageDoc next, boolean noDeprecated) {
PackageTreeWriter packgen;
String path = DirectoryManager.getDirectoryPath(pkg);
String filename = "package-tree.html";
try {
packgen = new PackageTreeWriter(configuration, path, filename, pkg,
prev, next);
packgen.generatePackageTreeFile();
packgen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate a separate tree file for each package.
*/
protected void generatePackageTreeFile() throws IOException {
Content body = getPackageTreeHeader();
Content headContent = getResource("doclet.Hierarchy_For_Package",
Util.getPackageName(packagedoc));
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, false,
HtmlStyle.title, headContent);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
if (configuration.packages.length > 1) {
addLinkToMainTree(div);
}
body.addContent(div);
HtmlTree divTree = new HtmlTree(HtmlTag.DIV);
divTree.addStyle(HtmlStyle.contentContainer);
addTree(classtree.baseclasses(), "doclet.Class_Hierarchy", divTree);
addTree(classtree.baseinterfaces(), "doclet.Interface_Hierarchy", divTree);
addTree(classtree.baseAnnotationTypes(), "doclet.Annotation_Type_Hierarchy", divTree);
addTree(classtree.baseEnums(), "doclet.Enum_Hierarchy", divTree);
body.addContent(divTree);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Get the package tree header.
*
* @return a content tree for the header
*/
protected Content getPackageTreeHeader() {
String title = packagedoc.name() + " " +
configuration.getText("doclet.Window_Class_Hierarchy");
Content bodyTree = getBody(true, getWindowTitle(title));
addTop(bodyTree);
addNavLinks(true, bodyTree);
return bodyTree;
}
/**
* Add a link to the tree for all the packages.
*
* @param div the content tree to which the link will be added
*/
protected void addLinkToMainTree(Content div) {
Content span = HtmlTree.SPAN(HtmlStyle.strong,
getResource("doclet.Package_Hierarchies"));
div.addContent(span);
HtmlTree ul = new HtmlTree (HtmlTag.UL);
ul.addStyle(HtmlStyle.horizontal);
ul.addContent(getNavLinkMainTree(configuration.getText("doclet.All_Packages")));
div.addContent(ul);
}
/**
* Get link for the previous package tree file.
*
* @return a content tree for the link
*/
protected Content getNavLinkPrevious() {
if (prev == null) {
return getNavLinkPrevious(null);
} else {
String path = DirectoryManager.getRelativePath(packagedoc.name(),
prev.name());
return getNavLinkPrevious(path + "package-tree.html");
}
}
/**
* Get link for the next package tree file.
*
* @return a content tree for the link
*/
protected Content getNavLinkNext() {
if (next == null) {
return getNavLinkNext(null);
} else {
String path = DirectoryManager.getRelativePath(packagedoc.name(),
next.name());
return getNavLinkNext(path + "package-tree.html");
}
}
/**
* Get link to the package summary page for the package of this tree.
*
* @return a content tree for the package link
*/
protected Content getNavLinkPackage() {
Content linkContent = getHyperLink("package-summary.html", "",
packageLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
}
| 7,464 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
WriterFactoryImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/WriterFactoryImpl.java | /*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.javadoc.*;
/**
* The factory that returns HTML writers.
*
* @author Jamie Ho
* @since 1.5
*/
public class WriterFactoryImpl implements WriterFactory {
private ConfigurationImpl configuration;
public WriterFactoryImpl(ConfigurationImpl configuration) {
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
public ConstantsSummaryWriter getConstantsSummaryWriter() throws Exception {
return new ConstantsSummaryWriterImpl(configuration);
}
/**
* {@inheritDoc}
*/
public PackageSummaryWriter getPackageSummaryWriter(PackageDoc packageDoc,
PackageDoc prevPkg, PackageDoc nextPkg) throws Exception {
return new PackageWriterImpl(ConfigurationImpl.getInstance(), packageDoc,
prevPkg, nextPkg);
}
/**
* {@inheritDoc}
*/
public ClassWriter getClassWriter(ClassDoc classDoc, ClassDoc prevClass,
ClassDoc nextClass, ClassTree classTree)
throws Exception {
return new ClassWriterImpl(classDoc, prevClass, nextClass, classTree);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeWriter getAnnotationTypeWriter(
AnnotationTypeDoc annotationType, Type prevType, Type nextType)
throws Exception {
return new AnnotationTypeWriterImpl(annotationType, prevType, nextType);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeOptionalMemberWriter
getAnnotationTypeOptionalMemberWriter(
AnnotationTypeWriter annotationTypeWriter) throws Exception {
return new AnnotationTypeOptionalMemberWriterImpl(
(SubWriterHolderWriter) annotationTypeWriter,
annotationTypeWriter.getAnnotationTypeDoc());
}
/**
* {@inheritDoc}
*/
public AnnotationTypeRequiredMemberWriter
getAnnotationTypeRequiredMemberWriter(AnnotationTypeWriter annotationTypeWriter) throws Exception {
return new AnnotationTypeRequiredMemberWriterImpl(
(SubWriterHolderWriter) annotationTypeWriter,
annotationTypeWriter.getAnnotationTypeDoc());
}
/**
* {@inheritDoc}
*/
public EnumConstantWriter getEnumConstantWriter(ClassWriter classWriter)
throws Exception {
return new EnumConstantWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public FieldWriter getFieldWriter(ClassWriter classWriter)
throws Exception {
return new FieldWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public MethodWriter getMethodWriter(ClassWriter classWriter)
throws Exception {
return new MethodWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public ConstructorWriter getConstructorWriter(ClassWriter classWriter)
throws Exception {
return new ConstructorWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public MemberSummaryWriter getMemberSummaryWriter(
ClassWriter classWriter, int memberType)
throws Exception {
switch (memberType) {
case VisibleMemberMap.CONSTRUCTORS:
return (ConstructorWriterImpl) getConstructorWriter(classWriter);
case VisibleMemberMap.ENUM_CONSTANTS:
return (EnumConstantWriterImpl) getEnumConstantWriter(classWriter);
case VisibleMemberMap.FIELDS:
return (FieldWriterImpl) getFieldWriter(classWriter);
case VisibleMemberMap.INNERCLASSES:
return new NestedClassWriterImpl((SubWriterHolderWriter)
classWriter, classWriter.getClassDoc());
case VisibleMemberMap.METHODS:
return (MethodWriterImpl) getMethodWriter(classWriter);
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public MemberSummaryWriter getMemberSummaryWriter(
AnnotationTypeWriter annotationTypeWriter, int memberType)
throws Exception {
switch (memberType) {
case VisibleMemberMap.ANNOTATION_TYPE_MEMBER_OPTIONAL:
return (AnnotationTypeOptionalMemberWriterImpl)
getAnnotationTypeOptionalMemberWriter(annotationTypeWriter);
case VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED:
return (AnnotationTypeRequiredMemberWriterImpl)
getAnnotationTypeRequiredMemberWriter(annotationTypeWriter);
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public SerializedFormWriter getSerializedFormWriter() throws Exception {
return new SerializedFormWriterImpl();
}
}
| 6,359 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SplitIndexWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/SplitIndexWriter.java | /*
* Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate Separate Index Files for all the member names with Indexing in
* Unicode Order. This will create "index-files" directory in the current or
* destination directory and will generate separate file for each unicode index.
*
* @see java.lang.Character
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class SplitIndexWriter extends AbstractIndexWriter {
/**
* Previous unicode character index in the built index.
*/
protected int prev;
/**
* Next unicode character in the built index.
*/
protected int next;
/**
* Construct the SplitIndexWriter. Uses path to this file and relative path
* from this file.
*
* @param path Path to the file which is getting generated.
* @param filename Name of the file which is getting genrated.
* @param relpath Relative path from this file to the current directory.
* @param indexbuilder Unicode based Index from {@link IndexBuilder}
*/
public SplitIndexWriter(ConfigurationImpl configuration,
String path, String filename,
String relpath, IndexBuilder indexbuilder,
int prev, int next) throws IOException {
super(configuration, path, filename, relpath, indexbuilder);
this.prev = prev;
this.next = next;
}
/**
* Generate separate index files, for each Unicode character, listing all
* the members starting with the particular unicode character.
*
* @param indexbuilder IndexBuilder built by {@link IndexBuilder}
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration,
IndexBuilder indexbuilder) {
SplitIndexWriter indexgen;
String filename = "";
String path = DirectoryManager.getPath("index-files");
String relpath = DirectoryManager.getRelativePath("index-files");
try {
for (int i = 0; i < indexbuilder.elements().length; i++) {
int j = i + 1;
int prev = (j == 1)? -1: i;
int next = (j == indexbuilder.elements().length)? -1: j + 1;
filename = "index-" + j +".html";
indexgen = new SplitIndexWriter(configuration,
path, filename, relpath,
indexbuilder, prev, next);
indexgen.generateIndexFile((Character)indexbuilder.
elements()[i]);
indexgen.close();
}
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the contents of each index file, with Header, Footer,
* Member Field, Method and Constructor Description.
*
* @param unicode Unicode character referring to the character for the
* index.
*/
protected void generateIndexFile(Character unicode) throws IOException {
String title = configuration.getText("doclet.Window_Split_Index",
unicode.toString());
Content body = getBody(true, getWindowTitle(title));
addTop(body);
addNavLinks(true, body);
HtmlTree divTree = new HtmlTree(HtmlTag.DIV);
divTree.addStyle(HtmlStyle.contentContainer);
addLinksForIndexes(divTree);
addContents(unicode, indexbuilder.getMemberList(unicode), divTree);
addLinksForIndexes(divTree);
body.addContent(divTree);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Add links for all the Index Files per unicode character.
*
* @param contentTree the content tree to which the links for indexes will be added
*/
protected void addLinksForIndexes(Content contentTree) {
Object[] unicodeChars = indexbuilder.elements();
for (int i = 0; i < unicodeChars.length; i++) {
int j = i + 1;
contentTree.addContent(getHyperLink("index-" + j + ".html",
new StringContent(unicodeChars[i].toString())));
contentTree.addContent(getSpace());
}
}
/**
* Get link to the previous unicode character.
*
* @return a content tree for the link
*/
public Content getNavLinkPrevious() {
Content prevletterLabel = getResource("doclet.Prev_Letter");
if (prev == -1) {
return HtmlTree.LI(prevletterLabel);
}
else {
Content prevLink = getHyperLink("index-" + prev + ".html", "",
prevletterLabel);
return HtmlTree.LI(prevLink);
}
}
/**
* Get link to the next unicode character.
*
* @return a content tree for the link
*/
public Content getNavLinkNext() {
Content nextletterLabel = getResource("doclet.Next_Letter");
if (next == -1) {
return HtmlTree.LI(nextletterLabel);
}
else {
Content nextLink = getHyperLink("index-" + next + ".html","",
nextletterLabel);
return HtmlTree.LI(nextLink);
}
}
}
| 6,899 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
NestedClassWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/NestedClassWriterImpl.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Writes nested class documentation in HTML format.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Jamie Ho (rewrite)
* @author Bhavesh Patel (Modified)
*/
public class NestedClassWriterImpl extends AbstractMemberWriter
implements MemberSummaryWriter {
public NestedClassWriterImpl(SubWriterHolderWriter writer,
ClassDoc classdoc) {
super(writer, classdoc);
}
public NestedClassWriterImpl(SubWriterHolderWriter writer) {
super(writer);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(HtmlConstants.START_OF_NESTED_CLASS_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* Close the writer.
*/
public void close() throws IOException {
writer.close();
}
public int getMemberKind() {
return VisibleMemberMap.INNERCLASSES;
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Nested_Class_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Nested_Class_Summary"),
configuration().getText("doclet.nested_classes"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Nested_Classes");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header;
if (member.isInterface()) {
header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Interface"),
configuration().getText("doclet.Description"))
};
}
else {
header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Class"),
configuration().getText("doclet.Description"))
};
}
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor("nested_class_summary"));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
inheritedTree.addContent(writer.getMarkerAnchor(
"nested_classes_inherited_from_class_" + cd.qualifiedName()));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
Content classLink = new RawHtml(writer.getPreQualifiedClassLink(
LinkInfoImpl.CONTEXT_MEMBER, cd, false));
Content label = new StringContent(cd.isInterface() ?
configuration().getText("doclet.Nested_Classes_Interface_Inherited_From_Interface") :
configuration().getText("doclet.Nested_Classes_Interfaces_Inherited_From_Class"));
Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING,
label);
labelHeading.addContent(writer.getSpace());
labelHeading.addContent(classLink);
inheritedTree.addContent(labelHeading);
}
/**
* {@inheritDoc}
*/
protected void addSummaryLink(int context, ClassDoc cd, ProgramElementDoc member,
Content tdSummary) {
Content strong = HtmlTree.STRONG(new RawHtml(
writer.getLink(new LinkInfoImpl(context, (ClassDoc)member, false))));
Content code = HtmlTree.CODE(strong);
tdSummary.addContent(code);
}
/**
* {@inheritDoc}
*/
protected void addInheritedSummaryLink(ClassDoc cd,
ProgramElementDoc member, Content linksTree) {
linksTree.addContent(new RawHtml(
writer.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
(ClassDoc)member, false))));
}
/**
* {@inheritDoc}
*/
protected void addSummaryType(ProgramElementDoc member,
Content tdSummaryType) {
ClassDoc cd = (ClassDoc)member;
addModifierAndType(cd, null, tdSummaryType);
}
/**
* {@inheritDoc}
*/
protected Content getDeprecatedLink(ProgramElementDoc member) {
return writer.getQualifiedClassLink(LinkInfoImpl.CONTEXT_MEMBER,
(ClassDoc)member);
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", (cd == null) ? "nested_class_summary":
"nested_classes_inherited_from_class_" +
cd.qualifiedName(),
writer.getResource("doclet.navNested"));
} else {
return writer.getResource("doclet.navNested");
}
}
/**
* {@inheritDoc}
*/
protected void addNavDetailLink(boolean link, Content liNav) {
}
}
| 7,047 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeRequiredMemberWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeRequiredMemberWriterImpl.java | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Writes annotation type required member documentation in HTML format.
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
*/
public class AnnotationTypeRequiredMemberWriterImpl extends AbstractMemberWriter
implements AnnotationTypeRequiredMemberWriter, MemberSummaryWriter {
/**
* Construct a new AnnotationTypeRequiredMemberWriterImpl.
*
* @param writer the writer that will write the output.
* @param annotationType the AnnotationType that holds this member.
*/
public AnnotationTypeRequiredMemberWriterImpl(SubWriterHolderWriter writer,
AnnotationTypeDoc annotationType) {
super(writer, annotationType);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(
HtmlConstants.START_OF_ANNOTATION_TYPE_REQUIRED_MEMBER_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* {@inheritDoc}
*/
public void addAnnotationDetailsTreeHeader(ClassDoc classDoc,
Content memberDetailsTree) {
if (!writer.printedAnnotationHeading) {
memberDetailsTree.addContent(writer.getMarkerAnchor(
"annotation_type_element_detail"));
Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
writer.annotationTypeDetailsLabel);
memberDetailsTree.addContent(heading);
writer.printedAnnotationHeading = true;
}
}
/**
* {@inheritDoc}
*/
public Content getAnnotationDocTreeHeader(MemberDoc member,
Content annotationDetailsTree) {
annotationDetailsTree.addContent(
writer.getMarkerAnchor(member.name() +
((ExecutableMemberDoc) member).signature()));
Content annotationDocTree = writer.getMemberTreeHeader();
Content heading = new HtmlTree(HtmlConstants.MEMBER_HEADING);
heading.addContent(member.name());
annotationDocTree.addContent(heading);
return annotationDocTree;
}
/**
* {@inheritDoc}
*/
public Content getSignature(MemberDoc member) {
Content pre = new HtmlTree(HtmlTag.PRE);
writer.addAnnotationInfo(member, pre);
addModifiers(member, pre);
Content link = new RawHtml(
writer.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
getType(member))));
pre.addContent(link);
pre.addContent(writer.getSpace());
if (configuration().linksource) {
Content memberName = new StringContent(member.name());
writer.addSrcLink(member, memberName, pre);
} else {
addName(member.name(), pre);
}
return pre;
}
/**
* {@inheritDoc}
*/
public void addDeprecated(MemberDoc member, Content annotationDocTree) {
addDeprecatedInfo(member, annotationDocTree);
}
/**
* {@inheritDoc}
*/
public void addComments(MemberDoc member, Content annotationDocTree) {
addComment(member, annotationDocTree);
}
/**
* {@inheritDoc}
*/
public void addTags(MemberDoc member, Content annotationDocTree) {
writer.addTagsInfo(member, annotationDocTree);
}
/**
* {@inheritDoc}
*/
public Content getAnnotationDetails(Content annotationDetailsTree) {
return getMemberTree(annotationDetailsTree);
}
/**
* {@inheritDoc}
*/
public Content getAnnotationDoc(Content annotationDocTree,
boolean isLastContent) {
return getMemberTree(annotationDocTree, isLastContent);
}
/**
* Close the writer.
*/
public void close() throws IOException {
writer.close();
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Annotation_Type_Required_Member_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Annotation_Type_Required_Member_Summary"),
configuration().getText("doclet.annotation_type_required_members"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Annotation_Type_Required_Members");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Annotation_Type_Required_Member"),
configuration().getText("doclet.Description"))
};
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor(
"annotation_type_required_element_summary"));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
}
/**
* {@inheritDoc}
*/
protected void addSummaryLink(int context, ClassDoc cd, ProgramElementDoc member,
Content tdSummary) {
Content strong = HtmlTree.STRONG(new RawHtml(
writer.getDocLink(context, (MemberDoc) member, member.name(), false)));
Content code = HtmlTree.CODE(strong);
tdSummary.addContent(code);
}
/**
* {@inheritDoc}
*/
protected void addInheritedSummaryLink(ClassDoc cd,
ProgramElementDoc member, Content linksTree) {
//Not applicable.
}
/**
* {@inheritDoc}
*/
protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) {
MemberDoc m = (MemberDoc)member;
addModifierAndType(m, getType(m), tdSummaryType);
}
/**
* {@inheritDoc}
*/
protected Content getDeprecatedLink(ProgramElementDoc member) {
return writer.getDocLink(LinkInfoImpl.CONTEXT_MEMBER,
(MemberDoc) member, ((MemberDoc)member).qualifiedName());
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", "annotation_type_required_element_summary",
writer.getResource("doclet.navAnnotationTypeRequiredMember"));
} else {
return writer.getResource("doclet.navAnnotationTypeRequiredMember");
}
}
/**
* {@inheritDoc}
*/
protected void addNavDetailLink(boolean link, Content liNav) {
if (link) {
liNav.addContent(writer.getHyperLink("", "annotation_type_element_detail",
writer.getResource("doclet.navAnnotationTypeMember")));
} else {
liNav.addContent(writer.getResource("doclet.navAnnotationTypeMember"));
}
}
private Type getType(MemberDoc member) {
if (member instanceof FieldDoc) {
return ((FieldDoc) member).type();
} else {
return ((MethodDoc) member).returnType();
}
}
}
| 9,141 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SourceToHTMLConverter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/SourceToHTMLConverter.java | /*
* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import javax.tools.FileObject;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Converts Java Source Code to HTML.
*
* This code is not part of an API.
* It is implementation that is subject to change.
* Do not use it as an API
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
* @since 1.4
*/
public class SourceToHTMLConverter {
/**
* The number of trailing blank lines at the end of the page.
* This is inserted so that anchors at the bottom of small pages
* can be reached.
*/
private static final int NUM_BLANK_LINES = 60;
/**
* New line to be added to the documentation.
*/
private static final Content NEW_LINE = new RawHtml(DocletConstants.NL);
/**
* Relative path from the documentation root to the file that is being
* generated.
*/
private static String relativePath = "";
/**
* Source is converted to HTML using static methods below.
*/
private SourceToHTMLConverter() {}
/**
* Convert the Classes in the given RootDoc to an HTML.
*
* @param configuration the configuration.
* @param rd the RootDoc to convert.
* @param outputdir the name of the directory to output to.
*/
public static void convertRoot(ConfigurationImpl configuration, RootDoc rd,
String outputdir) {
if (rd == null || outputdir == null) {
return;
}
PackageDoc[] pds = rd.specifiedPackages();
for (int i = 0; i < pds.length; i++) {
// If -nodeprecated option is set and the package is marked as deprecated,
// do not convert the package files to HTML.
if (!(configuration.nodeprecated && Util.isDeprecated(pds[i])))
convertPackage(configuration, pds[i], outputdir);
}
ClassDoc[] cds = rd.specifiedClasses();
for (int i = 0; i < cds.length; i++) {
// If -nodeprecated option is set and the class is marked as deprecated
// or the containing package is deprecated, do not convert the
// package files to HTML.
if (!(configuration.nodeprecated &&
(Util.isDeprecated(cds[i]) || Util.isDeprecated(cds[i].containingPackage()))))
convertClass(configuration, cds[i],
getPackageOutputDir(outputdir, cds[i].containingPackage()));
}
}
/**
* Convert the Classes in the given Package to an HTML.
*
* @param configuration the configuration.
* @param pd the Package to convert.
* @param outputdir the name of the directory to output to.
*/
public static void convertPackage(ConfigurationImpl configuration, PackageDoc pd,
String outputdir) {
if (pd == null || outputdir == null) {
return;
}
String classOutputdir = getPackageOutputDir(outputdir, pd);
ClassDoc[] cds = pd.allClasses();
for (int i = 0; i < cds.length; i++) {
// If -nodeprecated option is set and the class is marked as deprecated,
// do not convert the package files to HTML. We do not check for
// containing package deprecation since it is already check in
// the calling method above.
if (!(configuration.nodeprecated && Util.isDeprecated(cds[i])))
convertClass(configuration, cds[i], classOutputdir);
}
}
/**
* Return the directory write output to for the given package.
*
* @param outputDir the directory to output to.
* @param pd the Package to generate output for.
* @return the package output directory as a String.
*/
private static String getPackageOutputDir(String outputDir, PackageDoc pd) {
return outputDir + File.separator +
DirectoryManager.getDirectoryPath(pd) + File.separator;
}
/**
* Convert the given Class to an HTML.
*
* @param configuration the configuration.
* @param cd the class to convert.
* @param outputdir the name of the directory to output to.
*/
public static void convertClass(ConfigurationImpl configuration, ClassDoc cd,
String outputdir) {
if (cd == null || outputdir == null) {
return;
}
try {
SourcePosition sp = cd.position();
if (sp == null)
return;
Reader r;
// temp hack until we can update SourcePosition API.
if (sp instanceof com.sun.tools.javadoc.SourcePositionImpl) {
FileObject fo = ((com.sun.tools.javadoc.SourcePositionImpl) sp).fileObject();
if (fo == null)
return;
r = fo.openReader(true);
} else {
File file = sp.file();
if (file == null)
return;
r = new FileReader(file);
}
LineNumberReader reader = new LineNumberReader(r);
int lineno = 1;
String line;
relativePath = DirectoryManager.getRelativePath(DocletConstants.SOURCE_OUTPUT_DIR_NAME) +
DirectoryManager.getRelativePath(cd.containingPackage());
Content body = getHeader();
Content pre = new HtmlTree(HtmlTag.PRE);
try {
while ((line = reader.readLine()) != null) {
addLineNo(pre, lineno);
addLine(pre, line, configuration.sourcetab, lineno);
lineno++;
}
} finally {
reader.close();
}
addBlankLines(pre);
Content div = HtmlTree.DIV(HtmlStyle.sourceContainer, pre);
body.addContent(div);
writeToFile(body, outputdir, cd.name(), configuration);
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Write the output to the file.
*
* @param body the documentation content to be written to the file.
* @param outputDir the directory to output to.
* @param className the name of the class that I am converting to HTML.
* @param configuration the Doclet configuration to pass notices to.
*/
private static void writeToFile(Content body, String outputDir,
String className, ConfigurationImpl configuration) throws IOException {
Content htmlDocType = DocType.Transitional();
Content head = new HtmlTree(HtmlTag.HEAD);
head.addContent(HtmlTree.TITLE(new StringContent(
configuration.getText("doclet.Window_Source_title"))));
head.addContent(getStyleSheetProperties(configuration));
Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
head, body);
Content htmlDocument = new HtmlDocument(htmlDocType, htmlTree);
File dir = new File(outputDir);
dir.mkdirs();
File newFile = new File(dir, className + ".html");
configuration.message.notice("doclet.Generating_0", newFile.getPath());
FileOutputStream fout = new FileOutputStream(newFile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout));
bw.write(htmlDocument.toString());
bw.close();
fout.close();
}
/**
* Returns a link to the stylesheet file.
*
* @param configuration the doclet configuration for the current run of javadoc
* @return an HtmlTree for the lINK tag which provides the stylesheet location
*/
public static HtmlTree getStyleSheetProperties(ConfigurationImpl configuration) {
String filename = configuration.stylesheetfile;
if (filename.length() > 0) {
File stylefile = new File(filename);
String parent = stylefile.getParent();
filename = (parent == null)?
filename:
filename.substring(parent.length() + 1);
} else {
filename = "stylesheet.css";
}
filename = relativePath + filename;
HtmlTree link = HtmlTree.LINK("stylesheet", "text/css", filename, "Style");
return link;
}
/**
* Get the header.
*
* @return the header content for the HTML file
*/
private static Content getHeader() {
return new HtmlTree(HtmlTag.BODY);
}
/**
* Add the line numbers for the source code.
*
* @param pre the content tree to which the line number will be added
* @param lineno The line number
*/
private static void addLineNo(Content pre, int lineno) {
HtmlTree span = new HtmlTree(HtmlTag.SPAN);
span.addStyle(HtmlStyle.sourceLineNo);
if (lineno < 10) {
span.addContent("00" + Integer.toString(lineno));
} else if (lineno < 100) {
span.addContent("0" + Integer.toString(lineno));
} else {
span.addContent(Integer.toString(lineno));
}
pre.addContent(span);
}
/**
* Add a line from source to the HTML file that is generated.
*
* @param pre the content tree to which the line will be added.
* @param line the string to format.
* @param tabLength the number of spaces for each tab.
* @param currentLineNo the current number.
*/
private static void addLine(Content pre, String line, int tabLength,
int currentLineNo) {
if (line != null) {
StringBuilder lineBuffer = new StringBuilder(Util.escapeHtmlChars(line));
Util.replaceTabs(tabLength, lineBuffer);
pre.addContent(new RawHtml(lineBuffer.toString()));
Content anchor = HtmlTree.A_NAME("line." + Integer.toString(currentLineNo));
pre.addContent(anchor);
pre.addContent(NEW_LINE);
}
}
/**
* Add trailing blank lines at the end of the page.
*
* @param pre the content tree to which the blank lines will be added.
*/
private static void addBlankLines(Content pre) {
for (int i = 0; i < NUM_BLANK_LINES; i++) {
pre.addContent(NEW_LINE);
}
}
/**
* Given a <code>Doc</code>, return an anchor name for it.
*
* @param d the <code>Doc</code> to check.
* @return the name of the anchor.
*/
public static String getAnchorName(Doc d) {
return "line." + d.position().line();
}
}
| 11,853 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TagletOutputImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/TagletOutputImpl.java | /*
* Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.tools.doclets.internal.toolkit.taglets.*;
/**
* The output for HTML taglets.
*
* @since 1.5
* @author Jamie Ho
*/
public class TagletOutputImpl implements TagletOutput {
private StringBuffer output;
public TagletOutputImpl(String o) {
setOutput(o);
}
/**
* {@inheritDoc}
*/
public void setOutput (Object o) {
output = new StringBuffer(o == null ? "" : (String) o);
}
/**
* {@inheritDoc}
*/
public void appendOutput(TagletOutput o) {
output.append(o.toString());
}
/**
* {@inheritDoc}
*/
public boolean hasInheritDocTag() {
return output.indexOf(InheritDocTaglet.INHERIT_DOC_INLINE_TAG) != -1;
}
public String toString() {
return output.toString();
}
/**
* Check whether the taglet output is empty.
*/
public boolean isEmpty() {
return (toString().trim().isEmpty());
}
}
| 2,214 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MethodWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/MethodWriterImpl.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Writes method documentation in HTML format.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Jamie Ho (rewrite)
* @author Bhavesh Patel (Modified)
*/
public class MethodWriterImpl extends AbstractExecutableMemberWriter
implements MethodWriter, MemberSummaryWriter {
/**
* Construct a new MethodWriterImpl.
*
* @param writer the writer for the class that the methods belong to.
* @param classDoc the class being documented.
*/
public MethodWriterImpl(SubWriterHolderWriter writer, ClassDoc classDoc) {
super(writer, classDoc);
}
/**
* Construct a new MethodWriterImpl.
*
* @param writer The writer for the class that the methods belong to.
*/
public MethodWriterImpl(SubWriterHolderWriter writer) {
super(writer);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(HtmlConstants.START_OF_METHOD_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* {@inheritDoc}
*/
public Content getMethodDetailsTreeHeader(ClassDoc classDoc,
Content memberDetailsTree) {
memberDetailsTree.addContent(HtmlConstants.START_OF_METHOD_DETAILS);
Content methodDetailsTree = writer.getMemberTreeHeader();
methodDetailsTree.addContent(writer.getMarkerAnchor("method_detail"));
Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
writer.methodDetailsLabel);
methodDetailsTree.addContent(heading);
return methodDetailsTree;
}
/**
* {@inheritDoc}
*/
public Content getMethodDocTreeHeader(MethodDoc method,
Content methodDetailsTree) {
String erasureAnchor;
if ((erasureAnchor = getErasureAnchor(method)) != null) {
methodDetailsTree.addContent(writer.getMarkerAnchor((erasureAnchor)));
}
methodDetailsTree.addContent(
writer.getMarkerAnchor(writer.getAnchor(method)));
Content methodDocTree = writer.getMemberTreeHeader();
Content heading = new HtmlTree(HtmlConstants.MEMBER_HEADING);
heading.addContent(method.name());
methodDocTree.addContent(heading);
return methodDocTree;
}
/**
* Get the signature for the given method.
*
* @param method the method being documented.
* @return a content object for the signature
*/
public Content getSignature(MethodDoc method) {
writer.displayLength = 0;
Content pre = new HtmlTree(HtmlTag.PRE);
writer.addAnnotationInfo(method, pre);
addModifiers(method, pre);
addTypeParameters(method, pre);
addReturnType(method, pre);
if (configuration().linksource) {
Content methodName = new StringContent(method.name());
writer.addSrcLink(method, methodName, pre);
} else {
addName(method.name(), pre);
}
addParameters(method, pre);
addExceptions(method, pre);
return pre;
}
/**
* {@inheritDoc}
*/
public void addDeprecated(MethodDoc method, Content methodDocTree) {
addDeprecatedInfo(method, methodDocTree);
}
/**
* {@inheritDoc}
*/
public void addComments(Type holder, MethodDoc method, Content methodDocTree) {
ClassDoc holderClassDoc = holder.asClassDoc();
if (method.inlineTags().length > 0) {
if (holder.asClassDoc().equals(classdoc) ||
(! (holderClassDoc.isPublic() ||
Util.isLinkable(holderClassDoc, configuration())))) {
writer.addInlineComment(method, methodDocTree);
} else {
Content link = new RawHtml(
writer.getDocLink(LinkInfoImpl.CONTEXT_METHOD_DOC_COPY,
holder.asClassDoc(), method,
holder.asClassDoc().isIncluded() ?
holder.typeName() : holder.qualifiedTypeName(),
false));
Content codelLink = HtmlTree.CODE(link);
Content strong = HtmlTree.STRONG(holder.asClassDoc().isClass()?
writer.descfrmClassLabel : writer.descfrmInterfaceLabel);
strong.addContent(writer.getSpace());
strong.addContent(codelLink);
methodDocTree.addContent(HtmlTree.DIV(HtmlStyle.block, strong));
writer.addInlineComment(method, methodDocTree);
}
}
}
/**
* {@inheritDoc}
*/
public void addTags(MethodDoc method, Content methodDocTree) {
writer.addTagsInfo(method, methodDocTree);
}
/**
* {@inheritDoc}
*/
public Content getMethodDetails(Content methodDetailsTree) {
return getMemberTree(methodDetailsTree);
}
/**
* {@inheritDoc}
*/
public Content getMethodDoc(Content methodDocTree,
boolean isLastContent) {
return getMemberTree(methodDocTree, isLastContent);
}
/**
* Close the writer.
*/
public void close() throws IOException {
writer.close();
}
public int getMemberKind() {
return VisibleMemberMap.METHODS;
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Method_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Method_Summary"),
configuration().getText("doclet.methods"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Methods");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header = new String[] {
writer.getModifierTypeHeader(),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Method"),
configuration().getText("doclet.Description"))
};
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor("method_summary"));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
inheritedTree.addContent(writer.getMarkerAnchor(
"methods_inherited_from_class_" +
configuration().getClassName(cd)));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
Content classLink = new RawHtml(writer.getPreQualifiedClassLink(
LinkInfoImpl.CONTEXT_MEMBER, cd, false));
Content label = new StringContent(cd.isClass() ?
configuration().getText("doclet.Methods_Inherited_From_Class") :
configuration().getText("doclet.Methods_Inherited_From_Interface"));
Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING,
label);
labelHeading.addContent(writer.getSpace());
labelHeading.addContent(classLink);
inheritedTree.addContent(labelHeading);
}
/**
* {@inheritDoc}
*/
protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) {
MethodDoc meth = (MethodDoc)member;
addModifierAndType(meth, meth.returnType(), tdSummaryType);
}
/**
* {@inheritDoc}
*/
protected static void addOverridden(HtmlDocletWriter writer,
Type overriddenType, MethodDoc method, Content dl) {
if(writer.configuration.nocomment){
return;
}
ClassDoc holderClassDoc = overriddenType.asClassDoc();
if (! (holderClassDoc.isPublic() ||
Util.isLinkable(holderClassDoc, writer.configuration()))) {
//This is an implementation detail that should not be documented.
return;
}
if (overriddenType.asClassDoc().isIncluded() && ! method.isIncluded()) {
//The class is included but the method is not. That means that it
//is not visible so don't document this.
return;
}
Content label = writer.overridesLabel;
int context = LinkInfoImpl.CONTEXT_METHOD_OVERRIDES;
if (method != null) {
if(overriddenType.asClassDoc().isAbstract() && method.isAbstract()){
//Abstract method is implemented from abstract class,
//not overridden
label = writer.specifiedByLabel;
context = LinkInfoImpl.CONTEXT_METHOD_SPECIFIED_BY;
}
Content dt = HtmlTree.DT(HtmlTree.STRONG(label));
dl.addContent(dt);
Content overriddenTypeLink = new RawHtml(
writer.getLink(new LinkInfoImpl(context, overriddenType)));
Content codeOverridenTypeLink = HtmlTree.CODE(overriddenTypeLink);
String name = method.name();
Content methlink = new RawHtml(writer.getLink(
new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
overriddenType.asClassDoc(),
writer.getAnchor(method), name, false)));
Content codeMethLink = HtmlTree.CODE(methlink);
Content dd = HtmlTree.DD(codeMethLink);
dd.addContent(writer.getSpace());
dd.addContent(writer.getResource("doclet.in_class"));
dd.addContent(writer.getSpace());
dd.addContent(codeOverridenTypeLink);
dl.addContent(dd);
}
}
/**
* Parse the <Code> tag and return the text.
*/
protected String parseCodeTag(String tag){
if(tag == null){
return "";
}
String lc = tag.toLowerCase();
int begin = lc.indexOf("<code>");
int end = lc.indexOf("</code>");
if(begin == -1 || end == -1 || end <= begin){
return tag;
} else {
return tag.substring(begin + 6, end);
}
}
/**
* {@inheritDoc}
*/
protected static void addImplementsInfo(HtmlDocletWriter writer,
MethodDoc method, Content dl) {
if(writer.configuration.nocomment){
return;
}
ImplementedMethods implementedMethodsFinder =
new ImplementedMethods(method, writer.configuration);
MethodDoc[] implementedMethods = implementedMethodsFinder.build();
for (int i = 0; i < implementedMethods.length; i++) {
MethodDoc implementedMeth = implementedMethods[i];
Type intfac = implementedMethodsFinder.getMethodHolder(implementedMeth);
Content intfaclink = new RawHtml(writer.getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_METHOD_SPECIFIED_BY, intfac)));
Content codeIntfacLink = HtmlTree.CODE(intfaclink);
Content dt = HtmlTree.DT(HtmlTree.STRONG(writer.specifiedByLabel));
dl.addContent(dt);
Content methlink = new RawHtml(writer.getDocLink(
LinkInfoImpl.CONTEXT_MEMBER, implementedMeth,
implementedMeth.name(), false));
Content codeMethLink = HtmlTree.CODE(methlink);
Content dd = HtmlTree.DD(codeMethLink);
dd.addContent(writer.getSpace());
dd.addContent(writer.getResource("doclet.in_interface"));
dd.addContent(writer.getSpace());
dd.addContent(codeIntfacLink);
dl.addContent(dd);
}
}
/**
* Add the return type.
*
* @param method the method being documented.
* @param htmltree the content tree to which the return type will be added
*/
protected void addReturnType(MethodDoc method, Content htmltree) {
Type type = method.returnType();
if (type != null) {
Content linkContent = new RawHtml(writer.getLink(
new LinkInfoImpl(LinkInfoImpl.CONTEXT_RETURN_TYPE, type)));
htmltree.addContent(linkContent);
htmltree.addContent(writer.getSpace());
}
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", (cd == null)?
"method_summary":
"methods_inherited_from_class_" +
configuration().getClassName(cd),
writer.getResource("doclet.navMethod"));
} else {
return writer.getResource("doclet.navMethod");
}
}
/**
* {@inheritDoc}
*/
protected void addNavDetailLink(boolean link, Content liNav) {
if (link) {
liNav.addContent(writer.getHyperLink("", "method_detail",
writer.getResource("doclet.navMethod")));
} else {
liNav.addContent(writer.getResource("doclet.navMethod"));
}
}
}
| 15,012 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageUseWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageUseWriter.java | /*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Generate package usage information.
*
* @author Robert G. Field
* @author Bhavesh Patel (Modified)
*/
public class PackageUseWriter extends SubWriterHolderWriter {
final PackageDoc pkgdoc;
final SortedMap<String,Set<ClassDoc>> usingPackageToUsedClasses = new TreeMap<String,Set<ClassDoc>>();
/**
* Constructor.
*
* @param filename the file to be generated.
* @throws IOException
* @throws DocletAbortException
*/
public PackageUseWriter(ConfigurationImpl configuration,
ClassUseMapper mapper, String filename,
PackageDoc pkgdoc) throws IOException {
super(configuration, DirectoryManager.getDirectoryPath(pkgdoc),
filename,
DirectoryManager.getRelativePath(pkgdoc.name()));
this.pkgdoc = pkgdoc;
// by examining all classes in this package, find what packages
// use these classes - produce a map between using package and
// used classes.
ClassDoc[] content = pkgdoc.allClasses();
for (int i = 0; i < content.length; ++i) {
ClassDoc usedClass = content[i];
Set<ClassDoc> usingClasses = mapper.classToClass.get(usedClass.qualifiedName());
if (usingClasses != null) {
for (Iterator<ClassDoc> it = usingClasses.iterator(); it.hasNext(); ) {
ClassDoc usingClass = it.next();
PackageDoc usingPackage = usingClass.containingPackage();
Set<ClassDoc> usedClasses = usingPackageToUsedClasses
.get(usingPackage.name());
if (usedClasses == null) {
usedClasses = new TreeSet<ClassDoc>();
usingPackageToUsedClasses.put(Util.getPackageName(usingPackage),
usedClasses);
}
usedClasses.add(usedClass);
}
}
}
}
/**
* Generate a class page.
*
* @param configuration the current configuration of the doclet.
* @param mapper the mapping of the class usage.
* @param pkgdoc the package doc being documented.
*/
public static void generate(ConfigurationImpl configuration,
ClassUseMapper mapper, PackageDoc pkgdoc) {
PackageUseWriter pkgusegen;
String filename = "package-use.html";
try {
pkgusegen = new PackageUseWriter(configuration,
mapper, filename, pkgdoc);
pkgusegen.generatePackageUseFile();
pkgusegen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the package use list.
*/
protected void generatePackageUseFile() throws IOException {
Content body = getPackageUseHeader();
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.contentContainer);
if (usingPackageToUsedClasses.isEmpty()) {
div.addContent(getResource(
"doclet.ClassUse_No.usage.of.0", pkgdoc.name()));
} else {
addPackageUse(div);
}
body.addContent(div);
addNavLinks(false, body);
addBottom(body);
printHtmlDocument(null, true, body);
}
/**
* Add the package use information.
*
* @param contentTree the content tree to which the package use information will be added
*/
protected void addPackageUse(Content contentTree) throws IOException {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
if (configuration.packages.length > 1) {
addPackageList(ul);
}
addClassList(ul);
contentTree.addContent(ul);
}
/**
* Add the list of packages that use the given package.
*
* @param contentTree the content tree to which the package list will be added
*/
protected void addPackageList(Content contentTree) throws IOException {
Content table = HtmlTree.TABLE(0, 3, 0, useTableSummary,
getTableCaption(configuration().getText(
"doclet.ClassUse_Packages.that.use.0",
getPackageLinkString(pkgdoc, Util.getPackageName(pkgdoc), false))));
table.addContent(getSummaryTableHeader(packageTableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
Iterator<String> it = usingPackageToUsedClasses.keySet().iterator();
for (int i = 0; it.hasNext(); i++) {
PackageDoc pkg = configuration.root.packageNamed(it.next());
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
addPackageUse(pkg, tr);
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
contentTree.addContent(li);
}
/**
* Add the list of classes that use the given package.
*
* @param contentTree the content tree to which the class list will be added
*/
protected void addClassList(Content contentTree) throws IOException {
String[] classTableHeader = new String[] {
configuration.getText("doclet.0_and_1",
configuration.getText("doclet.Class"),
configuration.getText("doclet.Description"))
};
Iterator<String> itp = usingPackageToUsedClasses.keySet().iterator();
while (itp.hasNext()) {
String packageName = itp.next();
PackageDoc usingPackage = configuration.root.packageNamed(packageName);
HtmlTree li = new HtmlTree(HtmlTag.LI);
li.addStyle(HtmlStyle.blockList);
if (usingPackage != null) {
li.addContent(getMarkerAnchor(usingPackage.name()));
}
String tableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.classes"));
Content table = HtmlTree.TABLE(0, 3, 0, tableSummary,
getTableCaption(configuration().getText(
"doclet.ClassUse_Classes.in.0.used.by.1",
getPackageLinkString(pkgdoc, Util.getPackageName(pkgdoc), false),
getPackageLinkString(usingPackage,Util.getPackageName(usingPackage), false))));
table.addContent(getSummaryTableHeader(classTableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
Iterator<ClassDoc> itc =
usingPackageToUsedClasses.get(packageName).iterator();
for (int i = 0; itc.hasNext(); i++) {
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i % 2 == 0) {
tr.addStyle(HtmlStyle.altColor);
} else {
tr.addStyle(HtmlStyle.rowColor);
}
addClassRow(itc.next(), packageName, tr);
tbody.addContent(tr);
}
table.addContent(tbody);
li.addContent(table);
contentTree.addContent(li);
}
}
/**
* Add a row for the class that uses the given package.
*
* @param usedClass the class that uses the given package
* @param packageName the name of the package to which the class belongs
* @param contentTree the content tree to which the row will be added
*/
protected void addClassRow(ClassDoc usedClass, String packageName,
Content contentTree) {
String path = pathString(usedClass,
"class-use/" + usedClass.name() + ".html");
Content td = HtmlTree.TD(HtmlStyle.colOne,
getHyperLink(path, packageName, new StringContent(usedClass.name())));
addIndexComment(usedClass, td);
contentTree.addContent(td);
}
/**
* Add the package use information.
*
* @param pkg the package that used the given package
* @param contentTree the content tree to which the information will be added
*/
protected void addPackageUse(PackageDoc pkg, Content contentTree) throws IOException {
Content tdFirst = HtmlTree.TD(HtmlStyle.colFirst,
getHyperLink("", Util.getPackageName(pkg),
new RawHtml(Util.getPackageName(pkg))));
contentTree.addContent(tdFirst);
HtmlTree tdLast = new HtmlTree(HtmlTag.TD);
tdLast.addStyle(HtmlStyle.colLast);
if (pkg != null && pkg.name().length() != 0) {
addSummaryComment(pkg, tdLast);
} else {
tdLast.addContent(getSpace());
}
contentTree.addContent(tdLast);
}
/**
* Get the header for the package use listing.
*
* @return a content tree representing the package use header
*/
protected Content getPackageUseHeader() {
String packageText = configuration.getText("doclet.Package");
String name = pkgdoc.name();
String title = configuration.getText("doclet.Window_ClassUse_Header",
packageText, name);
Content bodyTree = getBody(true, getWindowTitle(title));
addTop(bodyTree);
addNavLinks(true, bodyTree);
Content headContent = getResource("doclet.ClassUse_Title", packageText, name);
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, headContent);
Content div = HtmlTree.DIV(HtmlStyle.header, heading);
bodyTree.addContent(div);
return bodyTree;
}
/**
* Get this package link.
*
* @return a content tree for the package link
*/
protected Content getNavLinkPackage() {
Content linkContent = getHyperLink("package-summary.html", "",
packageLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Get the use link.
*
* @return a content tree for the use link
*/
protected Content getNavLinkClassUse() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, useLabel);
return li;
}
/**
* Get the tree link.
*
* @return a content tree for the tree link
*/
protected Content getNavLinkTree() {
Content linkContent = getHyperLink("package-tree.html", "",
treeLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
}
| 12,334 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ConstructorWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstructorWriterImpl.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Writes constructor documentation.
*
* @author Robert Field
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class ConstructorWriterImpl extends AbstractExecutableMemberWriter
implements ConstructorWriter, MemberSummaryWriter {
private boolean foundNonPubConstructor = false;
/**
* Construct a new ConstructorWriterImpl.
*
* @param writer The writer for the class that the constructors belong to.
* @param classDoc the class being documented.
*/
public ConstructorWriterImpl(SubWriterHolderWriter writer,
ClassDoc classDoc) {
super(writer, classDoc);
VisibleMemberMap visibleMemberMap = new VisibleMemberMap(classDoc,
VisibleMemberMap.CONSTRUCTORS, configuration().nodeprecated);
List<ProgramElementDoc> constructors = new ArrayList<ProgramElementDoc>(visibleMemberMap.getMembersFor(classDoc));
for (int i = 0; i < constructors.size(); i++) {
if ((constructors.get(i)).isProtected() ||
(constructors.get(i)).isPrivate()) {
setFoundNonPubConstructor(true);
}
}
}
/**
* Construct a new ConstructorWriterImpl.
*
* @param writer The writer for the class that the constructors belong to.
*/
public ConstructorWriterImpl(SubWriterHolderWriter writer) {
super(writer);
}
/**
* {@inheritDoc}
*/
public Content getMemberSummaryHeader(ClassDoc classDoc,
Content memberSummaryTree) {
memberSummaryTree.addContent(HtmlConstants.START_OF_CONSTRUCTOR_SUMMARY);
Content memberTree = writer.getMemberTreeHeader();
writer.addSummaryHeader(this, classDoc, memberTree);
return memberTree;
}
/**
* {@inheritDoc}
*/
public Content getConstructorDetailsTreeHeader(ClassDoc classDoc,
Content memberDetailsTree) {
memberDetailsTree.addContent(HtmlConstants.START_OF_CONSTRUCTOR_DETAILS);
Content constructorDetailsTree = writer.getMemberTreeHeader();
constructorDetailsTree.addContent(writer.getMarkerAnchor("constructor_detail"));
Content heading = HtmlTree.HEADING(HtmlConstants.DETAILS_HEADING,
writer.constructorDetailsLabel);
constructorDetailsTree.addContent(heading);
return constructorDetailsTree;
}
/**
* {@inheritDoc}
*/
public Content getConstructorDocTreeHeader(ConstructorDoc constructor,
Content constructorDetailsTree) {
String erasureAnchor;
if ((erasureAnchor = getErasureAnchor(constructor)) != null) {
constructorDetailsTree.addContent(writer.getMarkerAnchor((erasureAnchor)));
}
constructorDetailsTree.addContent(
writer.getMarkerAnchor(writer.getAnchor(constructor)));
Content constructorDocTree = writer.getMemberTreeHeader();
Content heading = new HtmlTree(HtmlConstants.MEMBER_HEADING);
heading.addContent(constructor.name());
constructorDocTree.addContent(heading);
return constructorDocTree;
}
/**
* {@inheritDoc}
*/
public Content getSignature(ConstructorDoc constructor) {
writer.displayLength = 0;
Content pre = new HtmlTree(HtmlTag.PRE);
writer.addAnnotationInfo(constructor, pre);
addModifiers(constructor, pre);
if (configuration().linksource) {
Content constructorName = new StringContent(constructor.name());
writer.addSrcLink(constructor, constructorName, pre);
} else {
addName(constructor.name(), pre);
}
addParameters(constructor, pre);
addExceptions(constructor, pre);
return pre;
}
/**
* {@inheritDoc}
*/
@Override
public void setSummaryColumnStyle(HtmlTree tdTree) {
if (foundNonPubConstructor)
tdTree.addStyle(HtmlStyle.colLast);
else
tdTree.addStyle(HtmlStyle.colOne);
}
/**
* {@inheritDoc}
*/
public void addDeprecated(ConstructorDoc constructor, Content constructorDocTree) {
addDeprecatedInfo(constructor, constructorDocTree);
}
/**
* {@inheritDoc}
*/
public void addComments(ConstructorDoc constructor, Content constructorDocTree) {
addComment(constructor, constructorDocTree);
}
/**
* {@inheritDoc}
*/
public void addTags(ConstructorDoc constructor, Content constructorDocTree) {
writer.addTagsInfo(constructor, constructorDocTree);
}
/**
* {@inheritDoc}
*/
public Content getConstructorDetails(Content constructorDetailsTree) {
return getMemberTree(constructorDetailsTree);
}
/**
* {@inheritDoc}
*/
public Content getConstructorDoc(Content constructorDocTree,
boolean isLastContent) {
return getMemberTree(constructorDocTree, isLastContent);
}
/**
* Close the writer.
*/
public void close() throws IOException {
writer.close();
}
/**
* Let the writer know whether a non public constructor was found.
*
* @param foundNonPubConstructor true if we found a non public constructor.
*/
public void setFoundNonPubConstructor(boolean foundNonPubConstructor) {
this.foundNonPubConstructor = foundNonPubConstructor;
}
/**
* {@inheritDoc}
*/
public void addSummaryLabel(Content memberTree) {
Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
writer.getResource("doclet.Constructor_Summary"));
memberTree.addContent(label);
}
/**
* {@inheritDoc}
*/
public String getTableSummary() {
return configuration().getText("doclet.Member_Table_Summary",
configuration().getText("doclet.Constructor_Summary"),
configuration().getText("doclet.constructors"));
}
/**
* {@inheritDoc}
*/
public String getCaption() {
return configuration().getText("doclet.Constructors");
}
/**
* {@inheritDoc}
*/
public String[] getSummaryTableHeader(ProgramElementDoc member) {
String[] header;
if (foundNonPubConstructor) {
header = new String[] {
configuration().getText("doclet.Modifier"),
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Constructor"),
configuration().getText("doclet.Description"))
};
}
else {
header = new String[] {
configuration().getText("doclet.0_and_1",
configuration().getText("doclet.Constructor"),
configuration().getText("doclet.Description"))
};
}
return header;
}
/**
* {@inheritDoc}
*/
public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
memberTree.addContent(writer.getMarkerAnchor("constructor_summary"));
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
}
/**
* {@inheritDoc}
*/
public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
}
public int getMemberKind() {
return VisibleMemberMap.CONSTRUCTORS;
}
/**
* {@inheritDoc}
*/
protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
if (link) {
return writer.getHyperLink("", "constructor_summary",
writer.getResource("doclet.navConstructor"));
} else {
return writer.getResource("doclet.navConstructor");
}
}
/**
* {@inheritDoc}
*/
protected void addNavDetailLink(boolean link, Content liNav) {
if (link) {
liNav.addContent(writer.getHyperLink("", "constructor_detail",
writer.getResource("doclet.navConstructor")));
} else {
liNav.addContent(writer.getResource("doclet.navConstructor"));
}
}
/**
* {@inheritDoc}
*/
protected void addSummaryType(ProgramElementDoc member, Content tdSummaryType) {
if (foundNonPubConstructor) {
Content code = new HtmlTree(HtmlTag.CODE);
if (member.isProtected()) {
code.addContent("protected ");
} else if (member.isPrivate()) {
code.addContent("private ");
} else if (member.isPublic()) {
code.addContent(writer.getSpace());
} else {
code.addContent(
configuration().getText("doclet.Package_private"));
}
tdSummaryType.addContent(code);
}
}
}
| 10,350 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FrameOutputWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/FrameOutputWriter.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Generate the documentation in the Html "frame" format in the browser. The
* generated documentation will have two or three frames depending upon the
* number of packages on the command line. In general there will be three frames
* in the output, a left-hand top frame will have a list of all packages with
* links to target left-hand bottom frame. The left-hand bottom frame will have
* the particular package contents or the all-classes list, where as the single
* right-hand frame will have overview or package summary or class file. Also
* take care of browsers which do not support Html frames.
*
* @author Atul M Dambalkar
*/
public class FrameOutputWriter extends HtmlDocletWriter {
/**
* Number of packages specified on the command line.
*/
int noOfPackages;
private final String SCROLL_YES = "yes";
/**
* Constructor to construct FrameOutputWriter object.
*
* @param filename File to be generated.
*/
public FrameOutputWriter(ConfigurationImpl configuration,
String filename) throws IOException {
super(configuration, filename);
noOfPackages = configuration.packages.length;
}
/**
* Construct FrameOutputWriter object and then use it to generate the Html
* file which will have the description of all the frames in the
* documentation. The name of the generated file is "index.html" which is
* the default first file for Html documents.
* @throws DocletAbortException
*/
public static void generate(ConfigurationImpl configuration) {
FrameOutputWriter framegen;
String filename = "";
try {
filename = "index.html";
framegen = new FrameOutputWriter(configuration, filename);
framegen.generateFrameFile();
framegen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException();
}
}
/**
* Generate the contants in the "index.html" file. Print the frame details
* as well as warning if browser is not supporting the Html frames.
*/
protected void generateFrameFile() {
Content frameset = getFrameDetails();
if (configuration.windowtitle.length() > 0) {
printFramesetDocument(configuration.windowtitle, configuration.notimestamp,
frameset);
} else {
printFramesetDocument(configuration.getText("doclet.Generated_Docs_Untitled"),
configuration.notimestamp, frameset);
}
}
/**
* Add the code for issueing the warning for a non-frame capable web
* client. Also provide links to the non-frame version documentation.
*
* @param contentTree the content tree to which the non-frames information will be added
*/
protected void addFrameWarning(Content contentTree) {
Content noframes = new HtmlTree(HtmlTag.NOFRAMES);
Content noScript = HtmlTree.NOSCRIPT(
HtmlTree.DIV(getResource("doclet.No_Script_Message")));
noframes.addContent(noScript);
Content noframesHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING,
getResource("doclet.Frame_Alert"));
noframes.addContent(noframesHead);
Content p = HtmlTree.P(getResource("doclet.Frame_Warning_Message",
getHyperLinkString(configuration.topFile,
configuration.getText("doclet.Non_Frame_Version"))));
noframes.addContent(p);
contentTree.addContent(noframes);
}
/**
* Get the frame sizes and their contents.
*
* @return a content tree for the frame details
*/
protected Content getFrameDetails() {
HtmlTree frameset = HtmlTree.FRAMESET("20%,80%", null, "Documentation frame",
"top.loadFrames()");
if (noOfPackages <= 1) {
addAllClassesFrameTag(frameset);
} else if (noOfPackages > 1) {
HtmlTree leftFrameset = HtmlTree.FRAMESET(null, "30%,70%", "Left frames",
"top.loadFrames()");
addAllPackagesFrameTag(leftFrameset);
addAllClassesFrameTag(leftFrameset);
frameset.addContent(leftFrameset);
}
addClassFrameTag(frameset);
addFrameWarning(frameset);
return frameset;
}
/**
* Add the FRAME tag for the frame that lists all packages.
*
* @param contentTree the content tree to which the information will be added
*/
private void addAllPackagesFrameTag(Content contentTree) {
HtmlTree frame = HtmlTree.FRAME("overview-frame.html", "packageListFrame",
configuration.getText("doclet.All_Packages"));
contentTree.addContent(frame);
}
/**
* Add the FRAME tag for the frame that lists all classes.
*
* @param contentTree the content tree to which the information will be added
*/
private void addAllClassesFrameTag(Content contentTree) {
HtmlTree frame = HtmlTree.FRAME("allclasses-frame.html", "packageFrame",
configuration.getText("doclet.All_classes_and_interfaces"));
contentTree.addContent(frame);
}
/**
* Add the FRAME tag for the frame that describes the class in detail.
*
* @param contentTree the content tree to which the information will be added
*/
private void addClassFrameTag(Content contentTree) {
HtmlTree frame = HtmlTree.FRAME(configuration.topFile, "classFrame",
configuration.getText("doclet.Package_class_and_interface_descriptions"),
SCROLL_YES);
contentTree.addContent(frame);
}
}
| 7,273 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/PackageWriterImpl.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Class to generate file for each package contents in the right-hand
* frame. This will list all the Class Kinds in the package. A click on any
* class-kind will update the frame with the clicked class-kind page.
*
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class PackageWriterImpl extends HtmlDocletWriter
implements PackageSummaryWriter {
/**
* The prev package name in the alpha-order list.
*/
protected PackageDoc prev;
/**
* The next package name in the alpha-order list.
*/
protected PackageDoc next;
/**
* The package being documented.
*/
protected PackageDoc packageDoc;
/**
* The name of the output file.
*/
private static final String OUTPUT_FILE_NAME = "package-summary.html";
/**
* Constructor to construct PackageWriter object and to generate
* "package-summary.html" file in the respective package directory.
* For example for package "java.lang" this will generate file
* "package-summary.html" file in the "java/lang" directory. It will also
* create "java/lang" directory in the current or the destination directory
* if it doesen't exist.
*
* @param configuration the configuration of the doclet.
* @param packageDoc PackageDoc under consideration.
* @param prev Previous package in the sorted array.
* @param next Next package in the sorted array.
*/
public PackageWriterImpl(ConfigurationImpl configuration,
PackageDoc packageDoc, PackageDoc prev, PackageDoc next)
throws IOException {
super(configuration, DirectoryManager.getDirectoryPath(packageDoc), OUTPUT_FILE_NAME,
DirectoryManager.getRelativePath(packageDoc.name()));
this.prev = prev;
this.next = next;
this.packageDoc = packageDoc;
}
/**
* Return the name of the output file.
*
* @return the name of the output file.
*/
public String getOutputFileName() {
return OUTPUT_FILE_NAME;
}
/**
* {@inheritDoc}
*/
public Content getPackageHeader(String heading) {
String pkgName = packageDoc.name();
Content bodyTree = getBody(true, getWindowTitle(pkgName));
addTop(bodyTree);
addNavLinks(true, bodyTree);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
Content annotationContent = new HtmlTree(HtmlTag.P);
addAnnotationInfo(packageDoc, annotationContent);
div.addContent(annotationContent);
Content tHeading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, packageLabel);
tHeading.addContent(getSpace());
Content packageHead = new RawHtml(heading);
tHeading.addContent(packageHead);
div.addContent(tHeading);
addDeprecationInfo(div);
if (packageDoc.inlineTags().length > 0 && ! configuration.nocomment) {
HtmlTree docSummaryDiv = new HtmlTree(HtmlTag.DIV);
docSummaryDiv.addStyle(HtmlStyle.docSummary);
addSummaryComment(packageDoc, docSummaryDiv);
div.addContent(docSummaryDiv);
Content space = getSpace();
Content descLink = getHyperLink("", "package_description",
descriptionLabel, "", "");
Content descPara = new HtmlTree(HtmlTag.P, seeLabel, space, descLink);
div.addContent(descPara);
}
bodyTree.addContent(div);
return bodyTree;
}
/**
* {@inheritDoc}
*/
public Content getContentHeader() {
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.contentContainer);
return div;
}
/**
* Add the package deprecation information to the documentation tree.
*
* @param div the content tree to which the deprecation information will be added
*/
public void addDeprecationInfo(Content div) {
Tag[] deprs = packageDoc.tags("deprecated");
if (Util.isDeprecated(packageDoc)) {
HtmlTree deprDiv = new HtmlTree(HtmlTag.DIV);
deprDiv.addStyle(HtmlStyle.deprecatedContent);
Content deprPhrase = HtmlTree.SPAN(HtmlStyle.strong, deprecatedPhrase);
deprDiv.addContent(deprPhrase);
if (deprs.length > 0) {
Tag[] commentTags = deprs[0].inlineTags();
if (commentTags.length > 0) {
addInlineDeprecatedComment(packageDoc, deprs[0], deprDiv);
}
}
div.addContent(deprDiv);
}
}
/**
* {@inheritDoc}
*/
public Content getSummaryHeader() {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
return ul;
}
/**
* {@inheritDoc}
*/
public void addClassesSummary(ClassDoc[] classes, String label,
String tableSummary, String[] tableHeader, Content summaryContentTree) {
if(classes.length > 0) {
Arrays.sort(classes);
Content caption = getTableCaption(label);
Content table = HtmlTree.TABLE(HtmlStyle.packageSummary, 0, 3, 0,
tableSummary, caption);
table.addContent(getSummaryTableHeader(tableHeader, "col"));
Content tbody = new HtmlTree(HtmlTag.TBODY);
for (int i = 0; i < classes.length; i++) {
if (!Util.isCoreClass(classes[i]) ||
!configuration.isGeneratedDoc(classes[i])) {
continue;
}
Content classContent = new RawHtml(getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_PACKAGE, classes[i], false)));
Content tdClass = HtmlTree.TD(HtmlStyle.colFirst, classContent);
HtmlTree tr = HtmlTree.TR(tdClass);
if (i%2 == 0)
tr.addStyle(HtmlStyle.altColor);
else
tr.addStyle(HtmlStyle.rowColor);
HtmlTree tdClassDescription = new HtmlTree(HtmlTag.TD);
tdClassDescription.addStyle(HtmlStyle.colLast);
if (Util.isDeprecated(classes[i])) {
tdClassDescription.addContent(deprecatedLabel);
if (classes[i].tags("deprecated").length > 0) {
addSummaryDeprecatedComment(classes[i],
classes[i].tags("deprecated")[0], tdClassDescription);
}
}
else
addSummaryComment(classes[i], tdClassDescription);
tr.addContent(tdClassDescription);
tbody.addContent(tr);
}
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
summaryContentTree.addContent(li);
}
}
/**
* {@inheritDoc}
*/
public void addPackageDescription(Content packageContentTree) {
if (packageDoc.inlineTags().length > 0) {
packageContentTree.addContent(getMarkerAnchor("package_description"));
Content h2Content = new StringContent(
configuration.getText("doclet.Package_Description",
packageDoc.name()));
packageContentTree.addContent(HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING,
true, h2Content));
addInlineComment(packageDoc, packageContentTree);
}
}
/**
* {@inheritDoc}
*/
public void addPackageTags(Content packageContentTree) {
addTagsInfo(packageDoc, packageContentTree);
}
/**
* {@inheritDoc}
*/
public void addPackageFooter(Content contentTree) {
addNavLinks(false, contentTree);
addBottom(contentTree);
}
/**
* {@inheritDoc}
*/
public void printDocument(Content contentTree) {
printHtmlDocument(configuration.metakeywords.getMetaKeywords(packageDoc),
true, contentTree);
}
/**
* Get "Use" link for this pacakge in the navigation bar.
*
* @return a content tree for the class use link
*/
protected Content getNavLinkClassUse() {
Content useLink = getHyperLink("package-use.html", "",
useLabel, "", "");
Content li = HtmlTree.LI(useLink);
return li;
}
/**
* Get "PREV PACKAGE" link in the navigation bar.
*
* @return a content tree for the previous link
*/
public Content getNavLinkPrevious() {
Content li;
if (prev == null) {
li = HtmlTree.LI(prevpackageLabel);
} else {
String path = DirectoryManager.getRelativePath(packageDoc.name(),
prev.name());
li = HtmlTree.LI(getHyperLink(path + "package-summary.html", "",
prevpackageLabel, "", ""));
}
return li;
}
/**
* Get "NEXT PACKAGE" link in the navigation bar.
*
* @return a content tree for the next link
*/
public Content getNavLinkNext() {
Content li;
if (next == null) {
li = HtmlTree.LI(nextpackageLabel);
} else {
String path = DirectoryManager.getRelativePath(packageDoc.name(),
next.name());
li = HtmlTree.LI(getHyperLink(path + "package-summary.html", "",
nextpackageLabel, "", ""));
}
return li;
}
/**
* Get "Tree" link in the navigation bar. This will be link to the package
* tree file.
*
* @return a content tree for the tree link
*/
protected Content getNavLinkTree() {
Content useLink = getHyperLink("package-tree.html", "",
treeLabel, "", "");
Content li = HtmlTree.LI(useLink);
return li;
}
/**
* Highlight "Package" in the navigation bar, as this is the package page.
*
* @return a content tree for the package link
*/
protected Content getNavLinkPackage() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, packageLabel);
return li;
}
}
| 11,798 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/AnnotationTypeWriterImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.internal.toolkit.builders.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Generate the Class Information Page.
* @see com.sun.javadoc.ClassDoc
* @see java.util.Collections
* @see java.util.List
* @see java.util.ArrayList
* @see java.util.HashMap
*
* @author Atul M Dambalkar
* @author Robert Field
* @author Bhavesh Patel (Modified)
*/
public class AnnotationTypeWriterImpl extends SubWriterHolderWriter
implements AnnotationTypeWriter {
protected AnnotationTypeDoc annotationType;
protected Type prev;
protected Type next;
/**
* @param annotationType the annotation type being documented.
* @param prevType the previous class that was documented.
* @param nextType the next class being documented.
*/
public AnnotationTypeWriterImpl (AnnotationTypeDoc annotationType,
Type prevType, Type nextType)
throws Exception {
super(ConfigurationImpl.getInstance(),
DirectoryManager.getDirectoryPath(annotationType.containingPackage()),
annotationType.name() + ".html",
DirectoryManager.getRelativePath(annotationType.containingPackage().name()));
this.annotationType = annotationType;
configuration.currentcd = annotationType.asClassDoc();
this.prev = prevType;
this.next = nextType;
}
/**
* Get this package link.
*
* @return a content tree for the package link
*/
protected Content getNavLinkPackage() {
Content linkContent = getHyperLink("package-summary.html", "",
packageLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Get the class link.
*
* @return a content tree for the class link
*/
protected Content getNavLinkClass() {
Content li = HtmlTree.LI(HtmlStyle.navBarCell1Rev, classLabel);
return li;
}
/**
* Get the class use link.
*
* @return a content tree for the class use link
*/
protected Content getNavLinkClassUse() {
Content linkContent = getHyperLink("class-use/" + filename, "", useLabel);
Content li = HtmlTree.LI(linkContent);
return li;
}
/**
* Get link to previous class.
*
* @return a content tree for the previous class link
*/
public Content getNavLinkPrevious() {
Content li;
if (prev != null) {
Content prevLink = new RawHtml(getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS, prev.asClassDoc(), "",
configuration.getText("doclet.Prev_Class"), true)));
li = HtmlTree.LI(prevLink);
}
else
li = HtmlTree.LI(prevclassLabel);
return li;
}
/**
* Get link to next class.
*
* @return a content tree for the next class link
*/
public Content getNavLinkNext() {
Content li;
if (next != null) {
Content nextLink = new RawHtml(getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS, next.asClassDoc(), "",
configuration.getText("doclet.Next_Class"), true)));
li = HtmlTree.LI(nextLink);
}
else
li = HtmlTree.LI(nextclassLabel);
return li;
}
/**
* {@inheritDoc}
*/
public Content getHeader(String header) {
String pkgname = (annotationType.containingPackage() != null)?
annotationType.containingPackage().name(): "";
String clname = annotationType.name();
Content bodyTree = getBody(true, getWindowTitle(clname));
addTop(bodyTree);
addNavLinks(true, bodyTree);
bodyTree.addContent(HtmlConstants.START_OF_CLASS_DATA);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
if (pkgname.length() > 0) {
Content pkgNameContent = new StringContent(pkgname);
Content pkgNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, pkgNameContent);
div.addContent(pkgNameDiv);
}
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS_HEADER, annotationType, false);
Content headerContent = new StringContent(header);
Content heading = HtmlTree.HEADING(HtmlConstants.CLASS_PAGE_HEADING, true,
HtmlStyle.title, headerContent);
heading.addContent(new RawHtml(getTypeParameterLinks(linkInfo)));
div.addContent(heading);
bodyTree.addContent(div);
return bodyTree;
}
/**
* {@inheritDoc}
*/
public Content getAnnotationContentHeader() {
return getContentHeader();
}
/**
* {@inheritDoc}
*/
public void addFooter(Content contentTree) {
contentTree.addContent(HtmlConstants.END_OF_CLASS_DATA);
addNavLinks(false, contentTree);
addBottom(contentTree);
}
/**
* {@inheritDoc}
*/
public void printDocument(Content contentTree) {
printHtmlDocument(configuration.metakeywords.getMetaKeywords(annotationType),
true, contentTree);
}
/**
* {@inheritDoc}
*/
public Content getAnnotationInfoTreeHeader() {
return getMemberTreeHeader();
}
/**
* {@inheritDoc}
*/
public Content getAnnotationInfo(Content annotationInfoTree) {
return getMemberTree(HtmlStyle.description, annotationInfoTree);
}
/**
* {@inheritDoc}
*/
public void addAnnotationTypeSignature(String modifiers, Content annotationInfoTree) {
annotationInfoTree.addContent(new HtmlTree(HtmlTag.BR));
Content pre = new HtmlTree(HtmlTag.PRE);
addAnnotationInfo(annotationType, pre);
pre.addContent(modifiers);
LinkInfoImpl linkInfo = new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CLASS_SIGNATURE, annotationType, false);
Content annotationName = new StringContent(annotationType.name());
Content parameterLinks = new RawHtml(getTypeParameterLinks(linkInfo));
if (configuration().linksource) {
addSrcLink(annotationType, annotationName, pre);
pre.addContent(parameterLinks);
} else {
Content span = HtmlTree.SPAN(HtmlStyle.strong, annotationName);
span.addContent(parameterLinks);
pre.addContent(span);
}
annotationInfoTree.addContent(pre);
}
/**
* {@inheritDoc}
*/
public void addAnnotationTypeDescription(Content annotationInfoTree) {
if(!configuration.nocomment) {
if (annotationType.inlineTags().length > 0) {
addInlineComment(annotationType, annotationInfoTree);
}
}
}
/**
* {@inheritDoc}
*/
public void addAnnotationTypeTagInfo(Content annotationInfoTree) {
if(!configuration.nocomment) {
addTagsInfo(annotationType, annotationInfoTree);
}
}
/**
* {@inheritDoc}
*/
public void addAnnotationTypeDeprecationInfo(Content annotationInfoTree) {
Content hr = new HtmlTree(HtmlTag.HR);
annotationInfoTree.addContent(hr);
Tag[] deprs = annotationType.tags("deprecated");
if (Util.isDeprecated(annotationType)) {
Content strong = HtmlTree.STRONG(deprecatedPhrase);
Content div = HtmlTree.DIV(HtmlStyle.block, strong);
if (deprs.length > 0) {
Tag[] commentTags = deprs[0].inlineTags();
if (commentTags.length > 0) {
div.addContent(getSpace());
addInlineDeprecatedComment(annotationType, deprs[0], div);
}
}
annotationInfoTree.addContent(div);
}
}
/**
* {@inheritDoc}
*/
public void addAnnotationDetailsMarker(Content memberDetails) {
memberDetails.addContent(HtmlConstants.START_OF_ANNOTATION_TYPE_DETAILS);
}
/**
* {@inheritDoc}
*/
protected Content getNavLinkTree() {
Content treeLinkContent = getHyperLink("package-tree.html",
"", treeLabel, "", "");
Content li = HtmlTree.LI(treeLinkContent);
return li;
}
/**
* Add summary details to the navigation bar.
*
* @param subDiv the content tree to which the summary detail links will be added
*/
protected void addSummaryDetailLinks(Content subDiv) {
try {
Content div = HtmlTree.DIV(getNavSummaryLinks());
div.addContent(getNavDetailLinks());
subDiv.addContent(div);
} catch (Exception e) {
e.printStackTrace();
throw new DocletAbortException();
}
}
/**
* Get summary links for navigation bar.
*
* @return the content tree for the navigation summary links
*/
protected Content getNavSummaryLinks() throws Exception {
Content li = HtmlTree.LI(summaryLabel);
li.addContent(getSpace());
Content ulNav = HtmlTree.UL(HtmlStyle.subNavList, li);
MemberSummaryBuilder memberSummaryBuilder = (MemberSummaryBuilder)
configuration.getBuilderFactory().getMemberSummaryBuilder(this);
Content liNavReq = new HtmlTree(HtmlTag.LI);
addNavSummaryLink(memberSummaryBuilder,
"doclet.navAnnotationTypeRequiredMember",
VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED, liNavReq);
addNavGap(liNavReq);
ulNav.addContent(liNavReq);
Content liNavOpt = new HtmlTree(HtmlTag.LI);
addNavSummaryLink(memberSummaryBuilder,
"doclet.navAnnotationTypeOptionalMember",
VisibleMemberMap.ANNOTATION_TYPE_MEMBER_OPTIONAL, liNavOpt);
ulNav.addContent(liNavOpt);
return ulNav;
}
/**
* Add the navigation summary link.
*
* @param builder builder for the member to be documented
* @param label the label for the navigation
* @param type type to be documented
* @param liNav the content tree to which the navigation summary link will be added
*/
protected void addNavSummaryLink(MemberSummaryBuilder builder,
String label, int type, Content liNav) {
AbstractMemberWriter writer = ((AbstractMemberWriter) builder.
getMemberSummaryWriter(type));
if (writer == null) {
liNav.addContent(getResource(label));
} else {
liNav.addContent(writer.getNavSummaryLink(null,
! builder.getVisibleMemberMap(type).noVisibleMembers()));
}
}
/**
* Get detail links for the navigation bar.
*
* @return the content tree for the detail links
*/
protected Content getNavDetailLinks() throws Exception {
Content li = HtmlTree.LI(detailLabel);
li.addContent(getSpace());
Content ulNav = HtmlTree.UL(HtmlStyle.subNavList, li);
MemberSummaryBuilder memberSummaryBuilder = (MemberSummaryBuilder)
configuration.getBuilderFactory().getMemberSummaryBuilder(this);
AbstractMemberWriter writerOptional =
((AbstractMemberWriter) memberSummaryBuilder.
getMemberSummaryWriter(VisibleMemberMap.ANNOTATION_TYPE_MEMBER_OPTIONAL));
AbstractMemberWriter writerRequired =
((AbstractMemberWriter) memberSummaryBuilder.
getMemberSummaryWriter(VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED));
if (writerOptional != null){
Content liNavOpt = new HtmlTree(HtmlTag.LI);
writerOptional.addNavDetailLink(annotationType.elements().length > 0, liNavOpt);
ulNav.addContent(liNavOpt);
} else if (writerRequired != null){
Content liNavReq = new HtmlTree(HtmlTag.LI);
writerRequired.addNavDetailLink(annotationType.elements().length > 0, liNavReq);
ulNav.addContent(liNavReq);
} else {
Content liNav = HtmlTree.LI(getResource("doclet.navAnnotationTypeMember"));
ulNav.addContent(liNav);
}
return ulNav;
}
/**
* Add gap between navigation bar elements.
*
* @param liNav the content tree to which the gap will be added
*/
protected void addNavGap(Content liNav) {
liNav.addContent(getSpace());
liNav.addContent("|");
liNav.addContent(getSpace());
}
/**
* {@inheritDoc}
*/
public AnnotationTypeDoc getAnnotationTypeDoc() {
return annotationType;
}
}
| 14,042 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
LinkInfoImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/LinkInfoImpl.java | /*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.internal.toolkit.util.links.*;
public class LinkInfoImpl extends LinkInfo {
/**
* Indicate that the link appears in a class list.
*/
public static final int ALL_CLASSES_FRAME = 1;
/**
* Indicate that the link appears in a class documentation.
*/
public static final int CONTEXT_CLASS = 2;
/**
* Indicate that the link appears in member documentation.
*/
public static final int CONTEXT_MEMBER = 3;
/**
* Indicate that the link appears in class use documentation.
*/
public static final int CONTEXT_CLASS_USE = 4;
/**
* Indicate that the link appears in index documentation.
*/
public static final int CONTEXT_INDEX = 5;
/**
* Indicate that the link appears in constant value summary.
*/
public static final int CONTEXT_CONSTANT_SUMMARY = 6;
/**
* Indicate that the link appears in serialized form documentation.
*/
public static final int CONTEXT_SERIALIZED_FORM = 7;
/**
* Indicate that the link appears in serial member documentation.
*/
public static final int CONTEXT_SERIAL_MEMBER = 8;
/**
* Indicate that the link appears in package documentation.
*/
public static final int CONTEXT_PACKAGE = 9;
/**
* Indicate that the link appears in see tag documentation.
*/
public static final int CONTEXT_SEE_TAG = 10;
/**
* Indicate that the link appears in value tag documentation.
*/
public static final int CONTEXT_VALUE_TAG = 11;
/**
* Indicate that the link appears in tree documentation.
*/
public static final int CONTEXT_TREE = 12;
/**
* Indicate that the link appears in a class list.
*/
public static final int PACKAGE_FRAME = 13;
/**
* The header in the class documentation.
*/
public static final int CONTEXT_CLASS_HEADER = 14;
/**
* The signature in the class documentation.
*/
public static final int CONTEXT_CLASS_SIGNATURE = 15;
/**
* The return type of a method.
*/
public static final int CONTEXT_RETURN_TYPE = 16;
/**
* The return type of a method in a member summary.
*/
public static final int CONTEXT_SUMMARY_RETURN_TYPE = 17;
/**
* The type of a method/constructor parameter.
*/
public static final int CONTEXT_EXECUTABLE_MEMBER_PARAM = 18;
/**
* Super interface links.
*/
public static final int CONTEXT_SUPER_INTERFACES = 19;
/**
* Implemented interface links.
*/
public static final int CONTEXT_IMPLEMENTED_INTERFACES = 20;
/**
* Implemented class links.
*/
public static final int CONTEXT_IMPLEMENTED_CLASSES = 21;
/**
* Subinterface links.
*/
public static final int CONTEXT_SUBINTERFACES = 22;
/**
* Subclasses links.
*/
public static final int CONTEXT_SUBCLASSES = 23;
/**
* The signature in the class documentation (implements/extends portion).
*/
public static final int CONTEXT_CLASS_SIGNATURE_PARENT_NAME = 24;
/**
* The header for method documentation copied from parent.
*/
public static final int CONTEXT_METHOD_DOC_COPY = 26;
/**
* Method "specified by" link.
*/
public static final int CONTEXT_METHOD_SPECIFIED_BY = 27;
/**
* Method "overrides" link.
*/
public static final int CONTEXT_METHOD_OVERRIDES = 28;
/**
* Annotation link.
*/
public static final int CONTEXT_ANNOTATION = 29;
/**
* The header for field documentation copied from parent.
*/
public static final int CONTEXT_FIELD_DOC_COPY = 30;
/**
* The parent nodes int the class tree.
*/
public static final int CONTEXT_CLASS_TREE_PARENT = 31;
/**
* The type parameters of a method or constructor.
*/
public static final int CONTEXT_MEMBER_TYPE_PARAMS = 32;
/**
* Indicate that the link appears in class use documentation.
*/
public static final int CONTEXT_CLASS_USE_HEADER = 33;
/**
* The integer indicating the location of the link.
*/
public int context;
/**
* The value of the marker #.
*/
public String where = "";
/**
* String style of text defined in style sheet.
*/
public String styleName ="";
/**
* The valueof the target.
*/
public String target = "";
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param classDoc the class to link to.
* @param label the label for the link.
* @param target the value of the target attribute.
*/
public LinkInfoImpl (int context, ClassDoc classDoc, String label,
String target){
this.classDoc = classDoc;
this.label = label;
this.target = target;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param classDoc the class to link to.
* @param where the value of the marker #.
* @param label the label for the link.
* @param isStrong true if the link should be strong.
* @param styleName String style of text defined in style sheet.
*/
public LinkInfoImpl (int context, ClassDoc classDoc, String where, String label,
boolean isStrong, String styleName){
this.classDoc = classDoc;
this.where = where;
this.label = label;
this.isStrong = isStrong;
this.styleName = styleName;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param classDoc the class to link to.
* @param where the value of the marker #.
* @param label the label for the link.
* @param isStrong true if the link should be strong.
*/
public LinkInfoImpl (int context, ClassDoc classDoc, String where, String label,
boolean isStrong){
this.classDoc = classDoc;
this.where = where;
this.label = label;
this.isStrong = isStrong;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param classDoc the class to link to.
* @param label the label for the link.
*/
public LinkInfoImpl (ClassDoc classDoc, String label){
this.classDoc = classDoc;
this.label = label;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param executableMemberDoc the member to link to.
* @param isStrong true if the link should be strong.
*/
public LinkInfoImpl (int context, ExecutableMemberDoc executableMemberDoc,
boolean isStrong){
this.executableMemberDoc = executableMemberDoc;
this.isStrong = isStrong;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param classDoc the class to link to.
* @param isStrong true if the link should be strong.
*/
public LinkInfoImpl (int context, ClassDoc classDoc, boolean isStrong){
this.classDoc = classDoc;
this.isStrong = isStrong;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param type the class to link to.
*/
public LinkInfoImpl (int context, Type type){
this.type = type;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param type the class to link to.
* @param isVarArg true if this is a link to a var arg.
*/
public LinkInfoImpl (int context, Type type, boolean isVarArg){
this.type = type;
this.isVarArg = isVarArg;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param type the class to link to.
* @param label the label for the link.
* @param isStrong true if the link should be strong.
*/
public LinkInfoImpl (int context, Type type, String label,
boolean isStrong){
this.type = type;
this.label = label;
this.isStrong = isStrong;
setContext(context);
}
/**
* Construct a LinkInfo object.
*
* @param context the context of the link.
* @param classDoc the class to link to.
* @param label the label for the link.
* @param isStrong true if the link should be strong.
*/
public LinkInfoImpl (int context, ClassDoc classDoc, String label,
boolean isStrong){
this.classDoc = classDoc;
this.label = label;
this.isStrong = isStrong;
setContext(context);
}
/**
* {@inheritDoc}
*/
public int getContext() {
return context;
}
/**
* {@inheritDoc}
*
* This method sets the link attributes to the appropriate values
* based on the context.
*
* @param c the context id to set.
*/
public void setContext(int c) {
//NOTE: Put context specific link code here.
switch (c) {
case ALL_CLASSES_FRAME:
case PACKAGE_FRAME:
case CONTEXT_IMPLEMENTED_CLASSES:
case CONTEXT_SUBCLASSES:
case CONTEXT_METHOD_DOC_COPY:
case CONTEXT_FIELD_DOC_COPY:
case CONTEXT_CLASS_USE_HEADER:
includeTypeInClassLinkLabel = false;
break;
case CONTEXT_ANNOTATION:
excludeTypeParameterLinks = true;
excludeTypeBounds = true;
break;
case CONTEXT_IMPLEMENTED_INTERFACES:
case CONTEXT_SUPER_INTERFACES:
case CONTEXT_SUBINTERFACES:
case CONTEXT_CLASS_TREE_PARENT:
case CONTEXT_TREE:
case CONTEXT_CLASS_SIGNATURE_PARENT_NAME:
excludeTypeParameterLinks = true;
excludeTypeBounds = true;
includeTypeInClassLinkLabel = false;
includeTypeAsSepLink = true;
break;
case CONTEXT_PACKAGE:
case CONTEXT_CLASS_USE:
case CONTEXT_CLASS_HEADER:
case CONTEXT_CLASS_SIGNATURE:
excludeTypeParameterLinks = true;
includeTypeAsSepLink = true;
includeTypeInClassLinkLabel = false;
break;
case CONTEXT_MEMBER_TYPE_PARAMS:
includeTypeAsSepLink = true;
includeTypeInClassLinkLabel = false;
break;
case CONTEXT_RETURN_TYPE:
case CONTEXT_SUMMARY_RETURN_TYPE:
case CONTEXT_EXECUTABLE_MEMBER_PARAM:
excludeTypeBounds = true;
break;
}
context = c;
if (type != null &&
type.asTypeVariable()!= null &&
type.asTypeVariable().owner() instanceof ExecutableMemberDoc){
excludeTypeParameterLinks = true;
}
}
/**
* Return true if this link is linkable and false if we can't link to the
* desired place.
*
* @return true if this link is linkable and false if we can't link to the
* desired place.
*/
public boolean isLinkable() {
return Util.isLinkable(classDoc, ConfigurationImpl.getInstance());
}
}
| 13,113 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ConstantsSummaryWriterImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConstantsSummaryWriterImpl.java | /*
* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import com.sun.tools.doclets.formats.html.markup.*;
/**
* Write the Constants Summary Page in HTML format.
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
* @since 1.4
*/
public class ConstantsSummaryWriterImpl extends HtmlDocletWriter
implements ConstantsSummaryWriter {
/**
* The configuration used in this run of the standard doclet.
*/
ConfigurationImpl configuration;
/**
* The current class being documented.
*/
private ClassDoc currentClassDoc;
private final String constantsTableSummary;
private final String[] constantsTableHeader;
/**
* Construct a ConstantsSummaryWriter.
* @param configuration the configuration used in this run
* of the standard doclet.
*/
public ConstantsSummaryWriterImpl(ConfigurationImpl configuration)
throws IOException {
super(configuration, ConfigurationImpl.CONSTANTS_FILE_NAME);
this.configuration = configuration;
constantsTableSummary = configuration.getText("doclet.Constants_Table_Summary",
configuration.getText("doclet.Constants_Summary"));
constantsTableHeader = new String[] {
getModifierTypeHeader(),
configuration.getText("doclet.ConstantField"),
configuration.getText("doclet.Value")
};
}
/**
* {@inheritDoc}
*/
public Content getHeader() {
String label = configuration.getText("doclet.Constants_Summary");
Content bodyTree = getBody(true, getWindowTitle(label));
addTop(bodyTree);
addNavLinks(true, bodyTree);
return bodyTree;
}
/**
* {@inheritDoc}
*/
public Content getContentsHeader() {
return new HtmlTree(HtmlTag.UL);
}
/**
* {@inheritDoc}
*/
public void addLinkToPackageContent(PackageDoc pkg, String parsedPackageName,
Set<String> printedPackageHeaders, Content contentListTree) {
String packageName = pkg.name();
//add link to summary
Content link;
if (packageName.length() == 0) {
link = getHyperLink("#" + DocletConstants.UNNAMED_PACKAGE_ANCHOR,
"", defaultPackageLabel, "", "");
} else {
Content packageNameContent = getPackageLabel(parsedPackageName);
packageNameContent.addContent(".*");
link = getHyperLink("#" + parsedPackageName,
"", packageNameContent, "", "");
printedPackageHeaders.add(parsedPackageName);
}
contentListTree.addContent(HtmlTree.LI(link));
}
/**
* {@inheritDoc}
*/
public Content getContentsList(Content contentListTree) {
Content titleContent = getResource(
"doclet.Constants_Summary");
Content pHeading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, titleContent);
Content div = HtmlTree.DIV(HtmlStyle.header, pHeading);
Content headingContent = getResource(
"doclet.Contents");
div.addContent(HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, true,
headingContent));
div.addContent(contentListTree);
return div;
}
/**
* {@inheritDoc}
*/
public Content getConstantSummaries() {
HtmlTree summariesDiv = new HtmlTree(HtmlTag.DIV);
summariesDiv.addStyle(HtmlStyle.constantValuesContainer);
return summariesDiv;
}
/**
* {@inheritDoc}
*/
public void addPackageName(PackageDoc pkg, String parsedPackageName,
Content summariesTree) {
Content pkgNameContent;
if (parsedPackageName.length() == 0) {
summariesTree.addContent(getMarkerAnchor(
DocletConstants.UNNAMED_PACKAGE_ANCHOR));
pkgNameContent = defaultPackageLabel;
} else {
summariesTree.addContent(getMarkerAnchor(
parsedPackageName));
pkgNameContent = getPackageLabel(parsedPackageName);
}
Content headingContent = new StringContent(".*");
Content heading = HtmlTree.HEADING(HtmlConstants.PACKAGE_HEADING, true,
pkgNameContent);
heading.addContent(headingContent);
summariesTree.addContent(heading);
}
/**
* {@inheritDoc}
*/
public Content getClassConstantHeader() {
HtmlTree ul = new HtmlTree(HtmlTag.UL);
ul.addStyle(HtmlStyle.blockList);
return ul;
}
/**
* Get the table caption and header for the constant summary table
*
* @param cd classdoc to be documented
* @return constant members header content
*/
public Content getConstantMembersHeader(ClassDoc cd) {
//generate links backward only to public classes.
String classlink = (cd.isPublic() || cd.isProtected())?
getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_CONSTANT_SUMMARY, cd,
false)) :
cd.qualifiedName();
String name = cd.containingPackage().name();
if (name.length() > 0) {
return getClassName(name + "." + classlink);
} else {
return getClassName(classlink);
}
}
/**
* Get the class name in the table caption and the table header.
*
* @param classStr the class name to print.
* @return the table caption and header
*/
protected Content getClassName(String classStr) {
Content table = HtmlTree.TABLE(0, 3, 0, constantsTableSummary,
getTableCaption(classStr));
table.addContent(getSummaryTableHeader(constantsTableHeader, "col"));
return table;
}
/**
* {@inheritDoc}
*/
public void addConstantMembers(ClassDoc cd, List<FieldDoc> fields,
Content classConstantTree) {
currentClassDoc = cd;
Content tbody = new HtmlTree(HtmlTag.TBODY);
for (int i = 0; i < fields.size(); ++i) {
HtmlTree tr = new HtmlTree(HtmlTag.TR);
if (i%2 == 0)
tr.addStyle(HtmlStyle.altColor);
else
tr.addStyle(HtmlStyle.rowColor);
addConstantMember(fields.get(i), tr);
tbody.addContent(tr);
}
Content table = getConstantMembersHeader(cd);
table.addContent(tbody);
Content li = HtmlTree.LI(HtmlStyle.blockList, table);
classConstantTree.addContent(li);
}
/**
* Add the row for the constant summary table.
*
* @param member the field to be documented.
* @param trTree an htmltree object for the table row
*/
private void addConstantMember(FieldDoc member, HtmlTree trTree) {
trTree.addContent(getTypeColumn(member));
trTree.addContent(getNameColumn(member));
trTree.addContent(getValue(member));
}
/**
* Get the type column for the constant summary table row.
*
* @param member the field to be documented.
* @return the type column of the constant table row
*/
private Content getTypeColumn(FieldDoc member) {
Content anchor = getMarkerAnchor(currentClassDoc.qualifiedName() +
"." + member.name());
Content tdType = HtmlTree.TD(HtmlStyle.colFirst, anchor);
Content code = new HtmlTree(HtmlTag.CODE);
StringTokenizer mods = new StringTokenizer(member.modifiers());
while(mods.hasMoreTokens()) {
Content modifier = new StringContent(mods.nextToken());
code.addContent(modifier);
code.addContent(getSpace());
}
Content type = new RawHtml(getLink(new LinkInfoImpl(
LinkInfoImpl.CONTEXT_CONSTANT_SUMMARY, member.type())));
code.addContent(type);
tdType.addContent(code);
return tdType;
}
/**
* Get the name column for the constant summary table row.
*
* @param member the field to be documented.
* @return the name column of the constant table row
*/
private Content getNameColumn(FieldDoc member) {
Content nameContent = new RawHtml(getDocLink(
LinkInfoImpl.CONTEXT_CONSTANT_SUMMARY, member, member.name(), false));
Content code = HtmlTree.CODE(nameContent);
return HtmlTree.TD(code);
}
/**
* Get the value column for the constant summary table row.
*
* @param member the field to be documented.
* @return the value column of the constant table row
*/
private Content getValue(FieldDoc member) {
Content valueContent = new StringContent(member.constantValueExpression());
Content code = HtmlTree.CODE(valueContent);
return HtmlTree.TD(HtmlStyle.colLast, code);
}
/**
* {@inheritDoc}
*/
public void addFooter(Content contentTree) {
addNavLinks(false, contentTree);
addBottom(contentTree);
}
/**
* {@inheritDoc}
*/
public void printDocument(Content contentTree) {
printHtmlDocument(null, true, contentTree);
}
}
| 10,537 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlTree.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTree.java | /*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import java.util.*;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating HTML tree for javadoc output.
*
* @author Bhavesh Patel
*/
public class HtmlTree extends Content {
private HtmlTag htmlTag;
private Map<HtmlAttr,String> attrs = Collections.<HtmlAttr,String>emptyMap();
private List<Content> content = Collections.<Content>emptyList();
public static final Content EMPTY = new StringContent("");
/**
* Constructor to construct HtmlTree object.
*
* @param tag HTML tag for the HtmlTree object
*/
public HtmlTree(HtmlTag tag) {
htmlTag = nullCheck(tag);
}
/**
* Constructor to construct HtmlTree object.
*
* @param tag HTML tag for the HtmlTree object
* @param contents contents to be added to the tree
*/
public HtmlTree(HtmlTag tag, Content... contents) {
this(tag);
for (Content content: contents)
addContent(content);
}
/**
* Adds an attribute for the HTML tag.
*
* @param attrName name of the attribute
* @param attrValue value of the attribute
*/
public void addAttr(HtmlAttr attrName, String attrValue) {
if (attrs.isEmpty())
attrs = new LinkedHashMap<HtmlAttr,String>();
attrs.put(nullCheck(attrName), nullCheck(attrValue));
}
/**
* Adds a style for the HTML tag.
*
* @param style style to be added
*/
public void addStyle(HtmlStyle style) {
addAttr(HtmlAttr.CLASS, style.toString());
}
/**
* Adds content for the HTML tag.
*
* @param tagContent tag content to be added
*/
public void addContent(Content tagContent) {
if (tagContent == HtmlTree.EMPTY || tagContent.isValid()) {
if (content.isEmpty())
content = new ArrayList<Content>();
content.add(tagContent);
}
}
/**
* This method adds a string content to the htmltree. If the last content member
* added is a StringContent, append the string to that StringContent or else
* create a new StringContent and add it to the html tree.
*
* @param stringContent string content that needs to be added
*/
public void addContent(String stringContent) {
if (!content.isEmpty()) {
Content lastContent = content.get(content.size() - 1);
if (lastContent instanceof StringContent)
lastContent.addContent(stringContent);
else
addContent(new StringContent(stringContent));
}
else
addContent(new StringContent(stringContent));
}
/**
* Generates an HTML anchor tag.
*
* @param ref reference url for the anchor tag
* @param body content for the anchor tag
* @return an HtmlTree object
*/
public static HtmlTree A(String ref, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.A, nullCheck(body));
htmltree.addAttr(HtmlAttr.HREF, nullCheck(ref));
return htmltree;
}
/**
* Generates an HTML anchor tag with name attribute and content.
*
* @param name name for the anchor tag
* @param body content for the anchor tag
* @return an HtmlTree object
*/
public static HtmlTree A_NAME(String name, Content body) {
HtmlTree htmltree = HtmlTree.A_NAME(name);
htmltree.addContent(nullCheck(body));
return htmltree;
}
/**
* Generates an HTML anchor tag with name attribute.
*
* @param name name for the anchor tag
* @return an HtmlTree object
*/
public static HtmlTree A_NAME(String name) {
HtmlTree htmltree = new HtmlTree(HtmlTag.A);
htmltree.addAttr(HtmlAttr.NAME, nullCheck(name));
return htmltree;
}
/**
* Generates a CAPTION tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the CAPTION tag
*/
public static HtmlTree CAPTION(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.CAPTION, nullCheck(body));
return htmltree;
}
/**
* Generates a CODE tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the CODE tag
*/
public static HtmlTree CODE(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.CODE, nullCheck(body));
return htmltree;
}
/**
* Generates a DD tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the DD tag
*/
public static HtmlTree DD(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.DD, nullCheck(body));
return htmltree;
}
/**
* Generates a DL tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the DL tag
*/
public static HtmlTree DL(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.DL, nullCheck(body));
return htmltree;
}
/**
* Generates a DIV tag with the style class attributes. It also encloses
* a content.
*
* @param styleClass stylesheet class for the tag
* @param body content for the tag
* @return an HtmlTree object for the DIV tag
*/
public static HtmlTree DIV(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.DIV, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a DIV tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the DIV tag
*/
public static HtmlTree DIV(Content body) {
return DIV(null, body);
}
/**
* Generates a DT tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the DT tag
*/
public static HtmlTree DT(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.DT, nullCheck(body));
return htmltree;
}
/**
* Generates a EM tag with some content.
*
* @param body content to be added to the tag
* @return an HtmlTree object for the EM tag
*/
public static HtmlTree EM(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.EM, nullCheck(body));
return htmltree;
}
/**
* Generates a FRAME tag.
*
* @param src the url of the document to be shown in the frame
* @param name specifies the name of the frame
* @param title the title for the frame
* @param scrolling specifies whether to display scrollbars in the frame
* @return an HtmlTree object for the FRAME tag
*/
public static HtmlTree FRAME(String src, String name, String title, String scrolling) {
HtmlTree htmltree = new HtmlTree(HtmlTag.FRAME);
htmltree.addAttr(HtmlAttr.SRC, nullCheck(src));
htmltree.addAttr(HtmlAttr.NAME, nullCheck(name));
htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title));
if (scrolling != null)
htmltree.addAttr(HtmlAttr.SCROLLING, scrolling);
return htmltree;
}
/**
* Generates a Frame tag.
*
* @param src the url of the document to be shown in the frame
* @param name specifies the name of the frame
* @param title the title for the frame
* @return an HtmlTree object for the SPAN tag
*/
public static HtmlTree FRAME(String src, String name, String title) {
return FRAME(src, name, title, null);
}
/**
* Generates a FRAMESET tag.
*
* @param cols the size of columns in the frameset
* @param rows the size of rows in the frameset
* @param title the title for the frameset
* @param onload the script to run when the document loads
* @return an HtmlTree object for the FRAMESET tag
*/
public static HtmlTree FRAMESET(String cols, String rows, String title, String onload) {
HtmlTree htmltree = new HtmlTree(HtmlTag.FRAMESET);
if (cols != null)
htmltree.addAttr(HtmlAttr.COLS, cols);
if (rows != null)
htmltree.addAttr(HtmlAttr.ROWS, rows);
htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title));
htmltree.addAttr(HtmlAttr.ONLOAD, nullCheck(onload));
return htmltree;
}
/**
* Generates a heading tag (h1 to h6) with the title and style class attributes. It also encloses
* a content.
*
* @param headingTag the heading tag to be generated
* @param printTitle true if title for the tag needs to be printed else false
* @param styleClass stylesheet class for the tag
* @param body content for the tag
* @return an HtmlTree object for the tag
*/
public static HtmlTree HEADING(HtmlTag headingTag, boolean printTitle,
HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(headingTag, nullCheck(body));
if (printTitle)
htmltree.addAttr(HtmlAttr.TITLE, Util.stripHtml(body.toString()));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a heading tag (h1 to h6) with style class attribute. It also encloses
* a content.
*
* @param headingTag the heading tag to be generated
* @param styleClass stylesheet class for the tag
* @param body content for the tag
* @return an HtmlTree object for the tag
*/
public static HtmlTree HEADING(HtmlTag headingTag, HtmlStyle styleClass, Content body) {
return HEADING(headingTag, false, styleClass, body);
}
/**
* Generates a heading tag (h1 to h6) with the title attribute. It also encloses
* a content.
*
* @param headingTag the heading tag to be generated
* @param printTitle true if the title for the tag needs to be printed else false
* @param body content for the tag
* @return an HtmlTree object for the tag
*/
public static HtmlTree HEADING(HtmlTag headingTag, boolean printTitle, Content body) {
return HEADING(headingTag, printTitle, null, body);
}
/**
* Generates a heading tag (h1 to h6) with some content.
*
* @param headingTag the heading tag to be generated
* @param body content for the tag
* @return an HtmlTree object for the tag
*/
public static HtmlTree HEADING(HtmlTag headingTag, Content body) {
return HEADING(headingTag, false, null, body);
}
/**
* Generates an HTML tag with lang attribute. It also adds head and body
* content to the HTML tree.
*
* @param lang language for the HTML document
* @param head head for the HTML tag
* @param body body for the HTML tag
* @return an HtmlTree object for the HTML tag
*/
public static HtmlTree HTML(String lang, Content head, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body));
htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang));
return htmltree;
}
/**
* Generates a I tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the I tag
*/
public static HtmlTree I(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.I, nullCheck(body));
return htmltree;
}
/**
* Generates a LI tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the LI tag
*/
public static HtmlTree LI(Content body) {
return LI(null, body);
}
/**
* Generates a LI tag with some content.
*
* @param styleClass style for the tag
* @param body content for the tag
* @return an HtmlTree object for the LI tag
*/
public static HtmlTree LI(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.LI, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a LINK tag with the rel, type, href and title attributes.
*
* @param rel relevance of the link
* @param type type of link
* @param href the path for the link
* @param title title for the link
* @return an HtmlTree object for the LINK tag
*/
public static HtmlTree LINK(String rel, String type, String href, String title) {
HtmlTree htmltree = new HtmlTree(HtmlTag.LINK);
htmltree.addAttr(HtmlAttr.REL, nullCheck(rel));
htmltree.addAttr(HtmlAttr.TYPE, nullCheck(type));
htmltree.addAttr(HtmlAttr.HREF, nullCheck(href));
htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title));
return htmltree;
}
/**
* Generates a META tag with the http-equiv, content and charset attributes.
*
* @param http-equiv http equiv attribute for the META tag
* @param content type of content
* @param charset character set used
* @return an HtmlTree object for the META tag
*/
public static HtmlTree META(String httpEquiv, String content, String charSet) {
HtmlTree htmltree = new HtmlTree(HtmlTag.META);
htmltree.addAttr(HtmlAttr.HTTP_EQUIV, nullCheck(httpEquiv));
htmltree.addAttr(HtmlAttr.CONTENT, nullCheck(content));
htmltree.addAttr(HtmlAttr.CHARSET, nullCheck(charSet));
return htmltree;
}
/**
* Generates a META tag with the name and content attributes.
*
* @param name name attribute
* @param content type of content
* @return an HtmlTree object for the META tag
*/
public static HtmlTree META(String name, String content) {
HtmlTree htmltree = new HtmlTree(HtmlTag.META);
htmltree.addAttr(HtmlAttr.NAME, nullCheck(name));
htmltree.addAttr(HtmlAttr.CONTENT, nullCheck(content));
return htmltree;
}
/**
* Generates a NOSCRIPT tag with some content.
*
* @param body content of the noscript tag
* @return an HtmlTree object for the NOSCRIPT tag
*/
public static HtmlTree NOSCRIPT(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.NOSCRIPT, nullCheck(body));
return htmltree;
}
/**
* Generates a P tag with some content.
*
* @param body content of the Paragraph tag
* @return an HtmlTree object for the P tag
*/
public static HtmlTree P(Content body) {
return P(null, body);
}
/**
* Generates a P tag with some content.
*
* @param styleClass style of the Paragraph tag
* @param body content of the Paragraph tag
* @return an HtmlTree object for the P tag
*/
public static HtmlTree P(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.P, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a SMALL tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the SMALL tag
*/
public static HtmlTree SMALL(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.SMALL, nullCheck(body));
return htmltree;
}
/**
* Generates a STRONG tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the STRONG tag
*/
public static HtmlTree STRONG(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.STRONG, nullCheck(body));
return htmltree;
}
/**
* Generates a SPAN tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the SPAN tag
*/
public static HtmlTree SPAN(Content body) {
return SPAN(null, body);
}
/**
* Generates a SPAN tag with style class attribute and some content.
*
* @param styleClass style class for the tag
* @param body content for the tag
* @return an HtmlTree object for the SPAN tag
*/
public static HtmlTree SPAN(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.SPAN, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a Table tag with border, width and summary attributes and
* some content.
*
* @param border border for the table
* @param width width of the table
* @param summary summary for the table
* @param body content for the table
* @return an HtmlTree object for the TABLE tag
*/
public static HtmlTree TABLE(int border, int width, String summary,
Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TABLE, nullCheck(body));
htmltree.addAttr(HtmlAttr.BORDER, Integer.toString(border));
htmltree.addAttr(HtmlAttr.WIDTH, Integer.toString(width));
htmltree.addAttr(HtmlAttr.SUMMARY, nullCheck(summary));
return htmltree;
}
/**
* Generates a Table tag with style class, border, cell padding,
* cellspacing and summary attributes and some content.
*
* @param styleClass style of the table
* @param border border for the table
* @param cellPadding cell padding for the table
* @param cellSpacing cell spacing for the table
* @param summary summary for the table
* @param body content for the table
* @return an HtmlTree object for the TABLE tag
*/
public static HtmlTree TABLE(HtmlStyle styleClass, int border, int cellPadding,
int cellSpacing, String summary, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TABLE, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
htmltree.addAttr(HtmlAttr.BORDER, Integer.toString(border));
htmltree.addAttr(HtmlAttr.CELLPADDING, Integer.toString(cellPadding));
htmltree.addAttr(HtmlAttr.CELLSPACING, Integer.toString(cellSpacing));
htmltree.addAttr(HtmlAttr.SUMMARY, nullCheck(summary));
return htmltree;
}
/**
* Generates a Table tag with border, cell padding,
* cellspacing and summary attributes and some content.
*
* @param border border for the table
* @param cellPadding cell padding for the table
* @param cellSpacing cell spacing for the table
* @param summary summary for the table
* @param body content for the table
* @return an HtmlTree object for the TABLE tag
*/
public static HtmlTree TABLE(int border, int cellPadding,
int cellSpacing, String summary, Content body) {
return TABLE(null, border, cellPadding, cellSpacing, summary, body);
}
/**
* Generates a TD tag with style class attribute and some content.
*
* @param styleClass style for the tag
* @param body content for the tag
* @return an HtmlTree object for the TD tag
*/
public static HtmlTree TD(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TD, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
return htmltree;
}
/**
* Generates a TD tag for an HTML table with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the TD tag
*/
public static HtmlTree TD(Content body) {
return TD(null, body);
}
/**
* Generates a TH tag with style class and scope attributes and some content.
*
* @param styleClass style for the tag
* @param scope scope of the tag
* @param body content for the tag
* @return an HtmlTree object for the TH tag
*/
public static HtmlTree TH(HtmlStyle styleClass, String scope, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TH, nullCheck(body));
if (styleClass != null)
htmltree.addStyle(styleClass);
htmltree.addAttr(HtmlAttr.SCOPE, nullCheck(scope));
return htmltree;
}
/**
* Generates a TH tag with scope attribute and some content.
*
* @param scope scope of the tag
* @param body content for the tag
* @return an HtmlTree object for the TH tag
*/
public static HtmlTree TH(String scope, Content body) {
return TH(null, scope, body);
}
/**
* Generates a TITLE tag with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the TITLE tag
*/
public static HtmlTree TITLE(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TITLE, nullCheck(body));
return htmltree;
}
/**
* Generates a TR tag for an HTML table with some content.
*
* @param body content for the tag
* @return an HtmlTree object for the TR tag
*/
public static HtmlTree TR(Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.TR, nullCheck(body));
return htmltree;
}
/**
* Generates a UL tag with the style class attribute and some content.
*
* @param styleClass style for the tag
* @param body content for the tag
* @return an HtmlTree object for the UL tag
*/
public static HtmlTree UL(HtmlStyle styleClass, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.UL, nullCheck(body));
htmltree.addStyle(nullCheck(styleClass));
return htmltree;
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return (!hasContent() && !hasAttrs());
}
/**
* Returns true if the HTML tree has content.
*
* @return true if the HTML tree has content else return false
*/
public boolean hasContent() {
return (!content.isEmpty());
}
/**
* Returns true if the HTML tree has attributes.
*
* @return true if the HTML tree has attributes else return false
*/
public boolean hasAttrs() {
return (!attrs.isEmpty());
}
/**
* Returns true if the HTML tree has a specific attribute.
*
* @param attrName name of the attribute to check within the HTML tree
* @return true if the HTML tree has the specified attribute else return false
*/
public boolean hasAttr(HtmlAttr attrName) {
return (attrs.containsKey(attrName));
}
/**
* Returns true if the HTML tree is valid. This check is more specific to
* standard doclet and not exactly similar to W3C specifications. But it
* ensures HTML validation.
*
* @return true if the HTML tree is valid
*/
public boolean isValid() {
switch (htmlTag) {
case A :
return (hasAttr(HtmlAttr.NAME) || (hasAttr(HtmlAttr.HREF) && hasContent()));
case BR :
return (!hasContent() && (!hasAttrs() || hasAttr(HtmlAttr.CLEAR)));
case FRAME :
return (hasAttr(HtmlAttr.SRC) && !hasContent());
case HR :
return (!hasContent());
case IMG :
return (hasAttr(HtmlAttr.SRC) && hasAttr(HtmlAttr.ALT) && !hasContent());
case LINK :
return (hasAttr(HtmlAttr.HREF) && !hasContent());
case META :
return (hasAttr(HtmlAttr.CONTENT) && !hasContent());
default :
return hasContent();
}
}
/**
* Returns true if the element is an inline element.
*
* @return true if the HTML tag is an inline element
*/
public boolean isInline() {
return (htmlTag.blockType == HtmlTag.BlockType.INLINE);
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
if (!isInline() && !endsWithNewLine(contentBuilder))
contentBuilder.append(DocletConstants.NL);
String tagString = htmlTag.toString();
contentBuilder.append("<");
contentBuilder.append(tagString);
Iterator<HtmlAttr> iterator = attrs.keySet().iterator();
HtmlAttr key;
String value = "";
while (iterator.hasNext()) {
key = iterator.next();
value = attrs.get(key);
contentBuilder.append(" ");
contentBuilder.append(key.toString());
if (!value.isEmpty()) {
contentBuilder.append("=\"");
contentBuilder.append(value);
contentBuilder.append("\"");
}
}
contentBuilder.append(">");
for (Content c : content)
c.write(contentBuilder);
if (htmlTag.endTagRequired()) {
contentBuilder.append("</");
contentBuilder.append(tagString);
contentBuilder.append(">");
}
if (!isInline())
contentBuilder.append(DocletConstants.NL);
}
}
| 26,385 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlDocWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlDocWriter.java | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import java.io.*;
import java.util.*;
import com.sun.javadoc.*;
import com.sun.tools.doclets.internal.toolkit.*;
/**
* Class for the Html Format Code Generation specific to JavaDoc.
* This Class contains methods related to the Html Code Generation which
* are used by the Sub-Classes in the package com.sun.tools.doclets.standard
* and com.sun.tools.doclets.oneone.
*
* @since 1.2
* @author Atul M Dambalkar
* @author Robert Field
*/
public abstract class HtmlDocWriter extends HtmlWriter {
/**
* Constructor. Initializes the destination file name through the super
* class HtmlWriter.
*
* @param filename String file name.
*/
public HtmlDocWriter(Configuration configuration,
String filename) throws IOException {
super(configuration,
null, configuration.destDirName + filename,
configuration.docencoding);
// use File to normalize file separators
configuration.message.notice("doclet.Generating_0",
new File(configuration.destDirName, filename));
}
public HtmlDocWriter(Configuration configuration,
String path, String filename) throws IOException {
super(configuration,
configuration.destDirName + path, filename,
configuration.docencoding);
// use File to normalize file separators
configuration.message.notice("doclet.Generating_0",
new File(configuration.destDirName,
((path.length() > 0)? path + File.separator: "") + filename));
}
/**
* Accessor for configuration.
*/
public abstract Configuration configuration();
/**
* Print Html Hyper Link.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param strong Boolean that sets label to strong.
*/
public void printHyperLink(String link, String where,
String label, boolean strong) {
print(getHyperLinkString(link, where, label, strong, "", "", ""));
}
/**
* Print Html Hyper Link.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
*/
public void printHyperLink(String link, String where, String label) {
printHyperLink(link, where, label, false);
}
/**
* Print Html Hyper Link.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param strong Boolean that sets label to strong.
* @param stylename String style of text defined in style sheet.
*/
public void printHyperLink(String link, String where,
String label, boolean strong,
String stylename) {
print(getHyperLinkString(link, where, label, strong, stylename, "", ""));
}
/**
* Return Html Hyper Link string.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param strong Boolean that sets label to strong.
* @return String Hyper Link.
*/
public String getHyperLinkString(String link, String where,
String label, boolean strong) {
return getHyperLinkString(link, where, label, strong, "", "", "");
}
/**
* Get Html Hyper Link string.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param strong Boolean that sets label to strong.
* @param stylename String style of text defined in style sheet.
* @return String Hyper Link.
*/
public String getHyperLinkString(String link, String where,
String label, boolean strong,
String stylename) {
return getHyperLinkString(link, where, label, strong, stylename, "", "");
}
/**
* Get Html Hyper Link string.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @return a content tree for the hyper link
*/
public Content getHyperLink(String link, String where,
Content label) {
return getHyperLink(link, where, label, "", "");
}
/**
* Get Html Hyper Link string.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param strong Boolean that sets label to strong.
* @param stylename String style of text defined in style sheet.
* @param title String that describes the link's content for accessibility.
* @param target Target frame.
* @return String Hyper Link.
*/
public String getHyperLinkString(String link, String where,
String label, boolean strong,
String stylename, String title, String target) {
StringBuffer retlink = new StringBuffer();
retlink.append("<a href=\"");
retlink.append(link);
if (where != null && where.length() != 0) {
retlink.append("#");
retlink.append(where);
}
retlink.append("\"");
if (title != null && title.length() != 0) {
retlink.append(" title=\"" + title + "\"");
}
if (target != null && target.length() != 0) {
retlink.append(" target=\"" + target + "\"");
}
retlink.append(">");
if (stylename != null && stylename.length() != 0) {
retlink.append("<FONT CLASS=\"");
retlink.append(stylename);
retlink.append("\">");
}
if (strong) {
retlink.append("<span class=\"strong\">");
}
retlink.append(label);
if (strong) {
retlink.append("</span>");
}
if (stylename != null && stylename.length() != 0) {
retlink.append("</FONT>");
}
retlink.append("</a>");
return retlink.toString();
}
/**
* Get Html Hyper Link.
*
* @param link String name of the file.
* @param where Position of the link in the file. Character '#' is not
* needed.
* @param label Tag for the link.
* @param title String that describes the link's content for accessibility.
* @param target Target frame.
* @return a content tree for the hyper link.
*/
public Content getHyperLink(String link, String where,
Content label, String title, String target) {
if (where != null && where.length() != 0) {
link += "#" + where;
}
HtmlTree anchor = HtmlTree.A(link, label);
if (title != null && title.length() != 0) {
anchor.addAttr(HtmlAttr.TITLE, title);
}
if (target != null && target.length() != 0) {
anchor.addAttr(HtmlAttr.TARGET, target);
}
return anchor;
}
/**
* Get a hyperlink to a file.
*
* @param link String name of the file
* @param label Label for the link
* @return a content for the hyperlink to the file
*/
public Content getHyperLink(String link, Content label) {
return getHyperLink(link, "", label);
}
/**
* Get link string without positioning in the file.
*
* @param link String name of the file.
* @param label Tag for the link.
* @return Strign Hyper link.
*/
public String getHyperLinkString(String link, String label) {
return getHyperLinkString(link, "", label, false);
}
/**
* Print the name of the package, this class is in.
*
* @param cd ClassDoc.
*/
public void printPkgName(ClassDoc cd) {
print(getPkgName(cd));
}
/**
* Get the name of the package, this class is in.
*
* @param cd ClassDoc.
*/
public String getPkgName(ClassDoc cd) {
String pkgName = cd.containingPackage().name();
if (pkgName.length() > 0) {
pkgName += ".";
return pkgName;
}
return "";
}
/**
* Keep track of member details list. Print the definition list start tag
* if it is not printed yet.
*/
public void printMemberDetailsListStartTag () {
if (!getMemberDetailsListPrinted()) {
dl();
memberDetailsListPrinted = true;
}
}
/**
* Print the definition list end tag if the list start tag was printed.
*/
public void printMemberDetailsListEndTag () {
if (getMemberDetailsListPrinted()) {
dlEnd();
memberDetailsListPrinted = false;
}
}
public boolean getMemberDetailsListPrinted() {
return memberDetailsListPrinted;
}
/**
* Print the frameset version of the Html file header.
* Called only when generating an HTML frameset file.
*
* @param title Title of this HTML document
* @param noTimeStamp If true, don't print time stamp in header
* @param frameset the frameset to be added to the HTML document
*/
public void printFramesetDocument(String title, boolean noTimeStamp,
Content frameset) {
Content htmlDocType = DocType.Frameset();
Content htmlComment = new Comment(configuration.getText("doclet.New_Page"));
Content head = new HtmlTree(HtmlTag.HEAD);
if (! noTimeStamp) {
Content headComment = new Comment("Generated by javadoc on " + today());
head.addContent(headComment);
}
if (configuration.charset.length() > 0) {
Content meta = HtmlTree.META("Content-Type", "text/html",
configuration.charset);
head.addContent(meta);
}
Content windowTitle = HtmlTree.TITLE(new StringContent(title));
head.addContent(windowTitle);
head.addContent(getFramesetJavaScript());
Content htmlTree = HtmlTree.HTML(configuration.getLocale().getLanguage(),
head, frameset);
Content htmlDocument = new HtmlDocument(htmlDocType,
htmlComment, htmlTree);
print(htmlDocument.toString());
}
/**
* Print the appropriate spaces to format the class tree in the class page.
*
* @param len Number of spaces.
*/
public String spaces(int len) {
String space = "";
for (int i = 0; i < len; i++) {
space += " ";
}
return space;
}
/**
* Print the closing </body> and </html> tags.
*/
public void printBodyHtmlEnd() {
println();
bodyEnd();
htmlEnd();
}
/**
* Calls {@link #printBodyHtmlEnd()} method.
*/
public void printFooter() {
printBodyHtmlEnd();
}
/**
* Print closing </html> tag.
*/
public void printFrameFooter() {
htmlEnd();
}
/**
* Print ten non-breaking spaces("&nbsp;").
*/
public void printNbsps() {
print(" ");
}
/**
* Get the day and date information for today, depending upon user option.
*
* @return String Today.
* @see java.util.Calendar
* @see java.util.GregorianCalendar
* @see java.util.TimeZone
*/
public String today() {
Calendar calendar = new GregorianCalendar(TimeZone.getDefault());
return calendar.getTime().toString();
}
}
| 13,585 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlStyle.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlStyle.java | /*
* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
/**
* Enum representing HTML styles. The name map to values in the CSS file.
*
* @author Bhavesh Patel
*/
public enum HtmlStyle {
aboutLanguage,
altColor,
bar,
block,
blockList,
blockListLast,
bottomNav,
classUseContainer,
colFirst,
colLast,
colOne,
constantValuesContainer,
contentContainer,
description,
details,
docSummary,
header,
horizontal,
footer,
indexContainer,
indexHeader,
inheritance,
legalCopy,
nameValue,
navBarCell1Rev,
navList,
overviewSummary,
packageSummary,
rowColor,
serializedFormContainer,
sourceContainer,
sourceLineNo,
strong,
subNav,
subNavList,
subTitle,
summary,
deprecatedContent,
tabEnd,
title,
topNav;
}
| 2,068 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlWriter.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import java.io.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for the Html format code generation.
* Initilizes PrintWriter with FileWriter, to enable print
* related methods to generate the code to the named File through FileWriter.
*
* @since 1.2
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class HtmlWriter extends PrintWriter {
/**
* Name of the file, to which this writer is writing to.
*/
protected final String htmlFilename;
/**
* The window title of this file
*/
protected String winTitle;
/**
* URL file separator string("/").
*/
public static final String fileseparator =
DirectoryManager.URL_FILE_SEPARATOR;
/**
* The configuration
*/
protected Configuration configuration;
/**
* The flag to indicate whether a member details list is printed or not.
*/
protected boolean memberDetailsListPrinted;
/**
* Header for tables displaying packages and description..
*/
protected final String[] packageTableHeader;
/**
* Summary for use tables displaying class and package use.
*/
protected final String useTableSummary;
/**
* Column header for class docs displaying Modifier and Type header.
*/
protected final String modifierTypeHeader;
public final Content overviewLabel;
public final Content defaultPackageLabel;
public final Content packageLabel;
public final Content useLabel;
public final Content prevLabel;
public final Content nextLabel;
public final Content prevclassLabel;
public final Content nextclassLabel;
public final Content summaryLabel;
public final Content detailLabel;
public final Content framesLabel;
public final Content noframesLabel;
public final Content treeLabel;
public final Content classLabel;
public final Content deprecatedLabel;
public final Content deprecatedPhrase;
public final Content allclassesLabel;
public final Content indexLabel;
public final Content helpLabel;
public final Content seeLabel;
public final Content descriptionLabel;
public final Content prevpackageLabel;
public final Content nextpackageLabel;
public final Content packagesLabel;
public final Content methodDetailsLabel;
public final Content annotationTypeDetailsLabel;
public final Content fieldDetailsLabel;
public final Content constructorDetailsLabel;
public final Content enumConstantsDetailsLabel;
public final Content specifiedByLabel;
public final Content overridesLabel;
public final Content descfrmClassLabel;
public final Content descfrmInterfaceLabel;
/**
* Constructor.
*
* @param path The directory path to be created for this file
* or null if none to be created.
* @param filename File Name to which the PrintWriter will
* do the Output.
* @param docencoding Encoding to be used for this file.
* @exception IOException Exception raised by the FileWriter is passed on
* to next level.
* @exception UnSupportedEncodingException Exception raised by the
* OutputStreamWriter is passed on to next level.
*/
public HtmlWriter(Configuration configuration,
String path, String filename, String docencoding)
throws IOException, UnsupportedEncodingException {
super(Util.genWriter(configuration, path, filename, docencoding));
this.configuration = configuration;
htmlFilename = filename;
this.memberDetailsListPrinted = false;
packageTableHeader = new String[] {
configuration.getText("doclet.Package"),
configuration.getText("doclet.Description")
};
useTableSummary = configuration.getText("doclet.Use_Table_Summary",
configuration.getText("doclet.packages"));
modifierTypeHeader = configuration.getText("doclet.0_and_1",
configuration.getText("doclet.Modifier"),
configuration.getText("doclet.Type"));
overviewLabel = getResource("doclet.Overview");
defaultPackageLabel = new RawHtml(
DocletConstants.DEFAULT_PACKAGE_NAME);
packageLabel = getResource("doclet.Package");
useLabel = getResource("doclet.navClassUse");
prevLabel = getResource("doclet.Prev");
nextLabel = getResource("doclet.Next");
prevclassLabel = getResource("doclet.Prev_Class");
nextclassLabel = getResource("doclet.Next_Class");
summaryLabel = getResource("doclet.Summary");
detailLabel = getResource("doclet.Detail");
framesLabel = getResource("doclet.Frames");
noframesLabel = getResource("doclet.No_Frames");
treeLabel = getResource("doclet.Tree");
classLabel = getResource("doclet.Class");
deprecatedLabel = getResource("doclet.navDeprecated");
deprecatedPhrase = getResource("doclet.Deprecated");
allclassesLabel = getResource("doclet.All_Classes");
indexLabel = getResource("doclet.Index");
helpLabel = getResource("doclet.Help");
seeLabel = getResource("doclet.See");
descriptionLabel = getResource("doclet.Description");
prevpackageLabel = getResource("doclet.Prev_Package");
nextpackageLabel = getResource("doclet.Next_Package");
packagesLabel = getResource("doclet.Packages");
methodDetailsLabel = getResource("doclet.Method_Detail");
annotationTypeDetailsLabel = getResource("doclet.Annotation_Type_Member_Detail");
fieldDetailsLabel = getResource("doclet.Field_Detail");
constructorDetailsLabel = getResource("doclet.Constructor_Detail");
enumConstantsDetailsLabel = getResource("doclet.Enum_Constant_Detail");
specifiedByLabel = getResource("doclet.Specified_By");
overridesLabel = getResource("doclet.Overrides");
descfrmClassLabel = getResource("doclet.Description_From_Class");
descfrmInterfaceLabel = getResource("doclet.Description_From_Interface");
}
/**
* Get the configuration string as a content.
*
* @param key the key to look for in the configuration file
* @return a content tree for the text
*/
public Content getResource(String key) {
return new StringContent(configuration.getText(key));
}
/**
* Get the configuration string as a content.
*
* @param key the key to look for in the configuration file
* @param a1 string argument added to configuration text
* @return a content tree for the text
*/
public Content getResource(String key, String a1) {
return new RawHtml(configuration.getText(key, a1));
}
/**
* Get the configuration string as a content.
*
* @param key the key to look for in the configuration file
* @param a1 string argument added to configuration text
* @param a2 string argument added to configuration text
* @return a content tree for the text
*/
public Content getResource(String key, String a1, String a2) {
return new RawHtml(configuration.getText(key, a1, a2));
}
/**
* Print <HTML> tag. Add a newline character at the end.
*/
public void html() {
println("<HTML lang=\"" + configuration.getLocale().getLanguage() + "\">");
}
/**
* Print </HTML> tag. Add a newline character at the end.
*/
public void htmlEnd() {
println("</HTML>");
}
/**
* Print the script code to be embeded before the </HEAD> tag.
*/
protected void printWinTitleScript(String winTitle){
if(winTitle != null && winTitle.length() > 0) {
script();
println("function windowTitle()");
println("{");
println(" if (location.href.indexOf('is-external=true') == -1) {");
println(" parent.document.title=\"" + winTitle + "\";");
println(" }");
println("}");
scriptEnd();
noScript();
noScriptEnd();
}
}
/**
* Returns an HtmlTree for the SCRIPT tag.
*
* @return an HtmlTree for the SCRIPT tag
*/
protected HtmlTree getWinTitleScript(){
HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
if(winTitle != null && winTitle.length() > 0) {
script.addAttr(HtmlAttr.TYPE, "text/javascript");
String scriptCode = "<!--" + DocletConstants.NL +
" if (location.href.indexOf('is-external=true') == -1) {" + DocletConstants.NL +
" parent.document.title=\"" + winTitle + "\";" + DocletConstants.NL +
" }" + DocletConstants.NL +
"//-->" + DocletConstants.NL;
RawHtml scriptContent = new RawHtml(scriptCode);
script.addContent(scriptContent);
}
return script;
}
/**
* Returns a content tree for the SCRIPT tag for the main page(index.html).
*
* @return a content for the SCRIPT tag
*/
protected Content getFramesetJavaScript(){
HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
script.addAttr(HtmlAttr.TYPE, "text/javascript");
String scriptCode = DocletConstants.NL + " targetPage = \"\" + window.location.search;" + DocletConstants.NL +
" if (targetPage != \"\" && targetPage != \"undefined\")" + DocletConstants.NL +
" targetPage = targetPage.substring(1);" + DocletConstants.NL +
" if (targetPage.indexOf(\":\") != -1)" + DocletConstants.NL +
" targetPage = \"undefined\";" + DocletConstants.NL +
" function loadFrames() {" + DocletConstants.NL +
" if (targetPage != \"\" && targetPage != \"undefined\")" + DocletConstants.NL +
" top.classFrame.location = top.targetPage;" + DocletConstants.NL +
" }" + DocletConstants.NL;
RawHtml scriptContent = new RawHtml(scriptCode);
script.addContent(scriptContent);
return script;
}
/**
* Print the Javascript <SCRIPT> start tag with its type
* attribute.
*/
public void script() {
println("<SCRIPT type=\"text/javascript\">");
}
/**
* Print the Javascript </SCRIPT> end tag.
*/
public void scriptEnd() {
println("</SCRIPT>");
}
/**
* Print the Javascript <NOSCRIPT> start tag.
*/
public void noScript() {
println("<NOSCRIPT>");
}
/**
* Print the Javascript </NOSCRIPT> end tag.
*/
public void noScriptEnd() {
println("</NOSCRIPT>");
}
/**
* Return the Javascript call to be embedded in the <BODY> tag.
* Return nothing if winTitle is empty.
* @return the Javascript call to be embedded in the <BODY> tag.
*/
protected String getWindowTitleOnload(){
if(winTitle != null && winTitle.length() > 0) {
return " onload=\"windowTitle();\"";
} else {
return "";
}
}
/**
* Print <BODY BGCOLOR="bgcolor">, including JavaScript
* "onload" call to load windowtitle script. This script shows the name
* of the document in the window title bar when frames are on.
*
* @param bgcolor Background color.
* @param includeScript boolean set true if printing windowtitle script
*/
public void body(String bgcolor, boolean includeScript) {
print("<BODY BGCOLOR=\"" + bgcolor + "\"");
if (includeScript) {
print(getWindowTitleOnload());
}
println(">");
}
/**
* Returns an HtmlTree for the BODY tag.
*
* @param includeScript set true if printing windowtitle script
* @param title title for the window
* @return an HtmlTree for the BODY tag
*/
public HtmlTree getBody(boolean includeScript, String title) {
HtmlTree body = new HtmlTree(HtmlTag.BODY);
// Set window title string which is later printed
this.winTitle = title;
// Don't print windowtitle script for overview-frame, allclasses-frame
// and package-frame
if (includeScript) {
body.addContent(getWinTitleScript());
Content noScript = HtmlTree.NOSCRIPT(
HtmlTree.DIV(getResource("doclet.No_Script_Message")));
body.addContent(noScript);
}
return body;
}
/**
* Print </BODY> tag. Add a newline character at the end.
*/
public void bodyEnd() {
println("</BODY>");
}
/**
* Print <TITLE> tag. Add a newline character at the end.
*/
public void title() {
println("<TITLE>");
}
/**
* Print <TITLE> tag. Add a newline character at the end.
*
* @param winTitle The title of this document.
*/
public void title(String winTitle) {
// Set window title string which is later printed
this.winTitle = winTitle;
title();
}
/**
* Returns an HtmlTree for the TITLE tag.
*
* @return an HtmlTree for the TITLE tag
*/
public HtmlTree getTitle() {
HtmlTree title = HtmlTree.TITLE(new StringContent(winTitle));
return title;
}
/**
* Print </TITLE> tag. Add a newline character at the end.
*/
public void titleEnd() {
println("</TITLE>");
}
/**
* Print <UL> tag. Add a newline character at the end.
*/
public void ul() {
println("<UL>");
}
/**
* Print </UL> tag. Add a newline character at the end.
*/
public void ulEnd() {
println("</UL>");
}
/**
* Print <LI> tag.
*/
public void li() {
print("<LI>");
}
/**
* Print <LI TYPE="type"> tag.
*
* @param type Type string.
*/
public void li(String type) {
print("<LI TYPE=\"" + type + "\">");
}
/**
* Print <H1> tag. Add a newline character at the end.
*/
public void h1() {
println("<H1>");
}
/**
* Print </H1> tag. Add a newline character at the end.
*/
public void h1End() {
println("</H1>");
}
/**
* Print text with <H1> tag. Also adds </H1> tag. Add a newline character
* at the end of the text.
*
* @param text Text to be printed with <H1> format.
*/
public void h1(String text) {
h1();
println(text);
h1End();
}
/**
* Print <H2> tag. Add a newline character at the end.
*/
public void h2() {
println("<H2>");
}
/**
* Print text with <H2> tag. Also adds </H2> tag. Add a newline character
* at the end of the text.
*
* @param text Text to be printed with <H2> format.
*/
public void h2(String text) {
h2();
println(text);
h2End();
}
/**
* Print </H2> tag. Add a newline character at the end.
*/
public void h2End() {
println("</H2>");
}
/**
* Print <H3> tag. Add a newline character at the end.
*/
public void h3() {
println("<H3>");
}
/**
* Print text with <H3> tag. Also adds </H3> tag. Add a newline character
* at the end of the text.
*
* @param text Text to be printed with <H3> format.
*/
public void h3(String text) {
h3();
println(text);
h3End();
}
/**
* Print </H3> tag. Add a newline character at the end.
*/
public void h3End() {
println("</H3>");
}
/**
* Print <H4> tag. Add a newline character at the end.
*/
public void h4() {
println("<H4>");
}
/**
* Print </H4> tag. Add a newline character at the end.
*/
public void h4End() {
println("</H4>");
}
/**
* Print text with <H4> tag. Also adds </H4> tag. Add a newline character
* at the end of the text.
*
* @param text Text to be printed with <H4> format.
*/
public void h4(String text) {
h4();
println(text);
h4End();
}
/**
* Print <H5> tag. Add a newline character at the end.
*/
public void h5() {
println("<H5>");
}
/**
* Print </H5> tag. Add a newline character at the end.
*/
public void h5End() {
println("</H5>");
}
/**
* Print HTML <IMG SRC="imggif" WIDTH="width" HEIGHT="height" ALT="imgname>
* tag. It prepends the "images" directory name to the "imggif". This
* method is used for oneone format generation. Add a newline character
* at the end.
*
* @param imggif Image GIF file.
* @param imgname Image name.
* @param width Width of the image.
* @param height Height of the image.
*/
public void img(String imggif, String imgname, int width, int height) {
println("<IMG SRC=\"images/" + imggif + ".gif\""
+ " WIDTH=\"" + width + "\" HEIGHT=\"" + height
+ "\" ALT=\"" + imgname + "\">");
}
/**
* Print <MENU> tag. Add a newline character at the end.
*/
public void menu() {
println("<MENU>");
}
/**
* Print </MENU> tag. Add a newline character at the end.
*/
public void menuEnd() {
println("</MENU>");
}
/**
* Print <PRE> tag. Add a newline character at the end.
*/
public void pre() {
println("<PRE>");
}
/**
* Print <PRE> tag without adding new line character at th eend.
*/
public void preNoNewLine() {
print("<PRE>");
}
/**
* Print </PRE> tag. Add a newline character at the end.
*/
public void preEnd() {
println("</PRE>");
}
/**
* Print <HR> tag. Add a newline character at the end.
*/
public void hr() {
println("<HR>");
}
/**
* Print <HR SIZE="size" WIDTH="widthpercent%"> tag. Add a newline
* character at the end.
*
* @param size Size of the ruler.
* @param widthPercent Percentage Width of the ruler
*/
public void hr(int size, int widthPercent) {
println("<HR SIZE=\"" + size + "\" WIDTH=\"" + widthPercent + "%\">");
}
/**
* Print <HR SIZE="size" NOSHADE> tag. Add a newline character at the end.
*
* @param size Size of the ruler.
* @param noshade noshade string.
*/
public void hr(int size, String noshade) {
println("<HR SIZE=\"" + size + "\" NOSHADE>");
}
/**
* Get the "<STRONG>" string.
*
* @return String Return String "<STRONG>";
*/
public String getStrong() {
return "<STRONG>";
}
/**
* Get the "</STRONG>" string.
*
* @return String Return String "</STRONG>";
*/
public String getStrongEnd() {
return "</STRONG>";
}
/**
* Print <STRONG> tag.
*/
public void strong() {
print("<STRONG>");
}
/**
* Print </STRONG> tag.
*/
public void strongEnd() {
print("</STRONG>");
}
/**
* Print text passed, in strong format using <STRONG> and </STRONG> tags.
*
* @param text String to be printed in between <STRONG> and </STRONG> tags.
*/
public void strong(String text) {
strong();
print(text);
strongEnd();
}
/**
* Print text passed, in Italics using <I> and </I> tags.
*
* @param text String to be printed in between <I> and </I> tags.
*/
public void italics(String text) {
print("<I>");
print(text);
println("</I>");
}
/**
* Return, text passed, with Italics <i> and </i> tags, surrounding it.
* So if the text passed is "Hi", then string returned will be "<i>Hi</i>".
*
* @param text String to be printed in between <I> and </I> tags.
*/
public String italicsText(String text) {
return "<i>" + text + "</i>";
}
public String codeText(String text) {
return "<code>" + text + "</code>";
}
/**
* Print "&nbsp;", non-breaking space.
*/
public void space() {
print(" ");
}
/**
* Return "&nbsp;", non-breaking space.
*/
public Content getSpace() {
return RawHtml.nbsp;
}
/**
* Print <DL> tag. Add a newline character at the end.
*/
public void dl() {
println("<DL>");
}
/**
* Print </DL> tag. Add a newline character at the end.
*/
public void dlEnd() {
println("</DL>");
}
/**
* Print <DT> tag.
*/
public void dt() {
print("<DT>");
}
/**
* Print </DT> tag.
*/
public void dtEnd() {
print("</DT>");
}
/**
* Print <DD> tag.
*/
public void dd() {
print("<DD>");
}
/**
* Print </DD> tag. Add a newline character at the end.
*/
public void ddEnd() {
println("</DD>");
}
/**
* Print <SUP> tag. Add a newline character at the end.
*/
public void sup() {
println("<SUP>");
}
/**
* Print </SUP> tag. Add a newline character at the end.
*/
public void supEnd() {
println("</SUP>");
}
/**
* Print <FONT SIZE="size"> tag. Add a newline character at the end.
*
* @param size String size.
*/
public void font(String size) {
println("<FONT SIZE=\"" + size + "\">");
}
/**
* Print <FONT SIZE="size"> tag.
*
* @param size String size.
*/
public void fontNoNewLine(String size) {
print("<FONT SIZE=\"" + size + "\">");
}
/**
* Print <FONT CLASS="stylename"> tag. Add a newline character at the end.
*
* @param stylename String stylename.
*/
public void fontStyle(String stylename) {
print("<FONT CLASS=\"" + stylename + "\">");
}
/**
* Print <FONT SIZE="size" CLASS="stylename"> tag. Add a newline character
* at the end.
*
* @param size String size.
* @param stylename String stylename.
*/
public void fontSizeStyle(String size, String stylename) {
println("<FONT size=\"" + size + "\" CLASS=\"" + stylename + "\">");
}
/**
* Print </FONT> tag.
*/
public void fontEnd() {
print("</FONT>");
}
/**
* Get the "<FONT COLOR="color">" string.
*
* @param color String color.
* @return String Return String "<FONT COLOR="color">".
*/
public String getFontColor(String color) {
return "<FONT COLOR=\"" + color + "\">";
}
/**
* Get the "</FONT>" string.
*
* @return String Return String "</FONT>";
*/
public String getFontEnd() {
return "</FONT>";
}
/**
* Print <CENTER> tag. Add a newline character at the end.
*/
public void center() {
println("<CENTER>");
}
/**
* Print </CENTER> tag. Add a newline character at the end.
*/
public void centerEnd() {
println("</CENTER>");
}
/**
* Print anchor <A NAME="name"> tag.
*
* @param name Name String.
*/
public void aName(String name) {
print("<A NAME=\"" + name + "\">");
}
/**
* Print </A> tag.
*/
public void aEnd() {
print("</A>");
}
/**
* Print <I> tag.
*/
public void italic() {
print("<I>");
}
/**
* Print </I> tag.
*/
public void italicEnd() {
print("</I>");
}
/**
* Print contents within anchor <A NAME="name"> tags.
*
* @param name String name.
* @param content String contents.
*/
public void anchor(String name, String content) {
aName(name);
print(content);
aEnd();
}
/**
* Print anchor <A NAME="name"> and </A>tags. Print comment string
* "<!-- -->" within those tags.
*
* @param name String name.
*/
public void anchor(String name) {
anchor(name, "<!-- -->");
}
/**
* Print newline and then print <P> tag. Add a newline character at the
* end.
*/
public void p() {
println();
println("<P>");
}
/**
* Print newline and then print </P> tag. Add a newline character at the
* end.
*/
public void pEnd() {
println();
println("</P>");
}
/**
* Print newline and then print <BR> tag. Add a newline character at the
* end.
*/
public void br() {
println();
println("<BR>");
}
/**
* Print <ADDRESS> tag. Add a newline character at the end.
*/
public void address() {
println("<ADDRESS>");
}
/**
* Print </ADDRESS> tag. Add a newline character at the end.
*/
public void addressEnd() {
println("</ADDRESS>");
}
/**
* Print <HEAD> tag. Add a newline character at the end.
*/
public void head() {
println("<HEAD>");
}
/**
* Print </HEAD> tag. Add a newline character at the end.
*/
public void headEnd() {
println("</HEAD>");
}
/**
* Print <CODE> tag.
*/
public void code() {
print("<CODE>");
}
/**
* Print </CODE> tag.
*/
public void codeEnd() {
print("</CODE>");
}
/**
* Print <EM> tag. Add a newline character at the end.
*/
public void em() {
println("<EM>");
}
/**
* Print </EM> tag. Add a newline character at the end.
*/
public void emEnd() {
println("</EM>");
}
/**
* Print HTML <TABLE BORDER="border" WIDTH="width"
* CELLPADDING="cellpadding" CELLSPACING="cellspacing"> tag.
*
* @param border Border size.
* @param width Width of the table.
* @param cellpadding Cellpadding for the table cells.
* @param cellspacing Cellspacing for the table cells.
*/
public void table(int border, String width, int cellpadding,
int cellspacing) {
println(DocletConstants.NL +
"<TABLE BORDER=\"" + border +
"\" WIDTH=\"" + width +
"\" CELLPADDING=\"" + cellpadding +
"\" CELLSPACING=\"" + cellspacing +
"\" SUMMARY=\"\">");
}
/**
* Print HTML <TABLE BORDER="border" WIDTH="width"
* CELLPADDING="cellpadding" CELLSPACING="cellspacing" SUMMARY="summary"> tag.
*
* @param border Border size.
* @param width Width of the table.
* @param cellpadding Cellpadding for the table cells.
* @param cellspacing Cellspacing for the table cells.
* @param summary Table summary.
*/
public void table(int border, String width, int cellpadding,
int cellspacing, String summary) {
println(DocletConstants.NL +
"<TABLE BORDER=\"" + border +
"\" WIDTH=\"" + width +
"\" CELLPADDING=\"" + cellpadding +
"\" CELLSPACING=\"" + cellspacing +
"\" SUMMARY=\"" + summary + "\">");
}
/**
* Print HTML <TABLE BORDER="border" CELLPADDING="cellpadding"
* CELLSPACING="cellspacing"> tag.
*
* @param border Border size.
* @param cellpadding Cellpadding for the table cells.
* @param cellspacing Cellspacing for the table cells.
*/
public void table(int border, int cellpadding, int cellspacing) {
println(DocletConstants.NL +
"<TABLE BORDER=\"" + border +
"\" CELLPADDING=\"" + cellpadding +
"\" CELLSPACING=\"" + cellspacing +
"\" SUMMARY=\"\">");
}
/**
* Print HTML <TABLE BORDER="border" CELLPADDING="cellpadding"
* CELLSPACING="cellspacing" SUMMARY="summary"> tag.
*
* @param border Border size.
* @param cellpadding Cellpadding for the table cells.
* @param cellspacing Cellspacing for the table cells.
* @param summary Table summary.
*/
public void table(int border, int cellpadding, int cellspacing, String summary) {
println(DocletConstants.NL +
"<TABLE BORDER=\"" + border +
"\" CELLPADDING=\"" + cellpadding +
"\" CELLSPACING=\"" + cellspacing +
"\" SUMMARY=\"" + summary + "\">");
}
/**
* Print HTML <TABLE BORDER="border" WIDTH="width">
*
* @param border Border size.
* @param width Width of the table.
*/
public void table(int border, String width) {
println(DocletConstants.NL +
"<TABLE BORDER=\"" + border +
"\" WIDTH=\"" + width +
"\" SUMMARY=\"\">");
}
/**
* Print the HTML table tag with border size 0 and width 100%.
*/
public void table() {
table(0, "100%");
}
/**
* Print </TABLE> tag. Add a newline character at the end.
*/
public void tableEnd() {
println("</TABLE>");
}
/**
* Print <TR> tag. Add a newline character at the end.
*/
public void tr() {
println("<TR>");
}
/**
* Print </TR> tag. Add a newline character at the end.
*/
public void trEnd() {
println("</TR>");
}
/**
* Print <TD> tag.
*/
public void td() {
print("<TD>");
}
/**
* Print <TD NOWRAP> tag.
*/
public void tdNowrap() {
print("<TD NOWRAP>");
}
/**
* Print <TD WIDTH="width"> tag.
*
* @param width String width.
*/
public void tdWidth(String width) {
print("<TD WIDTH=\"" + width + "\">");
}
/**
* Print </TD> tag. Add a newline character at the end.
*/
public void tdEnd() {
println("</TD>");
}
/**
* Print <LINK str> tag.
*
* @param str String.
*/
public void link(String str) {
println("<LINK " + str + ">");
}
/**
* Print "<!-- " comment start string.
*/
public void commentStart() {
print("<!-- ");
}
/**
* Print "-->" comment end string. Add a newline character at the end.
*/
public void commentEnd() {
println("-->");
}
/**
* Print <CAPTION CLASS="stylename"> tag. Adds a newline character
* at the end.
*
* @param stylename style to be applied.
*/
public void captionStyle(String stylename) {
println("<CAPTION CLASS=\"" + stylename + "\">");
}
/**
* Print </CAPTION> tag. Add a newline character at the end.
*/
public void captionEnd() {
println("</CAPTION>");
}
/**
* Print <TR BGCOLOR="color" CLASS="stylename"> tag. Adds a newline character
* at the end.
*
* @param color String color.
* @param stylename String stylename.
*/
public void trBgcolorStyle(String color, String stylename) {
println("<TR BGCOLOR=\"" + color + "\" CLASS=\"" + stylename + "\">");
}
/**
* Print <TR BGCOLOR="color"> tag. Adds a newline character at the end.
*
* @param color String color.
*/
public void trBgcolor(String color) {
println("<TR BGCOLOR=\"" + color + "\">");
}
/**
* Print <TR ALIGN="align" VALIGN="valign"> tag. Adds a newline character
* at the end.
*
* @param align String align.
* @param valign String valign.
*/
public void trAlignVAlign(String align, String valign) {
println("<TR ALIGN=\"" + align + "\" VALIGN=\"" + valign + "\">");
}
/**
* Print <TH ALIGN="align"> tag.
*
* @param align the align attribute.
*/
public void thAlign(String align) {
print("<TH ALIGN=\"" + align + "\">");
}
/**
* Print <TH CLASS="stylename" SCOPE="scope" NOWRAP> tag.
*
* @param stylename style to be applied.
* @param scope the scope attribute.
*/
public void thScopeNoWrap(String stylename, String scope) {
print("<TH CLASS=\"" + stylename + "\" SCOPE=\"" + scope + "\" NOWRAP>");
}
/*
* Returns a header for Modifier and Type column of a table.
*/
public String getModifierTypeHeader() {
return modifierTypeHeader;
}
/**
* Print <TH align="align" COLSPAN=i> tag.
*
* @param align the align attribute.
* @param i integer.
*/
public void thAlignColspan(String align, int i) {
print("<TH ALIGN=\"" + align + "\" COLSPAN=\"" + i + "\">");
}
/**
* Print <TH align="align" NOWRAP> tag.
*
* @param align the align attribute.
*/
public void thAlignNowrap(String align) {
print("<TH ALIGN=\"" + align + "\" NOWRAP>");
}
/**
* Print </TH> tag. Add a newline character at the end.
*/
public void thEnd() {
println("</TH>");
}
/**
* Print <TD COLSPAN=i> tag.
*
* @param i integer.
*/
public void tdColspan(int i) {
print("<TD COLSPAN=" + i + ">");
}
/**
* Print <TD BGCOLOR="color" CLASS="stylename"> tag.
*
* @param color String color.
* @param stylename String stylename.
*/
public void tdBgcolorStyle(String color, String stylename) {
print("<TD BGCOLOR=\"" + color + "\" CLASS=\"" + stylename + "\">");
}
/**
* Print <TD COLSPAN=i BGCOLOR="color" CLASS="stylename"> tag.
*
* @param i integer.
* @param color String color.
* @param stylename String stylename.
*/
public void tdColspanBgcolorStyle(int i, String color, String stylename) {
print("<TD COLSPAN=" + i + " BGCOLOR=\"" + color + "\" CLASS=\"" +
stylename + "\">");
}
/**
* Print <TD ALIGN="align"> tag. Adds a newline character
* at the end.
*
* @param align String align.
*/
public void tdAlign(String align) {
print("<TD ALIGN=\"" + align + "\">");
}
/**
* Print <TD ALIGN="align" CLASS="stylename"> tag.
*
* @param align String align.
* @param stylename String stylename.
*/
public void tdVAlignClass(String align, String stylename) {
print("<TD VALIGN=\"" + align + "\" CLASS=\"" + stylename + "\">");
}
/**
* Print <TD VALIGN="valign"> tag.
*
* @param valign String valign.
*/
public void tdVAlign(String valign) {
print("<TD VALIGN=\"" + valign + "\">");
}
/**
* Print <TD ALIGN="align" VALIGN="valign"> tag.
*
* @param align String align.
* @param valign String valign.
*/
public void tdAlignVAlign(String align, String valign) {
print("<TD ALIGN=\"" + align + "\" VALIGN=\"" + valign + "\">");
}
/**
* Print <TD ALIGN="align" ROWSPAN=rowspan> tag.
*
* @param align String align.
* @param rowspan integer rowspan.
*/
public void tdAlignRowspan(String align, int rowspan) {
print("<TD ALIGN=\"" + align + "\" ROWSPAN=" + rowspan + ">");
}
/**
* Print <TD ALIGN="align" VALIGN="valign" ROWSPAN=rowspan> tag.
*
* @param align String align.
* @param valign String valign.
* @param rowspan integer rowspan.
*/
public void tdAlignVAlignRowspan(String align, String valign,
int rowspan) {
print("<TD ALIGN=\"" + align + "\" VALIGN=\"" + valign
+ "\" ROWSPAN=" + rowspan + ">");
}
/**
* Print <BLOCKQUOTE> tag. Add a newline character at the end.
*/
public void blockquote() {
println("<BLOCKQUOTE>");
}
/**
* Print </BLOCKQUOTE> tag. Add a newline character at the end.
*/
public void blockquoteEnd() {
println("</BLOCKQUOTE>");
}
/**
* Get the "<code>" string.
*
* @return String Return String "<code>";
*/
public String getCode() {
return "<code>";
}
/**
* Get the "</code>" string.
*
* @return String Return String "</code>";
*/
public String getCodeEnd() {
return "</code>";
}
/**
* Print <NOFRAMES> tag. Add a newline character at the end.
*/
public void noFrames() {
println("<NOFRAMES>");
}
/**
* Print </NOFRAMES> tag. Add a newline character at the end.
*/
public void noFramesEnd() {
println("</NOFRAMES>");
}
}
| 39,080 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlConstants.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlConstants.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import com.sun.tools.doclets.internal.toolkit.Content;
/**
* Stores constants for Html Doclet.
*
* @author Bhavesh Patel
*/
public class HtmlConstants {
/**
* Marker to identify start of top navigation bar.
*/
public static final Content START_OF_TOP_NAVBAR =
new Comment("========= START OF TOP NAVBAR =======");
/**
* Marker to identify start of bottom navigation bar.
*/
public static final Content START_OF_BOTTOM_NAVBAR =
new Comment("======= START OF BOTTOM NAVBAR ======");
/**
* Marker to identify end of top navigation bar.
*/
public static final Content END_OF_TOP_NAVBAR =
new Comment("========= END OF TOP NAVBAR =========");
/**
* Marker to identify end of bottom navigation bar.
*/
public static final Content END_OF_BOTTOM_NAVBAR =
new Comment("======== END OF BOTTOM NAVBAR =======");
/**
* Marker to identify start of class data.
*/
public static final Content START_OF_CLASS_DATA =
new Comment("======== START OF CLASS DATA ========");
/**
* Marker to identify end of class data.
*/
public static final Content END_OF_CLASS_DATA =
new Comment("========= END OF CLASS DATA =========");
/**
* Marker to identify start of nested class summary.
*/
public static final Content START_OF_NESTED_CLASS_SUMMARY =
new Comment("======== NESTED CLASS SUMMARY ========");
/**
* Marker to identify start of annotation type optional member summary.
*/
public static final Content START_OF_ANNOTATION_TYPE_OPTIONAL_MEMBER_SUMMARY =
new Comment("=========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY ===========");
/**
* Marker to identify start of annotation type required member summary.
*/
public static final Content START_OF_ANNOTATION_TYPE_REQUIRED_MEMBER_SUMMARY =
new Comment("=========== ANNOTATION TYPE REQUIRED MEMBER SUMMARY ===========");
/**
* Marker to identify start of constructor summary.
*/
public static final Content START_OF_CONSTRUCTOR_SUMMARY =
new Comment("======== CONSTRUCTOR SUMMARY ========");
/**
* Marker to identify start of enum constants summary.
*/
public static final Content START_OF_ENUM_CONSTANT_SUMMARY =
new Comment("=========== ENUM CONSTANT SUMMARY ===========");
/**
* Marker to identify start of field summary.
*/
public static final Content START_OF_FIELD_SUMMARY =
new Comment("=========== FIELD SUMMARY ===========");
/**
* Marker to identify start of method summary.
*/
public static final Content START_OF_METHOD_SUMMARY =
new Comment("========== METHOD SUMMARY ===========");
/**
* Marker to identify start of annotation type details.
*/
public static final Content START_OF_ANNOTATION_TYPE_DETAILS =
new Comment("============ ANNOTATION TYPE MEMBER DETAIL ===========");
/**
* Marker to identify start of method details.
*/
public static final Content START_OF_METHOD_DETAILS =
new Comment("============ METHOD DETAIL ==========");
/**
* Marker to identify start of field details.
*/
public static final Content START_OF_FIELD_DETAILS =
new Comment("============ FIELD DETAIL ===========");
/**
* Marker to identify start of constructor details.
*/
public static final Content START_OF_CONSTRUCTOR_DETAILS =
new Comment("========= CONSTRUCTOR DETAIL ========");
/**
* Marker to identify start of enum constants details.
*/
public static final Content START_OF_ENUM_CONSTANT_DETAILS =
new Comment("============ ENUM CONSTANT DETAIL ===========");
/**
* Html tag for the page title heading.
*/
public static final HtmlTag TITLE_HEADING = HtmlTag.H1;
/**
* Html tag for the class page title heading.
*/
public static final HtmlTag CLASS_PAGE_HEADING = HtmlTag.H2;
/**
* Html tag for the content heading.
*/
public static final HtmlTag CONTENT_HEADING = HtmlTag.H2;
/**
* Html tag for the package name heading.
*/
public static final HtmlTag PACKAGE_HEADING = HtmlTag.H2;
/**
* Html tag for the member summary heading.
*/
public static final HtmlTag SUMMARY_HEADING = HtmlTag.H3;
/**
* Html tag for the inherited member summary heading.
*/
public static final HtmlTag INHERITED_SUMMARY_HEADING = HtmlTag.H3;
/**
* Html tag for the member details heading.
*/
public static final HtmlTag DETAILS_HEADING = HtmlTag.H3;
/**
* Html tag for the serialized member heading.
*/
public static final HtmlTag SERIALIZED_MEMBER_HEADING = HtmlTag.H3;
/**
* Html tag for the member heading.
*/
public static final HtmlTag MEMBER_HEADING = HtmlTag.H4;
}
| 6,279 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Comment.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/Comment.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating a comment for HTML pages of javadoc output.
*
* @author Bhavesh Patel
*/
public class Comment extends Content{
private String commentText;
/**
* Constructor to construct a Comment object.
*
* @param comment comment text for the comment
*/
public Comment(String comment) {
commentText = nullCheck(comment);
}
/**
* This method is not supported by the class.
*
* @param content content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(Content content) {
throw new DocletAbortException();
}
/**
* This method is not supported by the class.
*
* @param stringContent string content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(String stringContent) {
throw new DocletAbortException();
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return commentText.isEmpty();
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
if (!endsWithNewLine(contentBuilder))
contentBuilder.append(DocletConstants.NL);
contentBuilder.append("<!-- ");
contentBuilder.append(commentText);
contentBuilder.append(" -->" + DocletConstants.NL);
}
}
| 3,053 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlDocument.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlDocument.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import java.util.*;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating an HTML document for javadoc output.
*
* @author Bhavesh Patel
*/
public class HtmlDocument extends Content {
private List<Content> docContent = Collections.<Content>emptyList();
/**
* Constructor to construct an HTML document.
*
* @param docType document type for the HTML document
* @param docComment comment for the document
* @param htmlTree HTML tree of the document
*/
public HtmlDocument(Content docType, Content docComment, Content htmlTree) {
docContent = new ArrayList<Content>();
addContent(nullCheck(docType));
addContent(nullCheck(docComment));
addContent(nullCheck(htmlTree));
}
/**
* Constructor to construct an HTML document.
*
* @param docType document type for the HTML document
* @param htmlTree HTML tree of the document
*/
public HtmlDocument(Content docType, Content htmlTree) {
docContent = new ArrayList<Content>();
addContent(nullCheck(docType));
addContent(nullCheck(htmlTree));
}
/**
* Adds content for the HTML document.
*
* @param htmlContent html content to be added
*/
public void addContent(Content htmlContent) {
if (htmlContent.isValid())
docContent.add(htmlContent);
}
/**
* This method is not supported by the class.
*
* @param stringContent string content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(String stringContent) {
throw new DocletAbortException();
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return (docContent.isEmpty());
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
for (Content c : docContent)
c.write(contentBuilder);
}
}
| 3,437 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RawHtml.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/RawHtml.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating raw HTML content to be added to HTML pages of javadoc output.
*
* @author Bhavesh Patel
*/
public class RawHtml extends Content{
private String rawHtmlContent;
public static final Content nbsp = new RawHtml(" ");
/**
* Constructor to construct a RawHtml object.
*
* @param rawHtml raw HTML text to be added
*/
public RawHtml(String rawHtml) {
rawHtmlContent = nullCheck(rawHtml);
}
/**
* This method is not supported by the class.
*
* @param content content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(Content content) {
throw new DocletAbortException();
}
/**
* This method is not supported by the class.
*
* @param stringContent string content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(String stringContent) {
throw new DocletAbortException();
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return rawHtmlContent.isEmpty();
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
contentBuilder.append(rawHtmlContent);
}
}
| 2,942 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlTag.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlTag.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
/**
* Enum representing HTML tags.
*
* @author Bhavesh Patel
*/
public enum HtmlTag {
A(BlockType.INLINE, EndTag.END),
BLOCKQUOTE,
BODY(BlockType.OTHER, EndTag.END),
BR(BlockType.INLINE, EndTag.NOEND),
CAPTION,
CENTER,
CODE(BlockType.INLINE, EndTag.END),
DD,
DIV,
DL,
DT,
EM(BlockType.INLINE, EndTag.END),
FONT(BlockType.INLINE, EndTag.END),
FRAME(BlockType.OTHER, EndTag.NOEND),
FRAMESET(BlockType.OTHER, EndTag.END),
H1,
H2,
H3,
H4,
H5,
H6,
HEAD(BlockType.OTHER, EndTag.END),
HR(BlockType.BLOCK, EndTag.NOEND),
HTML(BlockType.OTHER, EndTag.END),
I(BlockType.INLINE, EndTag.END),
IMG(BlockType.INLINE, EndTag.NOEND),
LI,
LINK(BlockType.OTHER, EndTag.NOEND),
MENU,
META(BlockType.OTHER, EndTag.NOEND),
NOFRAMES(BlockType.OTHER, EndTag.END),
NOSCRIPT(BlockType.OTHER, EndTag.END),
OL,
P,
PRE,
SCRIPT(BlockType.OTHER, EndTag.END),
SMALL(BlockType.INLINE, EndTag.END),
SPAN(BlockType.INLINE, EndTag.END),
STRONG(BlockType.INLINE, EndTag.END),
TABLE,
TBODY,
TD,
TH,
TITLE(BlockType.OTHER, EndTag.END),
TR,
TT(BlockType.INLINE, EndTag.END),
UL;
protected final BlockType blockType;
protected final EndTag endTag;
private final String value;
/**
* Enum representing the type of HTML element.
*/
protected static enum BlockType {
BLOCK,
INLINE,
OTHER;
}
/**
* Enum representing HTML end tag requirement.
*/
protected static enum EndTag {
END,
NOEND;
}
HtmlTag() {
this(BlockType.BLOCK, EndTag.END);
}
HtmlTag(BlockType blockType, EndTag endTag ) {
this.blockType = blockType;
this.endTag = endTag;
this.value = name().toLowerCase();
}
/**
* Returns true if the end tag is required. This is specific to the standard
* doclet and does not exactly resemble the W3C specifications.
*
* @return true if end tag needs to be displayed else return false
*/
public boolean endTagRequired() {
return (endTag == EndTag.END);
}
public String toString() {
return value;
}
}
| 3,518 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
StringContent.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/StringContent.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating string content for HTML tags of javadoc output.
*
* @author Bhavesh Patel
*/
public class StringContent extends Content{
private StringBuilder stringContent;
/**
* Constructor to construct StringContent object.
*/
public StringContent() {
stringContent = new StringBuilder();
}
/**
* Constructor to construct StringContent object with some initial content.
*
* @param initialContent initial content for the object
*/
public StringContent(String initialContent) {
stringContent = new StringBuilder(
Util.escapeHtmlChars(nullCheck(initialContent)));
}
/**
* This method is not supported by the class.
*
* @param content content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(Content content) {
throw new DocletAbortException();
}
/**
* Adds content for the StringContent object. The method escapes
* HTML characters for the string content that is added.
*
* @param strContent string content to be added
*/
public void addContent(String strContent) {
stringContent.append(Util.escapeHtmlChars(nullCheck(strContent)));
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return (stringContent.length() == 0);
}
/**
* {@inheritDoc}
*/
public String toString() {
return stringContent.toString();
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
contentBuilder.append(stringContent);
}
}
| 3,174 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DocType.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/DocType.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating document type for HTML pages of javadoc output.
*
* @author Bhavesh Patel
*/
public class DocType extends Content{
private String docType;
private static DocType transitional;
private static DocType frameset;
/**
* Constructor to construct a DocType object.
*
* @param type the doctype to be added
*/
private DocType(String type, String dtd) {
docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 " + type +
"//EN\" \"" + dtd + "\">" + DocletConstants.NL;
}
/**
* Construct and return a HTML 4.01 transitional DocType content
*
* @return a content tree for transitional DocType
*/
public static DocType Transitional() {
if (transitional == null)
transitional = new DocType("Transitional", "http://www.w3.org/TR/html4/loose.dtd");
return transitional;
}
/**
* Construct and return a HTML 4.01 frameset DocType content
*
* @return a content tree for frameset DocType
*/
public static DocType Frameset() {
if (frameset == null)
frameset = new DocType("Frameset", "http://www.w3.org/TR/html4/frameset.dtd");
return frameset;
}
/**
* This method is not supported by the class.
*
* @param content content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(Content content) {
throw new DocletAbortException();
}
/**
* This method is not supported by the class.
*
* @param stringContent string content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(String stringContent) {
throw new DocletAbortException();
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return (docType.length() == 0);
}
/**
* {@inheritDoc}
*/
public void write(StringBuilder contentBuilder) {
contentBuilder.append(docType);
}
}
| 3,718 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
HtmlAttr.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlAttr.java | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
/**
* Enum representing HTML tag attributes.
*
* @author Bhavesh Patel
*/
public enum HtmlAttr {
ALT,
BORDER,
CELLPADDING,
CELLSPACING,
CHARSET,
CLASS,
CLEAR,
COLS,
CONTENT,
HREF,
HTTP_EQUIV("http-equiv"),
ID,
LANG,
NAME,
ONLOAD,
REL,
ROWS,
SCOPE,
SCROLLING,
SRC,
SUMMARY,
TARGET,
TITLE,
TYPE,
WIDTH;
private final String value;
HtmlAttr() {
this.value = name().toLowerCase();
}
HtmlAttr(String name) {
this.value = name;
}
public String toString() {
return value;
}
}
| 1,889 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JNI.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/JNI.java | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
/**
* Header file generator for JNI.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar(Revised)
*/
public class JNI extends Gen {
JNI(Util util) {
super(util);
}
public String getIncludes() {
return "#include <jni.h>";
}
public void write(OutputStream o, TypeElement clazz) throws Util.Exit {
try {
String cname = mangler.mangle(clazz.getQualifiedName(), Mangle.Type.CLASS);
PrintWriter pw = wrapWriter(o);
pw.println(guardBegin(cname));
pw.println(cppGuardBegin());
/* Write statics. */
List<VariableElement> classfields = getAllFields(clazz);
for (VariableElement v: classfields) {
if (!v.getModifiers().contains(Modifier.STATIC))
continue;
String s = null;
s = defineForStatic(clazz, v);
if (s != null) {
pw.println(s);
}
}
/* Write methods. */
List<ExecutableElement> classmethods = ElementFilter.methodsIn(clazz.getEnclosedElements());
for (ExecutableElement md: classmethods) {
if(md.getModifiers().contains(Modifier.NATIVE)){
TypeMirror mtr = types.erasure(md.getReturnType());
String sig = signature(md);
TypeSignature newtypesig = new TypeSignature(elems);
CharSequence methodName = md.getSimpleName();
boolean longName = false;
for (ExecutableElement md2: classmethods) {
if ((md2 != md)
&& (methodName.equals(md2.getSimpleName()))
&& (md2.getModifiers().contains(Modifier.NATIVE)))
longName = true;
}
pw.println("/*");
pw.println(" * Class: " + cname);
pw.println(" * Method: " +
mangler.mangle(methodName, Mangle.Type.FIELDSTUB));
pw.println(" * Signature: " + newtypesig.getTypeSignature(sig, mtr));
pw.println(" */");
pw.println("JNIEXPORT " + jniType(mtr) +
" JNICALL " +
mangler.mangleMethod(md, clazz,
(longName) ?
Mangle.Type.METHOD_JNI_LONG :
Mangle.Type.METHOD_JNI_SHORT));
pw.print(" (JNIEnv *, ");
List<? extends VariableElement> paramargs = md.getParameters();
List<TypeMirror> args = new ArrayList<TypeMirror>();
for (VariableElement p: paramargs) {
args.add(types.erasure(p.asType()));
}
if (md.getModifiers().contains(Modifier.STATIC))
pw.print("jclass");
else
pw.print("jobject");
for (TypeMirror arg: args) {
pw.print(", ");
pw.print(jniType(arg));
}
pw.println(");" + lineSep);
}
}
pw.println(cppGuardEnd());
pw.println(guardEnd(cname));
} catch (TypeSignature.SignatureException e) {
util.error("jni.sigerror", e.getMessage());
}
}
protected final String jniType(TypeMirror t) throws Util.Exit {
TypeElement throwable = elems.getTypeElement("java.lang.Throwable");
TypeElement jClass = elems.getTypeElement("java.lang.Class");
TypeElement jString = elems.getTypeElement("java.lang.String");
Element tclassDoc = types.asElement(t);
switch (t.getKind()) {
case ARRAY: {
TypeMirror ct = ((ArrayType) t).getComponentType();
switch (ct.getKind()) {
case BOOLEAN: return "jbooleanArray";
case BYTE: return "jbyteArray";
case CHAR: return "jcharArray";
case SHORT: return "jshortArray";
case INT: return "jintArray";
case LONG: return "jlongArray";
case FLOAT: return "jfloatArray";
case DOUBLE: return "jdoubleArray";
case ARRAY:
case DECLARED: return "jobjectArray";
default: throw new Error(ct.toString());
}
}
case VOID: return "void";
case BOOLEAN: return "jboolean";
case BYTE: return "jbyte";
case CHAR: return "jchar";
case SHORT: return "jshort";
case INT: return "jint";
case LONG: return "jlong";
case FLOAT: return "jfloat";
case DOUBLE: return "jdouble";
case DECLARED: {
if (tclassDoc.equals(jString))
return "jstring";
else if (types.isAssignable(t, throwable.asType()))
return "jthrowable";
else if (types.isAssignable(t, jClass.asType()))
return "jclass";
else
return "jobject";
}
}
util.bug("jni.unknown.type");
return null; /* dead code. */
}
}
| 7,552 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
LLNI.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/LLNI.java | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVisitor;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleTypeVisitor7;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar(Revised)
*/
public class LLNI extends Gen {
protected final char innerDelim = '$'; /* For inner classes */
protected Set<String> doneHandleTypes;
List<VariableElement> fields;
List<ExecutableElement> methods;
private boolean doubleAlign;
private int padFieldNum = 0;
LLNI(boolean doubleAlign, Util util) {
super(util);
this.doubleAlign = doubleAlign;
}
protected String getIncludes() {
return "";
}
protected void write(OutputStream o, TypeElement clazz) throws Util.Exit {
try {
String cname = mangleClassName(clazz.getQualifiedName().toString());
PrintWriter pw = wrapWriter(o);
fields = ElementFilter.fieldsIn(clazz.getEnclosedElements());
methods = ElementFilter.methodsIn(clazz.getEnclosedElements());
generateDeclsForClass(pw, clazz, cname);
// FIXME check if errors occurred on the PrintWriter and throw exception if so
} catch (TypeSignature.SignatureException e) {
util.error("llni.sigerror", e.getMessage());
}
}
protected void generateDeclsForClass(PrintWriter pw,
TypeElement clazz, String cname)
throws TypeSignature.SignatureException, Util.Exit {
doneHandleTypes = new HashSet<String>();
/* The following handle types are predefined in "typedefs.h". Suppress
inclusion in the output by generating them "into the blue" here. */
genHandleType(null, "java.lang.Class");
genHandleType(null, "java.lang.ClassLoader");
genHandleType(null, "java.lang.Object");
genHandleType(null, "java.lang.String");
genHandleType(null, "java.lang.Thread");
genHandleType(null, "java.lang.ThreadGroup");
genHandleType(null, "java.lang.Throwable");
pw.println("/* LLNI Header for class " + clazz.getQualifiedName() + " */" + lineSep);
pw.println("#ifndef _Included_" + cname);
pw.println("#define _Included_" + cname);
pw.println("#include \"typedefs.h\"");
pw.println("#include \"llni.h\"");
pw.println("#include \"jni.h\"" + lineSep);
forwardDecls(pw, clazz);
structSectionForClass(pw, clazz, cname);
methodSectionForClass(pw, clazz, cname);
pw.println("#endif");
}
protected void genHandleType(PrintWriter pw, String clazzname) {
String cname = mangleClassName(clazzname);
if (!doneHandleTypes.contains(cname)) {
doneHandleTypes.add(cname);
if (pw != null) {
pw.println("#ifndef DEFINED_" + cname);
pw.println(" #define DEFINED_" + cname);
pw.println(" GEN_HANDLE_TYPES(" + cname + ");");
pw.println("#endif" + lineSep);
}
}
}
protected String mangleClassName(String s) {
return s.replace('.', '_')
.replace('/', '_')
.replace(innerDelim, '_');
}
protected void forwardDecls(PrintWriter pw, TypeElement clazz)
throws TypeSignature.SignatureException {
TypeElement object = elems.getTypeElement("java.lang.Object");
if (clazz.equals(object))
return;
genHandleType(pw, clazz.getQualifiedName().toString());
TypeElement superClass = (TypeElement) (types.asElement(clazz.getSuperclass()));
if (superClass != null) {
String superClassName = superClass.getQualifiedName().toString();
forwardDecls(pw, superClass);
}
for (VariableElement field: fields) {
if (!field.getModifiers().contains(Modifier.STATIC)) {
TypeMirror t = types.erasure(field.asType());
TypeSignature newTypeSig = new TypeSignature(elems);
String tname = newTypeSig.qualifiedTypeName(t);
String sig = newTypeSig.getTypeSignature(tname);
if (sig.charAt(0) != '[')
forwardDeclsFromSig(pw, sig);
}
}
for (ExecutableElement method: methods) {
if (method.getModifiers().contains(Modifier.NATIVE)) {
TypeMirror retType = types.erasure(method.getReturnType());
String typesig = signature(method);
TypeSignature newTypeSig = new TypeSignature(elems);
String sig = newTypeSig.getTypeSignature(typesig, retType);
if (sig.charAt(0) != '[')
forwardDeclsFromSig(pw, sig);
}
}
}
protected void forwardDeclsFromSig(PrintWriter pw, String sig) {
int len = sig.length();
int i = sig.charAt(0) == '(' ? 1 : 0;
/* Skip the initial "(". */
while (i < len) {
if (sig.charAt(i) == 'L') {
int j = i + 1;
while (sig.charAt(j) != ';') j++;
genHandleType(pw, sig.substring(i + 1, j));
i = j + 1;
} else {
i++;
}
}
}
protected void structSectionForClass(PrintWriter pw,
TypeElement jclazz, String cname) {
String jname = jclazz.getQualifiedName().toString();
if (cname.equals("java_lang_Object")) {
pw.println("/* struct java_lang_Object is defined in typedefs.h. */");
pw.println();
return;
}
pw.println("#if !defined(__i386)");
pw.println("#pragma pack(4)");
pw.println("#endif");
pw.println();
pw.println("struct " + cname + " {");
pw.println(" ObjHeader h;");
pw.print(fieldDefs(jclazz, cname));
if (jname.equals("java.lang.Class"))
pw.println(" Class *LLNI_mask(cClass);" +
" /* Fake field; don't access (see oobj.h) */");
pw.println("};" + lineSep + lineSep + "#pragma pack()");
pw.println();
return;
}
private static class FieldDefsRes {
public String className; /* Name of the current class. */
public FieldDefsRes parent;
public String s;
public int byteSize;
public boolean bottomMost;
public boolean printedOne = false;
FieldDefsRes(TypeElement clazz, FieldDefsRes parent, boolean bottomMost) {
this.className = clazz.getQualifiedName().toString();
this.parent = parent;
this.bottomMost = bottomMost;
int byteSize = 0;
if (parent == null) this.s = "";
else this.s = parent.s;
}
}
/* Returns "true" iff added a field. */
private boolean doField(FieldDefsRes res, VariableElement field,
String cname, boolean padWord) {
String fieldDef = addStructMember(field, cname, padWord);
if (fieldDef != null) {
if (!res.printedOne) { /* add separator */
if (res.bottomMost) {
if (res.s.length() != 0)
res.s = res.s + " /* local members: */" + lineSep;
} else {
res.s = res.s + " /* inherited members from " +
res.className + ": */" + lineSep;
}
res.printedOne = true;
}
res.s = res.s + fieldDef;
return true;
}
// Otherwise.
return false;
}
private int doTwoWordFields(FieldDefsRes res, TypeElement clazz,
int offset, String cname, boolean padWord) {
boolean first = true;
List<VariableElement> fields = ElementFilter.fieldsIn(clazz.getEnclosedElements());
for (VariableElement field: fields) {
TypeKind tk = field.asType().getKind();
boolean twoWords = (tk == TypeKind.LONG || tk == TypeKind.DOUBLE);
if (twoWords && doField(res, field, cname, first && padWord)) {
offset += 8; first = false;
}
}
return offset;
}
String fieldDefs(TypeElement clazz, String cname) {
FieldDefsRes res = fieldDefs(clazz, cname, true);
return res.s;
}
FieldDefsRes fieldDefs(TypeElement clazz, String cname,
boolean bottomMost){
FieldDefsRes res;
int offset;
boolean didTwoWordFields = false;
TypeElement superclazz = (TypeElement) types.asElement(clazz.getSuperclass());
if (superclazz != null) {
String supername = superclazz.getQualifiedName().toString();
res = new FieldDefsRes(clazz,
fieldDefs(superclazz, cname, false),
bottomMost);
offset = res.parent.byteSize;
} else {
res = new FieldDefsRes(clazz, null, bottomMost);
offset = 0;
}
List<VariableElement> fields = ElementFilter.fieldsIn(clazz.getEnclosedElements());
for (VariableElement field: fields) {
if (doubleAlign && !didTwoWordFields && (offset % 8) == 0) {
offset = doTwoWordFields(res, clazz, offset, cname, false);
didTwoWordFields = true;
}
TypeKind tk = field.asType().getKind();
boolean twoWords = (tk == TypeKind.LONG || tk == TypeKind.DOUBLE);
if (!doubleAlign || !twoWords) {
if (doField(res, field, cname, false)) offset += 4;
}
}
if (doubleAlign && !didTwoWordFields) {
if ((offset % 8) != 0) offset += 4;
offset = doTwoWordFields(res, clazz, offset, cname, true);
}
res.byteSize = offset;
return res;
}
/* OVERRIDE: This method handles instance fields */
protected String addStructMember(VariableElement member, String cname,
boolean padWord) {
String res = null;
if (member.getModifiers().contains(Modifier.STATIC)) {
res = addStaticStructMember(member, cname);
// if (res == null) /* JNI didn't handle it, print comment. */
// res = " /* Inaccessible static: " + member + " */" + lineSep;
} else {
TypeMirror mt = types.erasure(member.asType());
if (padWord) res = " java_int padWord" + padFieldNum++ + ";" + lineSep;
res = " " + llniType(mt, false, false) + " " + llniFieldName(member);
if (isLongOrDouble(mt)) res = res + "[2]";
res = res + ";" + lineSep;
}
return res;
}
static private final boolean isWindows =
System.getProperty("os.name").startsWith("Windows");
/*
* This method only handles static final fields.
*/
protected String addStaticStructMember(VariableElement field, String cname) {
String res = null;
Object exp = null;
if (!field.getModifiers().contains(Modifier.STATIC))
return res;
if (!field.getModifiers().contains(Modifier.FINAL))
return res;
exp = field.getConstantValue();
if (exp != null) {
/* Constant. */
String cn = cname + "_" + field.getSimpleName();
String suffix = null;
long val = 0;
/* Can only handle int, long, float, and double fields. */
if (exp instanceof Byte
|| exp instanceof Short
|| exp instanceof Integer) {
suffix = "L";
val = ((Number)exp).intValue();
}
else if (exp instanceof Long) {
// Visual C++ supports the i64 suffix, not LL
suffix = isWindows ? "i64" : "LL";
val = ((Long)exp).longValue();
}
else if (exp instanceof Float) suffix = "f";
else if (exp instanceof Double) suffix = "";
else if (exp instanceof Character) {
suffix = "L";
Character ch = (Character) exp;
val = ((int) ch) & 0xffff;
}
if (suffix != null) {
// Some compilers will generate a spurious warning
// for the integer constants for Integer.MIN_VALUE
// and Long.MIN_VALUE so we handle them specially.
if ((suffix.equals("L") && (val == Integer.MIN_VALUE)) ||
(suffix.equals("LL") && (val == Long.MIN_VALUE))) {
res = " #undef " + cn + lineSep
+ " #define " + cn
+ " (" + (val + 1) + suffix + "-1)" + lineSep;
} else if (suffix.equals("L") || suffix.endsWith("LL")) {
res = " #undef " + cn + lineSep
+ " #define " + cn + " " + val + suffix + lineSep;
} else {
res = " #undef " + cn + lineSep
+ " #define " + cn + " " + exp + suffix + lineSep;
}
}
}
return res;
}
protected void methodSectionForClass(PrintWriter pw,
TypeElement clazz, String cname)
throws TypeSignature.SignatureException, Util.Exit {
String methods = methodDecls(clazz, cname);
if (methods.length() != 0) {
pw.println("/* Native method declarations: */" + lineSep);
pw.println("#ifdef __cplusplus");
pw.println("extern \"C\" {");
pw.println("#endif" + lineSep);
pw.println(methods);
pw.println("#ifdef __cplusplus");
pw.println("}");
pw.println("#endif");
}
}
protected String methodDecls(TypeElement clazz, String cname)
throws TypeSignature.SignatureException, Util.Exit {
String res = "";
for (ExecutableElement method: methods) {
if (method.getModifiers().contains(Modifier.NATIVE))
res = res + methodDecl(method, clazz, cname);
}
return res;
}
protected String methodDecl(ExecutableElement method,
TypeElement clazz, String cname)
throws TypeSignature.SignatureException, Util.Exit {
String res = null;
TypeMirror retType = types.erasure(method.getReturnType());
String typesig = signature(method);
TypeSignature newTypeSig = new TypeSignature(elems);
String sig = newTypeSig.getTypeSignature(typesig, retType);
boolean longName = needLongName(method, clazz);
if (sig.charAt(0) != '(')
util.error("invalid.method.signature", sig);
res = "JNIEXPORT " + jniType(retType) + " JNICALL" + lineSep + jniMethodName(method, cname, longName)
+ "(JNIEnv *, " + cRcvrDecl(method, cname);
List<? extends VariableElement> params = method.getParameters();
List<TypeMirror> argTypes = new ArrayList<TypeMirror>();
for (VariableElement p: params){
argTypes.add(types.erasure(p.asType()));
}
/* It would have been nice to include the argument names in the
declaration, but there seems to be a bug in the "BinaryField"
class, causing the getArguments() method to return "null" for
most (non-constructor) methods. */
for (TypeMirror argType: argTypes)
res = res + ", " + jniType(argType);
res = res + ");" + lineSep;
return res;
}
protected final boolean needLongName(ExecutableElement method,
TypeElement clazz) {
Name methodName = method.getSimpleName();
for (ExecutableElement memberMethod: methods) {
if ((memberMethod != method) &&
memberMethod.getModifiers().contains(Modifier.NATIVE) &&
(methodName.equals(memberMethod.getSimpleName())))
return true;
}
return false;
}
protected final String jniMethodName(ExecutableElement method, String cname,
boolean longName)
throws TypeSignature.SignatureException {
String res = "Java_" + cname + "_" + method.getSimpleName();
if (longName) {
TypeMirror mType = types.erasure(method.getReturnType());
List<? extends VariableElement> params = method.getParameters();
List<TypeMirror> argTypes = new ArrayList<TypeMirror>();
for (VariableElement param: params) {
argTypes.add(types.erasure(param.asType()));
}
res = res + "__";
for (TypeMirror t: argTypes) {
String tname = t.toString();
TypeSignature newTypeSig = new TypeSignature(elems);
String sig = newTypeSig.getTypeSignature(tname);
res = res + nameToIdentifier(sig);
}
}
return res;
}
// copied from JNI.java
protected final String jniType(TypeMirror t) throws Util.Exit {
TypeElement throwable = elems.getTypeElement("java.lang.Throwable");
TypeElement jClass = elems.getTypeElement("java.lang.Class");
TypeElement jString = elems.getTypeElement("java.lang.String");
Element tclassDoc = types.asElement(t);
switch (t.getKind()) {
case ARRAY: {
TypeMirror ct = ((ArrayType) t).getComponentType();
switch (ct.getKind()) {
case BOOLEAN: return "jbooleanArray";
case BYTE: return "jbyteArray";
case CHAR: return "jcharArray";
case SHORT: return "jshortArray";
case INT: return "jintArray";
case LONG: return "jlongArray";
case FLOAT: return "jfloatArray";
case DOUBLE: return "jdoubleArray";
case ARRAY:
case DECLARED: return "jobjectArray";
default: throw new Error(ct.toString());
}
}
case VOID: return "void";
case BOOLEAN: return "jboolean";
case BYTE: return "jbyte";
case CHAR: return "jchar";
case SHORT: return "jshort";
case INT: return "jint";
case LONG: return "jlong";
case FLOAT: return "jfloat";
case DOUBLE: return "jdouble";
case DECLARED: {
if (tclassDoc.equals(jString))
return "jstring";
else if (types.isAssignable(t, throwable.asType()))
return "jthrowable";
else if (types.isAssignable(t, jClass.asType()))
return "jclass";
else
return "jobject";
}
}
util.bug("jni.unknown.type");
return null; /* dead code. */
}
protected String llniType(TypeMirror t, boolean handleize, boolean longDoubleOK) {
String res = null;
switch (t.getKind()) {
case ARRAY: {
TypeMirror ct = ((ArrayType) t).getComponentType();
switch (ct.getKind()) {
case BOOLEAN: res = "IArrayOfBoolean"; break;
case BYTE: res = "IArrayOfByte"; break;
case CHAR: res = "IArrayOfChar"; break;
case SHORT: res = "IArrayOfShort"; break;
case INT: res = "IArrayOfInt"; break;
case LONG: res = "IArrayOfLong"; break;
case FLOAT: res = "IArrayOfFloat"; break;
case DOUBLE: res = "IArrayOfDouble"; break;
case ARRAY:
case DECLARED: res = "IArrayOfRef"; break;
default: throw new Error(ct.getKind() + " " + ct);
}
if (!handleize) res = "DEREFERENCED_" + res;
break;
}
case VOID:
res = "void";
break;
case BOOLEAN:
case BYTE:
case CHAR:
case SHORT:
case INT:
res = "java_int" ;
break;
case LONG:
res = longDoubleOK ? "java_long" : "val32 /* java_long */";
break;
case FLOAT:
res = "java_float";
break;
case DOUBLE:
res = longDoubleOK ? "java_double" : "val32 /* java_double */";
break;
case DECLARED:
TypeElement e = (TypeElement) types.asElement(t);
res = "I" + mangleClassName(e.getQualifiedName().toString());
if (!handleize) res = "DEREFERENCED_" + res;
break;
default:
throw new Error(t.getKind() + " " + t); // FIXME
}
return res;
}
protected final String cRcvrDecl(Element field, String cname) {
return (field.getModifiers().contains(Modifier.STATIC) ? "jclass" : "jobject");
}
protected String maskName(String s) {
return "LLNI_mask(" + s + ")";
}
protected String llniFieldName(VariableElement field) {
return maskName(field.getSimpleName().toString());
}
protected final boolean isLongOrDouble(TypeMirror t) {
TypeVisitor<Boolean,Void> v = new SimpleTypeVisitor7<Boolean,Void>() {
public Boolean defaultAction(TypeMirror t, Void p){
return false;
}
public Boolean visitArray(ArrayType t, Void p) {
return visit(t.getComponentType(), p);
}
public Boolean visitPrimitive(PrimitiveType t, Void p) {
TypeKind tk = t.getKind();
return (tk == TypeKind.LONG || tk == TypeKind.DOUBLE);
}
};
return v.visit(t, null);
}
/* Do unicode to ansi C identifier conversion.
%%% This may not be right, but should be called more often. */
protected final String nameToIdentifier(String name) {
int len = name.length();
StringBuffer buf = new StringBuffer(len);
for (int i = 0; i < len; i++) {
char c = name.charAt(i);
if (isASCIILetterOrDigit(c))
buf.append(c);
else if (c == '/')
buf.append('_');
else if (c == '.')
buf.append('_');
else if (c == '_')
buf.append("_1");
else if (c == ';')
buf.append("_2");
else if (c == '[')
buf.append("_3");
else
buf.append("_0" + ((int)c));
}
return new String(buf);
}
protected final boolean isASCIILetterOrDigit(char c) {
if (((c >= 'A') && (c <= 'Z')) ||
((c >= 'a') && (c <= 'z')) ||
((c >= '0') && (c <= '9')))
return true;
else
return false;
}
}
| 25,598 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Gen.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/Gen.java | /*
* Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
/**
* An abstraction for generating support files required by native methods.
* Subclasses are for specific native interfaces. At the time of its
* original writing, this interface is rich enough to support JNI and the
* old 1.0-style native method interface.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar(Revised)
*/
public abstract class Gen {
protected String lineSep = System.getProperty("line.separator");
protected ProcessingEnvironment processingEnvironment;
protected Types types;
protected Elements elems;
protected Mangle mangler;
protected Util util;
protected Gen(Util util) {
this.util = util;
}
/*
* List of classes for which we must generate output.
*/
protected Set<TypeElement> classes;
static private final boolean isWindows =
System.getProperty("os.name").startsWith("Windows");
/**
* Override this abstract method, generating content for the named
* class into the outputstream.
*/
protected abstract void write(OutputStream o, TypeElement clazz) throws Util.Exit;
/**
* Override this method to provide a list of #include statements
* required by the native interface.
*/
protected abstract String getIncludes();
/*
* Output location.
*/
protected JavaFileManager fileManager;
protected JavaFileObject outFile;
public void setFileManager(JavaFileManager fm) {
fileManager = fm;
}
public void setOutFile(JavaFileObject outFile) {
this.outFile = outFile;
}
public void setClasses(Set<TypeElement> classes) {
this.classes = classes;
}
void setProcessingEnvironment(ProcessingEnvironment pEnv) {
processingEnvironment = pEnv;
elems = pEnv.getElementUtils();
types = pEnv.getTypeUtils();
mangler = new Mangle(elems, types);
}
/*
* Smartness with generated files.
*/
protected boolean force = false;
public void setForce(boolean state) {
force = state;
}
/**
* We explicitly need to write ASCII files because that is what C
* compilers understand.
*/
protected PrintWriter wrapWriter(OutputStream o) throws Util.Exit {
try {
return new PrintWriter(new OutputStreamWriter(o, "ISO8859_1"), true);
} catch (UnsupportedEncodingException use) {
util.bug("encoding.iso8859_1.not.found");
return null; /* dead code */
}
}
/**
* After initializing state of an instance, use this method to start
* processing.
*
* Buffer size chosen as an approximation from a single sampling of:
* expr `du -sk` / `ls *.h | wc -l`
*/
public void run() throws IOException, ClassNotFoundException, Util.Exit {
int i = 0;
if (outFile != null) {
/* Everything goes to one big file... */
ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
writeFileTop(bout); /* only once */
for (TypeElement t: classes) {
write(bout, t);
}
writeIfChanged(bout.toByteArray(), outFile);
} else {
/* Each class goes to its own file... */
for (TypeElement t: classes) {
ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
writeFileTop(bout);
write(bout, t);
writeIfChanged(bout.toByteArray(), getFileObject(t.getQualifiedName()));
}
}
}
/*
* Write the contents of byte[] b to a file named file. Writing
* is done if either the file doesn't exist or if the contents are
* different.
*/
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
boolean mustWrite = false;
String event = "[No need to update file ";
if (force) {
mustWrite = true;
event = "[Forcefully writing file ";
} else {
InputStream in;
byte[] a;
try {
// regrettably, there's no API to get the length in bytes
// for a FileObject, so we can't short-circuit reading the
// file here
in = file.openInputStream();
a = readBytes(in);
if (!Arrays.equals(a, b)) {
mustWrite = true;
event = "[Overwriting file ";
}
} catch (FileNotFoundException e) {
mustWrite = true;
event = "[Creating file ";
}
}
if (util.verbose)
util.log(event + file + "]");
if (mustWrite) {
OutputStream out = file.openOutputStream();
out.write(b); /* No buffering, just one big write! */
out.close();
}
}
protected byte[] readBytes(InputStream in) throws IOException {
try {
byte[] array = new byte[in.available() + 1];
int offset = 0;
int n;
while ((n = in.read(array, offset, array.length - offset)) != -1) {
offset += n;
if (offset == array.length)
array = Arrays.copyOf(array, array.length * 2);
}
return Arrays.copyOf(array, offset);
} finally {
in.close();
}
}
protected String defineForStatic(TypeElement c, VariableElement f)
throws Util.Exit {
CharSequence cnamedoc = c.getQualifiedName();
CharSequence fnamedoc = f.getSimpleName();
String cname = mangler.mangle(cnamedoc, Mangle.Type.CLASS);
String fname = mangler.mangle(fnamedoc, Mangle.Type.FIELDSTUB);
if (!f.getModifiers().contains(Modifier.STATIC))
util.bug("tried.to.define.non.static");
if (f.getModifiers().contains(Modifier.FINAL)) {
Object value = null;
value = f.getConstantValue();
if (value != null) { /* so it is a ConstantExpression */
String constString = null;
if ((value instanceof Integer)
|| (value instanceof Byte)
|| (value instanceof Short)) {
/* covers byte, short, int */
constString = value.toString() + "L";
} else if (value instanceof Boolean) {
constString = ((Boolean) value) ? "1L" : "0L";
} else if (value instanceof Character) {
Character ch = (Character) value;
constString = String.valueOf(((int) ch) & 0xffff) + "L";
} else if (value instanceof Long) {
// Visual C++ supports the i64 suffix, not LL.
if (isWindows)
constString = value.toString() + "i64";
else
constString = value.toString() + "LL";
} else if (value instanceof Float) {
/* bug for bug */
float fv = ((Float)value).floatValue();
if (Float.isInfinite(fv))
constString = ((fv < 0) ? "-" : "") + "Inff";
else
constString = value.toString() + "f";
} else if (value instanceof Double) {
/* bug for bug */
double d = ((Double)value).doubleValue();
if (Double.isInfinite(d))
constString = ((d < 0) ? "-" : "") + "InfD";
else
constString = value.toString();
}
if (constString != null) {
StringBuffer s = new StringBuffer("#undef ");
s.append(cname); s.append("_"); s.append(fname); s.append(lineSep);
s.append("#define "); s.append(cname); s.append("_");
s.append(fname); s.append(" "); s.append(constString);
return s.toString();
}
}
}
return null;
}
/*
* Deal with the C pre-processor.
*/
protected String cppGuardBegin() {
return "#ifdef __cplusplus" + lineSep + "extern \"C\" {" + lineSep + "#endif";
}
protected String cppGuardEnd() {
return "#ifdef __cplusplus" + lineSep + "}" + lineSep + "#endif";
}
protected String guardBegin(String cname) {
return "/* Header for class " + cname + " */" + lineSep + lineSep +
"#ifndef _Included_" + cname + lineSep +
"#define _Included_" + cname;
}
protected String guardEnd(String cname) {
return "#endif";
}
/*
* File name and file preamble related operations.
*/
protected void writeFileTop(OutputStream o) throws Util.Exit {
PrintWriter pw = wrapWriter(o);
pw.println("/* DO NOT EDIT THIS FILE - it is machine generated */" + lineSep +
getIncludes());
}
protected String baseFileName(CharSequence className) {
return mangler.mangle(className, Mangle.Type.CLASS);
}
protected FileObject getFileObject(CharSequence className) throws IOException {
String name = baseFileName(className) + getFileSuffix();
return fileManager.getFileForOutput(StandardLocation.SOURCE_OUTPUT, "", name, null);
}
protected String getFileSuffix() {
return ".h";
}
/**
* Including super classes' fields.
*/
List<VariableElement> getAllFields(TypeElement subclazz) {
List<VariableElement> fields = new ArrayList<VariableElement>();
TypeElement cd = null;
Stack<TypeElement> s = new Stack<TypeElement>();
cd = subclazz;
while (true) {
s.push(cd);
TypeElement c = (TypeElement) (types.asElement(cd.getSuperclass()));
if (c == null)
break;
cd = c;
}
while (!s.empty()) {
cd = s.pop();
fields.addAll(ElementFilter.fieldsIn(cd.getEnclosedElements()));
}
return fields;
}
// c.f. MethodDoc.signature
String signature(ExecutableElement e) {
StringBuffer sb = new StringBuffer("(");
String sep = "";
for (VariableElement p: e.getParameters()) {
sb.append(sep);
sb.append(types.erasure(p.asType()).toString());
sep = ",";
}
sb.append(")");
return sb.toString();
}
}
| 12,978 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
NativeHeaderTool.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/NativeHeaderTool.java | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah; //javax.tools;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.Callable;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.OptionChecker;
import javax.tools.StandardJavaFileManager;
import javax.tools.Tool;
/**
* This class is intended to be put in javax.tools.
*
* @see DiagnosticListener
* @see Diagnostic
* @see JavaFileManager
* @since 1.7
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public interface NativeHeaderTool extends Tool, OptionChecker {
/**
* Creates a future for a native header task with the given
* components and arguments. The task might not have
* completed as described in the NativeHeaderTask interface.
*
* <p>If a file manager is provided, it must be able to handle all
* locations defined in {@link StandardLocation}.
*
* @param out a Writer for additional output from the task;
* use {@code System.err} if {@code null}
* @param fileManager a file manager; if {@code null} use the
* task's standard filemanager
* @param diagnosticListener a diagnostic listener; if {@code
* null} use the compiler's default method for reporting
* diagnostics
* @param options task options, {@code null} means no options
* @param classes class names for which native headers should be generated
* @return an object representing the task to be done
* @throws RuntimeException if an unrecoverable error
* occurred in a user supplied component. The
* {@linkplain Throwable#getCause() cause} will be the error in
* user code.
* @throws IllegalArgumentException if any of the given
* compilation units are of other kind than
* {@linkplain JavaFileObject.Kind#SOURCE source}
*/
NativeHeaderTask getTask(Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes);
/**
* Gets a new instance of the standard file manager implementation
* for this tool. The file manager will use the given diagnostic
* listener for producing any non-fatal diagnostics. Fatal errors
* will be signalled with the appropriate exceptions.
*
* <p>The standard file manager will be automatically reopened if
* it is accessed after calls to {@code flush} or {@code close}.
* The standard file manager must be usable with other tools.
*
* @param diagnosticListener a diagnostic listener for non-fatal
* diagnostics; if {@code null} use the tool's default method
* for reporting diagnostics
* @param locale the locale to apply when formatting diagnostics;
* {@code null} means the {@linkplain Locale#getDefault() default locale}.
* @param charset the character set used for decoding bytes; if
* {@code null} use the platform default
* @return the standard file manager
*/
StandardJavaFileManager getStandardFileManager(
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale,
Charset charset);
/**
* Interface representing a future for a native header task. The
* task has not yet started. To start the task, call
* the {@linkplain #call call} method.
*
* <p>Before calling the call method, additional aspects of the
* task can be configured, for example, by calling the
* {@linkplain #setLocale setLocale} method.
*/
interface NativeHeaderTask extends Callable<Boolean> {
/**
* Set the locale to be applied when formatting diagnostics and
* other localized data.
*
* @param locale the locale to apply; {@code null} means apply no
* locale
* @throws IllegalStateException if the task has started
*/
void setLocale(Locale locale);
/**
* Performs this native header task. The task may only
* be performed once. Subsequent calls to this method throw
* IllegalStateException.
*
* @return true if and only all the files were processed without errors;
* false otherwise
*
* @throws RuntimeException if an unrecoverable error occurred
* in a user-supplied component. The
* {@linkplain Throwable#getCause() cause} will be the error
* in user code.
* @throws IllegalStateException if called more than once
*/
Boolean call();
}
}
| 6,132 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavahFileManager.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/JavahFileManager.java | /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
/**
* javah's implementation of JavaFileManager.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
class JavahFileManager extends JavacFileManager {
private JavahFileManager(Context context, Charset charset) {
super(context, true, charset);
setIgnoreSymbolFile(true);
}
static JavahFileManager create(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
Context javac_context = new Context();
if (dl != null)
javac_context.put(DiagnosticListener.class, dl);
javac_context.put(com.sun.tools.javac.util.Log.outKey, log);
return new JavahFileManager(javac_context, null);
}
void setIgnoreSymbolFile(boolean b) {
ignoreSymbolFile = b;
}
}
| 2,396 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
InternalError.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/InternalError.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class InternalError extends Error {
private static final long serialVersionUID = 8411861562497165022L;
InternalError(String msg, Throwable cause) {
super("Internal error: " + msg);
initCause(cause);
}
}
| 1,711 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Main.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/Main.java | /*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.PrintWriter;
/**
* Main entry point.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Main {
/**
* Main entry point for the launcher.
* Note: This method calls System.exit.
* @param args command line arguments
*/
public static void main(String[] args) {
JavahTask t = new JavahTask();
int rc = t.run(args);
System.exit(rc);
}
/**
* Entry point that does <i>not</i> call System.exit.
* @param args command line arguments
* @param out output stream
* @return an exit code. 0 means success, non-zero means an error occurred.
*/
public static int run(String[] args, PrintWriter out) {
JavahTask t = new JavahTask();
t.setLog(out);
return t.run(args);
}
}
| 2,223 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeSignature.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/TypeSignature.java | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.util.*;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.TypeVisitor;
import javax.lang.model.util.Elements;
import javax.lang.model.util.SimpleTypeVisitor7;
/**
* Returns internal type signature.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar
*/
public class TypeSignature {
static class SignatureException extends Exception {
private static final long serialVersionUID = 1L;
SignatureException(String reason) {
super(reason);
}
}
Elements elems;
/* Signature Characters */
private static final String SIG_VOID = "V";
private static final String SIG_BOOLEAN = "Z";
private static final String SIG_BYTE = "B";
private static final String SIG_CHAR = "C";
private static final String SIG_SHORT = "S";
private static final String SIG_INT = "I";
private static final String SIG_LONG = "J";
private static final String SIG_FLOAT = "F";
private static final String SIG_DOUBLE = "D";
private static final String SIG_ARRAY = "[";
private static final String SIG_CLASS = "L";
public TypeSignature(Elements elems){
this.elems = elems;
}
/*
* Returns the type signature of a field according to JVM specs
*/
public String getTypeSignature(String javasignature) throws SignatureException {
return getParamJVMSignature(javasignature);
}
/*
* Returns the type signature of a method according to JVM specs
*/
public String getTypeSignature(String javasignature, TypeMirror returnType)
throws SignatureException {
String signature = null; //Java type signature.
String typeSignature = null; //Internal type signature.
List<String> params = new ArrayList<String>(); //List of parameters.
String paramsig = null; //Java parameter signature.
String paramJVMSig = null; //Internal parameter signature.
String returnSig = null; //Java return type signature.
String returnJVMType = null; //Internal return type signature.
int dimensions = 0; //Array dimension.
int startIndex = -1;
int endIndex = -1;
StringTokenizer st = null;
int i = 0;
// Gets the actual java signature without parentheses.
if (javasignature != null) {
startIndex = javasignature.indexOf("(");
endIndex = javasignature.indexOf(")");
}
if (((startIndex != -1) && (endIndex != -1))
&&(startIndex+1 < javasignature.length())
&&(endIndex < javasignature.length())) {
signature = javasignature.substring(startIndex+1, endIndex);
}
// Separates parameters.
if (signature != null) {
if (signature.indexOf(",") != -1) {
st = new StringTokenizer(signature, ",");
if (st != null) {
while (st.hasMoreTokens()) {
params.add(st.nextToken());
}
}
} else {
params.add(signature);
}
}
/* JVM type signature. */
typeSignature = "(";
// Gets indivisual internal parameter signature.
while (params.isEmpty() != true) {
paramsig = params.remove(i).trim();
paramJVMSig = getParamJVMSignature(paramsig);
if (paramJVMSig != null) {
typeSignature += paramJVMSig;
}
}
typeSignature += ")";
// Get internal return type signature.
returnJVMType = "";
if (returnType != null) {
dimensions = dimensions(returnType);
}
//Gets array dimension of return type.
while (dimensions-- > 0) {
returnJVMType += "[";
}
if (returnType != null) {
returnSig = qualifiedTypeName(returnType);
returnJVMType += getComponentType(returnSig);
} else {
System.out.println("Invalid return type.");
}
typeSignature += returnJVMType;
return typeSignature;
}
/*
* Returns internal signature of a parameter.
*/
private String getParamJVMSignature(String paramsig) throws SignatureException {
String paramJVMSig = "";
String componentType ="";
if(paramsig != null){
if(paramsig.indexOf("[]") != -1) {
// Gets array dimension.
int endindex = paramsig.indexOf("[]");
componentType = paramsig.substring(0, endindex);
String dimensionString = paramsig.substring(endindex);
if(dimensionString != null){
while(dimensionString.indexOf("[]") != -1){
paramJVMSig += "[";
int beginindex = dimensionString.indexOf("]") + 1;
if(beginindex < dimensionString.length()){
dimensionString = dimensionString.substring(beginindex);
}else
dimensionString = "";
}
}
} else componentType = paramsig;
paramJVMSig += getComponentType(componentType);
}
return paramJVMSig;
}
/*
* Returns internal signature of a component.
*/
private String getComponentType(String componentType) throws SignatureException {
String JVMSig = "";
if(componentType != null){
if(componentType.equals("void")) JVMSig += SIG_VOID ;
else if(componentType.equals("boolean")) JVMSig += SIG_BOOLEAN ;
else if(componentType.equals("byte")) JVMSig += SIG_BYTE ;
else if(componentType.equals("char")) JVMSig += SIG_CHAR ;
else if(componentType.equals("short")) JVMSig += SIG_SHORT ;
else if(componentType.equals("int")) JVMSig += SIG_INT ;
else if(componentType.equals("long")) JVMSig += SIG_LONG ;
else if(componentType.equals("float")) JVMSig += SIG_FLOAT ;
else if(componentType.equals("double")) JVMSig += SIG_DOUBLE ;
else {
if(!componentType.equals("")){
TypeElement classNameDoc = elems.getTypeElement(componentType);
if(classNameDoc == null){
throw new SignatureException(componentType);
}else {
String classname = classNameDoc.getQualifiedName().toString();
String newclassname = classname.replace('.', '/');
JVMSig += "L";
JVMSig += newclassname;
JVMSig += ";";
}
}
}
}
return JVMSig;
}
int dimensions(TypeMirror t) {
if (t.getKind() != TypeKind.ARRAY)
return 0;
return 1 + dimensions(((ArrayType) t).getComponentType());
}
String qualifiedTypeName(TypeMirror type) {
TypeVisitor<Name, Void> v = new SimpleTypeVisitor7<Name, Void>() {
@Override
public Name visitArray(ArrayType t, Void p) {
return t.getComponentType().accept(this, p);
}
@Override
public Name visitDeclared(DeclaredType t, Void p) {
return ((TypeElement) t.asElement()).getQualifiedName();
}
@Override
public Name visitPrimitive(PrimitiveType t, Void p) {
return elems.getName(t.toString());
}
@Override
public Name visitNoType(NoType t, Void p) {
if (t.getKind() == TypeKind.VOID)
return elems.getName("void");
return defaultAction(t, p);
}
@Override
public Name visitTypeVariable(TypeVariable t, Void p) {
return t.getUpperBound().accept(this, p);
}
};
return v.visit(type).toString();
}
}
| 10,079 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Util.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/Util.java | /*
* Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
/**
* Messages, verbose and error handling support.
*
* For errors, the failure modes are:
* error -- User did something wrong
* bug -- Bug has occurred in javah
* fatal -- We can't even find resources, so bail fast, don't localize
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class Util {
/** Exit is used to replace the use of System.exit in the original javah.
*/
public static class Exit extends Error {
private static final long serialVersionUID = 430820978114067221L;
Exit(int exitValue) {
this(exitValue, null);
}
Exit(int exitValue, Throwable cause) {
super(cause);
this.exitValue = exitValue;
this.cause = cause;
}
Exit(Exit e) {
this(e.exitValue, e.cause);
}
public final int exitValue;
public final Throwable cause;
}
/*
* Help for verbosity.
*/
public boolean verbose = false;
public PrintWriter log;
public DiagnosticListener<? super JavaFileObject> dl;
Util(PrintWriter log, DiagnosticListener<? super JavaFileObject> dl) {
this.log = log;
this.dl = dl;
}
public void log(String s) {
log.println(s);
}
/*
* Help for loading localized messages.
*/
private ResourceBundle m;
private void initMessages() throws Exit {
try {
m = ResourceBundle.getBundle("com.sun.tools.javah.resources.l10n");
} catch (MissingResourceException mre) {
fatal("Error loading resources. Please file a bug report.", mre);
}
}
private String getText(String key, Object... args) throws Exit {
if (m == null)
initMessages();
try {
return MessageFormat.format(m.getString(key), args);
} catch (MissingResourceException e) {
fatal("Key " + key + " not found in resources.", e);
}
return null; /* dead code */
}
/*
* Usage message.
*/
public void usage() throws Exit {
log.println(getText("usage"));
}
public void version() throws Exit {
log.println(getText("javah.version",
System.getProperty("java.version"), null));
}
/*
* Failure modes.
*/
public void bug(String key) throws Exit {
bug(key, null);
}
public void bug(String key, Exception e) throws Exit {
dl.report(createDiagnostic(Diagnostic.Kind.ERROR, key));
dl.report(createDiagnostic(Diagnostic.Kind.NOTE, "bug.report"));
throw new Exit(11, e);
}
public void error(String key, Object... args) throws Exit {
dl.report(createDiagnostic(Diagnostic.Kind.ERROR, key, args));
throw new Exit(15);
}
private void fatal(String msg) throws Exit {
fatal(msg, null);
}
private void fatal(String msg, Exception e) throws Exit {
dl.report(createDiagnostic(Diagnostic.Kind.ERROR, "", msg));
throw new Exit(10, e);
}
private Diagnostic<JavaFileObject> createDiagnostic(
final Diagnostic.Kind kind, final String code, final Object... args) {
return new Diagnostic<JavaFileObject>() {
public String getCode() {
return code;
}
public long getColumnNumber() {
return Diagnostic.NOPOS;
}
public long getEndPosition() {
return Diagnostic.NOPOS;
}
public Kind getKind() {
return kind;
}
public long getLineNumber() {
return Diagnostic.NOPOS;
}
public String getMessage(Locale locale) {
if (code.length() == 0)
return (String) args[0];
return getText(code, args); // FIXME locale
}
public long getPosition() {
return Diagnostic.NOPOS;
}
public JavaFileObject getSource() {
return null;
}
public long getStartPosition() {
return Diagnostic.NOPOS;
}
};
}
}
| 5,966 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavahTask.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/JavahTask.java | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVisitor;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleTypeVisitor7;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import static javax.tools.Diagnostic.Kind.*;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.main.CommandLine;
/**
* Javah generates support files for native methods.
* Parse commandline options & Invokes javadoc to execute those commands.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar
* @author Jonathan Gibbons
*/
public class JavahTask implements NativeHeaderTool.NativeHeaderTask {
public class BadArgs extends Exception {
private static final long serialVersionUID = 1479361270874789045L;
BadArgs(String key, Object... args) {
super(JavahTask.this.getMessage(key, args));
this.key = key;
this.args = args;
}
BadArgs showUsage(boolean b) {
showUsage = b;
return this;
}
final String key;
final Object[] args;
boolean showUsage;
}
static abstract class Option {
Option(boolean hasArg, String... aliases) {
this.hasArg = hasArg;
this.aliases = aliases;
}
boolean isHidden() {
return false;
}
boolean matches(String opt) {
for (String a: aliases) {
if (a.equals(opt))
return true;
}
return false;
}
boolean ignoreRest() {
return false;
}
abstract void process(JavahTask task, String opt, String arg) throws BadArgs;
final boolean hasArg;
final String[] aliases;
}
static abstract class HiddenOption extends Option {
HiddenOption(boolean hasArg, String... aliases) {
super(hasArg, aliases);
}
@Override
boolean isHidden() {
return true;
}
}
static Option[] recognizedOptions = {
new Option(true, "-o") {
void process(JavahTask task, String opt, String arg) {
task.ofile = new File(arg);
}
},
new Option(true, "-d") {
void process(JavahTask task, String opt, String arg) {
task.odir = new File(arg);
}
},
new HiddenOption(true, "-td") {
void process(JavahTask task, String opt, String arg) {
// ignored; for backwards compatibility
}
},
new HiddenOption(false, "-stubs") {
void process(JavahTask task, String opt, String arg) {
// ignored; for backwards compatibility
}
},
new Option(false, "-v", "-verbose") {
void process(JavahTask task, String opt, String arg) {
task.verbose = true;
}
},
new Option(false, "-h", "-help", "--help", "-?") {
void process(JavahTask task, String opt, String arg) {
task.help = true;
}
},
new HiddenOption(false, "-trace") {
void process(JavahTask task, String opt, String arg) {
task.trace = true;
}
},
new Option(false, "-version") {
void process(JavahTask task, String opt, String arg) {
task.version = true;
}
},
new HiddenOption(false, "-fullversion") {
void process(JavahTask task, String opt, String arg) {
task.fullVersion = true;
}
},
new Option(false, "-jni") {
void process(JavahTask task, String opt, String arg) {
task.jni = true;
}
},
new Option(false, "-force") {
void process(JavahTask task, String opt, String arg) {
task.force = true;
}
},
new HiddenOption(false, "-Xnew") {
void process(JavahTask task, String opt, String arg) {
// we're already using the new javah
}
},
new HiddenOption(false, "-old") {
void process(JavahTask task, String opt, String arg) {
task.old = true;
}
},
new HiddenOption(false, "-llni", "-Xllni") {
void process(JavahTask task, String opt, String arg) {
task.llni = true;
}
},
new HiddenOption(false, "-llnidouble") {
void process(JavahTask task, String opt, String arg) {
task.llni = true;
task.doubleAlign = true;
}
},
new HiddenOption(false) {
boolean matches(String opt) {
return opt.startsWith("-XD");
}
void process(JavahTask task, String opt, String arg) {
task.javac_extras.add(opt);
}
},
};
JavahTask() {
}
JavahTask(Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes) {
this();
this.log = getPrintWriterForWriter(out);
this.fileManager = fileManager;
this.diagnosticListener = diagnosticListener;
try {
handleOptions(options, false);
} catch (BadArgs e) {
throw new IllegalArgumentException(e.getMessage());
}
this.classes = new ArrayList<String>();
if (classes != null) {
for (String classname: classes) {
classname.getClass(); // null-check
this.classes.add(classname);
}
}
}
public void setLocale(Locale locale) {
if (locale == null)
locale = Locale.getDefault();
task_locale = locale;
}
public void setLog(PrintWriter log) {
this.log = log;
}
public void setLog(OutputStream s) {
setLog(getPrintWriterForStream(s));
}
static PrintWriter getPrintWriterForStream(OutputStream s) {
return new PrintWriter(s, true);
}
static PrintWriter getPrintWriterForWriter(Writer w) {
if (w == null)
return getPrintWriterForStream(null);
else if (w instanceof PrintWriter)
return (PrintWriter) w;
else
return new PrintWriter(w, true);
}
public void setDiagnosticListener(DiagnosticListener<? super JavaFileObject> dl) {
diagnosticListener = dl;
}
public void setDiagnosticListener(OutputStream s) {
setDiagnosticListener(getDiagnosticListenerForStream(s));
}
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForStream(OutputStream s) {
return getDiagnosticListenerForWriter(getPrintWriterForStream(s));
}
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) {
final PrintWriter pw = getPrintWriterForWriter(w);
return new DiagnosticListener<JavaFileObject> () {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
pw.print(getMessage("err.prefix"));
pw.print(" ");
}
pw.println(diagnostic.getMessage(null));
}
};
}
int run(String[] args) {
try {
handleOptions(args);
boolean ok = run();
return ok ? 0 : 1;
} catch (BadArgs e) {
diagnosticListener.report(createDiagnostic(e.key, e.args));
return 1;
} catch (InternalError e) {
diagnosticListener.report(createDiagnostic("err.internal.error", e.getMessage()));
return 1;
} catch (Util.Exit e) {
return e.exitValue;
} finally {
log.flush();
}
}
public void handleOptions(String[] args) throws BadArgs {
handleOptions(Arrays.asList(args), true);
}
private void handleOptions(Iterable<String> args, boolean allowClasses) throws BadArgs {
if (log == null) {
log = getPrintWriterForStream(System.out);
if (diagnosticListener == null)
diagnosticListener = getDiagnosticListenerForStream(System.err);
} else {
if (diagnosticListener == null)
diagnosticListener = getDiagnosticListenerForWriter(log);
}
if (fileManager == null)
fileManager = getDefaultFileManager(diagnosticListener, log);
Iterator<String> iter = expandAtArgs(args).iterator();
noArgs = !iter.hasNext();
while (iter.hasNext()) {
String arg = iter.next();
if (arg.startsWith("-"))
handleOption(arg, iter);
else if (allowClasses) {
if (classes == null)
classes = new ArrayList<String>();
classes.add(arg);
while (iter.hasNext())
classes.add(iter.next());
} else
throw new BadArgs("err.unknown.option", arg).showUsage(true);
}
if ((classes == null || classes.size() == 0) &&
!(noArgs || help || version || fullVersion)) {
throw new BadArgs("err.no.classes.specified");
}
if (jni && llni)
throw new BadArgs("jni.llni.mixed");
if (odir != null && ofile != null)
throw new BadArgs("dir.file.mixed");
}
private void handleOption(String name, Iterator<String> rest) throws BadArgs {
for (Option o: recognizedOptions) {
if (o.matches(name)) {
if (o.hasArg) {
if (rest.hasNext())
o.process(this, name, rest.next());
else
throw new BadArgs("err.missing.arg", name).showUsage(true);
} else
o.process(this, name, null);
if (o.ignoreRest()) {
while (rest.hasNext())
rest.next();
}
return;
}
}
if (fileManager.handleOption(name, rest))
return;
throw new BadArgs("err.unknown.option", name).showUsage(true);
}
private Iterable<String> expandAtArgs(Iterable<String> args) throws BadArgs {
try {
List<String> l = new ArrayList<String>();
for (String arg: args) l.add(arg);
return Arrays.asList(CommandLine.parse(l.toArray(new String[l.size()])));
} catch (FileNotFoundException e) {
throw new BadArgs("at.args.file.not.found", e.getLocalizedMessage());
} catch (IOException e) {
throw new BadArgs("at.args.io.exception", e.getLocalizedMessage());
}
}
public Boolean call() {
return run();
}
public boolean run() throws Util.Exit {
Util util = new Util(log, diagnosticListener);
if (noArgs || help) {
showHelp();
return help; // treat noArgs as an error for purposes of exit code
}
if (version || fullVersion) {
showVersion(fullVersion);
return true;
}
util.verbose = verbose;
Gen g;
if (llni)
g = new LLNI(doubleAlign, util);
else {
// if (stubs)
// throw new BadArgs("jni.no.stubs");
g = new JNI(util);
}
if (ofile != null) {
if (!(fileManager instanceof StandardJavaFileManager)) {
diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-o"));
return false;
}
Iterable<? extends JavaFileObject> iter =
((StandardJavaFileManager) fileManager).getJavaFileObjectsFromFiles(Collections.singleton(ofile));
JavaFileObject fo = iter.iterator().next();
g.setOutFile(fo);
} else {
if (odir != null) {
if (!(fileManager instanceof StandardJavaFileManager)) {
diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-d"));
return false;
}
if (!odir.exists())
if (!odir.mkdirs())
util.error("cant.create.dir", odir.toString());
try {
((StandardJavaFileManager) fileManager).setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(odir));
} catch (IOException e) {
Object msg = e.getLocalizedMessage();
if (msg == null) {
msg = e;
}
diagnosticListener.report(createDiagnostic("err.ioerror", odir, msg));
return false;
}
}
g.setFileManager(fileManager);
}
/*
* Force set to false will turn off smarts about checking file
* content before writing.
*/
g.setForce(force);
if (fileManager instanceof JavahFileManager)
((JavahFileManager) fileManager).setIgnoreSymbolFile(true);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
List<String> opts = new ArrayList<String>();
opts.add("-proc:only");
opts.addAll(javac_extras);
CompilationTask t = c.getTask(log, fileManager, diagnosticListener, opts, internalize(classes), null);
JavahProcessor p = new JavahProcessor(g);
t.setProcessors(Collections.singleton(p));
boolean ok = t.call();
if (p.exit != null)
throw new Util.Exit(p.exit);
return ok;
}
private List<String> internalize(List<String> classes) {
List<String> l = new ArrayList<String>();
for (String c: classes) {
l.add(c.replace('$', '.'));
}
return l;
}
private List<File> pathToFiles(String path) {
List<File> files = new ArrayList<File>();
for (String f: path.split(File.pathSeparator)) {
if (f.length() > 0)
files.add(new File(f));
}
return files;
}
static StandardJavaFileManager getDefaultFileManager(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) {
return JavahFileManager.create(dl, log);
}
private void showHelp() {
log.println(getMessage("main.usage", progname));
for (Option o: recognizedOptions) {
if (o.isHidden())
continue;
String name = o.aliases[0].substring(1); // there must always be at least one name
log.println(getMessage("main.opt." + name));
}
String[] fmOptions = { "-classpath", "-bootclasspath" };
for (String o: fmOptions) {
if (fileManager.isSupportedOption(o) == -1)
continue;
String name = o.substring(1);
log.println(getMessage("main.opt." + name));
}
log.println(getMessage("main.usage.foot"));
}
private void showVersion(boolean full) {
log.println(version(full));
}
private static final String versionRBName = "com.sun.tools.javah.resources.version";
private static ResourceBundle versionRB;
private String version(boolean full) {
String msgKey = (full ? "javah.fullVersion" : "javah.version");
String versionKey = (full ? "full" : "release");
// versionKey=product: mm.nn.oo[-milestone]
// versionKey=full: mm.mm.oo[-milestone]-build
if (versionRB == null) {
try {
versionRB = ResourceBundle.getBundle(versionRBName);
} catch (MissingResourceException e) {
return getMessage("version.resource.missing", System.getProperty("java.version"));
}
}
try {
return getMessage(msgKey, "javah", versionRB.getString(versionKey));
}
catch (MissingResourceException e) {
return getMessage("version.unknown", System.getProperty("java.version"));
}
}
private Diagnostic<JavaFileObject> createDiagnostic(final String key, final Object... args) {
return new Diagnostic<JavaFileObject>() {
public Kind getKind() {
return Diagnostic.Kind.ERROR;
}
public JavaFileObject getSource() {
return null;
}
public long getPosition() {
return Diagnostic.NOPOS;
}
public long getStartPosition() {
return Diagnostic.NOPOS;
}
public long getEndPosition() {
return Diagnostic.NOPOS;
}
public long getLineNumber() {
return Diagnostic.NOPOS;
}
public long getColumnNumber() {
return Diagnostic.NOPOS;
}
public String getCode() {
return key;
}
public String getMessage(Locale locale) {
return JavahTask.this.getMessage(locale, key, args);
}
};
}
private String getMessage(String key, Object... args) {
return getMessage(task_locale, key, args);
}
private String getMessage(Locale locale, String key, Object... args) {
if (bundles == null) {
// could make this a HashMap<Locale,SoftReference<ResourceBundle>>
// and for efficiency, keep a hard reference to the bundle for the task
// locale
bundles = new HashMap<Locale, ResourceBundle>();
}
if (locale == null)
locale = Locale.getDefault();
ResourceBundle b = bundles.get(locale);
if (b == null) {
try {
b = ResourceBundle.getBundle("com.sun.tools.javah.resources.l10n", locale);
bundles.put(locale, b);
} catch (MissingResourceException e) {
throw new InternalError("Cannot find javah resource bundle for locale " + locale, e);
}
}
try {
return MessageFormat.format(b.getString(key), args);
} catch (MissingResourceException e) {
return key;
//throw new InternalError(e, key);
}
}
File ofile;
File odir;
String bootcp;
String usercp;
List<String> classes;
boolean verbose;
boolean noArgs;
boolean help;
boolean trace;
boolean version;
boolean fullVersion;
boolean jni;
boolean llni;
boolean doubleAlign;
boolean force;
boolean old;
Set<String> javac_extras = new LinkedHashSet<String>();
PrintWriter log;
JavaFileManager fileManager;
DiagnosticListener<? super JavaFileObject> diagnosticListener;
Locale task_locale;
Map<Locale, ResourceBundle> bundles;
private static final String progname = "javah";
@SupportedAnnotationTypes("*")
class JavahProcessor extends AbstractProcessor {
private Messager messager;
JavahProcessor(Gen g) {
this.g = g;
}
@Override
public SourceVersion getSupportedSourceVersion() {
// since this is co-bundled with javac, we can assume it supports
// the latest source version
return SourceVersion.latest();
}
@Override
public void init(ProcessingEnvironment pEnv) {
super.init(pEnv);
messager = processingEnv.getMessager();
}
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
Set<TypeElement> classes = getAllClasses(ElementFilter.typesIn(roundEnv.getRootElements()));
if (classes.size() > 0) {
checkMethodParameters(classes);
g.setProcessingEnvironment(processingEnv);
g.setClasses(classes);
g.run();
}
} catch (CompletionFailure cf) {
messager.printMessage(ERROR, getMessage("class.not.found", cf.sym.getQualifiedName().toString()));
} catch (ClassNotFoundException cnfe) {
messager.printMessage(ERROR, getMessage("class.not.found", cnfe.getMessage()));
} catch (IOException ioe) {
messager.printMessage(ERROR, getMessage("io.exception", ioe.getMessage()));
} catch (Util.Exit e) {
exit = e;
}
return true;
}
private Set<TypeElement> getAllClasses(Set<? extends TypeElement> classes) {
Set<TypeElement> allClasses = new LinkedHashSet<TypeElement>();
getAllClasses0(classes, allClasses);
return allClasses;
}
private void getAllClasses0(Iterable<? extends TypeElement> classes, Set<TypeElement> allClasses) {
for (TypeElement c: classes) {
allClasses.add(c);
getAllClasses0(ElementFilter.typesIn(c.getEnclosedElements()), allClasses);
}
}
// 4942232:
// check that classes exist for all the parameters of native methods
private void checkMethodParameters(Set<TypeElement> classes) {
Types types = processingEnv.getTypeUtils();
for (TypeElement te: classes) {
for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
for (VariableElement ve: ee.getParameters()) {
TypeMirror tm = ve.asType();
checkMethodParametersVisitor.visit(tm, types);
}
}
}
}
private TypeVisitor<Void,Types> checkMethodParametersVisitor =
new SimpleTypeVisitor7<Void,Types>() {
@Override
public Void visitArray(ArrayType t, Types types) {
visit(t.getComponentType(), types);
return null;
}
@Override
public Void visitDeclared(DeclaredType t, Types types) {
t.asElement().getKind(); // ensure class exists
for (TypeMirror st: types.directSupertypes(t))
visit(st, types);
return null;
}
};
private Gen g;
private Util.Exit exit;
}
}
| 25,668 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
JavahTool.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/JavahTool.java | /*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Set;
import javax.lang.model.SourceVersion;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class JavahTool implements NativeHeaderTool {
public NativeHeaderTask getTask(Writer out,
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes) {
return new JavahTask(out, fileManager, diagnosticListener, options, classes);
}
public StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) {
return JavahTask.getDefaultFileManager(diagnosticListener, null);
}
public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
JavahTask t = new JavahTask(
JavahTask.getPrintWriterForStream(out),
null,
null,
Arrays.asList(arguments),
null);
return (t.run() ? 0 : 1);
}
public Set<SourceVersion> getSourceVersions() {
return EnumSet.allOf(SourceVersion.class);
}
public int isSupportedOption(String option) {
JavahTask.Option[] options = JavahTask.recognizedOptions;
for (int i = 0; i < options.length; i++) {
if (options[i].matches(option))
return (options[i].hasArg ? 1 : 0);
}
return -1;
}
}
| 3,244 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Mangle.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/javah/Mangle.java | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javah;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
/**
* A utility for mangling java identifiers into C names. Should make
* this more fine grained and distribute the functionality to the
* generators.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*
* @author Sucheta Dambalkar(Revised)
*/
public class Mangle {
public static class Type {
public static final int CLASS = 1;
public static final int FIELDSTUB = 2;
public static final int FIELD = 3;
public static final int JNI = 4;
public static final int SIGNATURE = 5;
public static final int METHOD_JDK_1 = 6;
public static final int METHOD_JNI_SHORT = 7;
public static final int METHOD_JNI_LONG = 8;
};
private Elements elems;
private Types types;
Mangle(Elements elems, Types types) {
this.elems = elems;
this.types = types;
}
public final String mangle(CharSequence name, int mtype) {
StringBuffer result = new StringBuffer(100);
int length = name.length();
for (int i = 0; i < length; i++) {
char ch = name.charAt(i);
if (isalnum(ch)) {
result.append(ch);
} else if ((ch == '.') &&
mtype == Mangle.Type.CLASS) {
result.append('_');
} else if (( ch == '$') &&
mtype == Mangle.Type.CLASS) {
result.append('_');
result.append('_');
} else if (ch == '_' && mtype == Mangle.Type.FIELDSTUB) {
result.append('_');
} else if (ch == '_' && mtype == Mangle.Type.CLASS) {
result.append('_');
} else if (mtype == Mangle.Type.JNI) {
String esc = null;
if (ch == '_')
esc = "_1";
else if (ch == '.')
esc = "_";
else if (ch == ';')
esc = "_2";
else if (ch == '[')
esc = "_3";
if (esc != null) {
result.append(esc);
} else {
result.append(mangleChar(ch));
}
} else if (mtype == Mangle.Type.SIGNATURE) {
if (isprint(ch)) {
result.append(ch);
} else {
result.append(mangleChar(ch));
}
} else {
result.append(mangleChar(ch));
}
}
return result.toString();
}
public String mangleMethod(ExecutableElement method, TypeElement clazz,
int mtype) throws TypeSignature.SignatureException {
StringBuffer result = new StringBuffer(100);
result.append("Java_");
if (mtype == Mangle.Type.METHOD_JDK_1) {
result.append(mangle(clazz.getQualifiedName(), Mangle.Type.CLASS));
result.append('_');
result.append(mangle(method.getSimpleName(),
Mangle.Type.FIELD));
result.append("_stub");
return result.toString();
}
/* JNI */
result.append(mangle(getInnerQualifiedName(clazz), Mangle.Type.JNI));
result.append('_');
result.append(mangle(method.getSimpleName(),
Mangle.Type.JNI));
if (mtype == Mangle.Type.METHOD_JNI_LONG) {
result.append("__");
String typesig = signature(method);
TypeSignature newTypeSig = new TypeSignature(elems);
String sig = newTypeSig.getTypeSignature(typesig, method.getReturnType());
sig = sig.substring(1);
sig = sig.substring(0, sig.lastIndexOf(')'));
sig = sig.replace('/', '.');
result.append(mangle(sig, Mangle.Type.JNI));
}
return result.toString();
}
//where
private String getInnerQualifiedName(TypeElement clazz) {
return elems.getBinaryName(clazz).toString();
}
public final String mangleChar(char ch) {
String s = Integer.toHexString(ch);
int nzeros = 5 - s.length();
char[] result = new char[6];
result[0] = '_';
for (int i = 1; i <= nzeros; i++)
result[i] = '0';
for (int i = nzeros+1, j = 0; i < 6; i++, j++)
result[i] = s.charAt(j);
return new String(result);
}
// Warning: duplicated in Gen
private String signature(ExecutableElement e) {
StringBuffer sb = new StringBuffer();
String sep = "(";
for (VariableElement p: e.getParameters()) {
sb.append(sep);
sb.append(types.erasure(p.asType()).toString());
sep = ",";
}
sb.append(")");
return sb.toString();
}
/* Warning: Intentional ASCII operation. */
private static final boolean isalnum(char ch) {
return ch <= 0x7f && /* quick test */
((ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9'));
}
/* Warning: Intentional ASCII operation. */
private static final boolean isprint(char ch) {
return ch >= 32 && ch <= 126;
}
}
| 6,944 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Main.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/Main.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt;
import java.io.PrintWriter;
import com.sun.mirror.apt.AnnotationProcessorFactory;
/**
* The main program for the command-line tool apt.
*
* <p>Nothing described in this source file is part of any supported
* API. If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.
*/
public class Main {
static {
ClassLoader loader = Main.class.getClassLoader();
if (loader != null)
loader.setPackageAssertionStatus("com.sun.tools.apt", true);
}
/** Command line interface. If args is <tt>null</tt>, a
* <tt>NullPointerException</tt> is thrown.
* @param args The command line parameters.
*/
public static void main(String... args) {
System.exit(process(args));
}
/** Programatic interface. If args is <tt>null</tt>, a
* <tt>NullPointerException</tt> is thrown.
* Output is directed to <tt>System.err</tt>.
* @param args The command line parameters.
*/
public static int process(String... args) {
return processing(null, null, args);
}
/** Programmatic interface. If any argument
* is <tt>null</tt>, a <tt>NullPointerException</tt> is thrown.
* @param args The command line parameters.
* @param out Where the tool's output is directed.
*/
public static int process(PrintWriter out, String... args) {
if (out == null)
throw new NullPointerException("Parameter out cannot be null.");
return processing(null, out, args);
}
/** Programmatic interface. If <tt>factory</tt> or <tt>args</tt>
* is <tt>null</tt>, a <tt>NullPointerException</tt> is thrown.
* The "<tt>-factory</tt>" and "<tt>-factorypath</tt>"
* command line parameters are ignored by this entry point.
* Output is directed to <tt>System.err</tt>.
*
* @param factory The annotation processor factory to use
* @param args The command line parameters.
*/
public static int process(AnnotationProcessorFactory factory, String... args) {
return process(factory, new PrintWriter(System.err, true), args);
}
/** Programmatic interface. If any argument
* is <tt>null</tt>, a <tt>NullPointerException</tt> is thrown.
* The "<tt>-factory</tt>" and "<tt>-factorypath</tt>"
* command line parameters are ignored by this entry point.
*
* @param factory The annotation processor factory to use
* @param args The command line parameters.
* @param out Where the tool's output is directed.
*/
public static int process(AnnotationProcessorFactory factory, PrintWriter out,
String... args) {
if (out == null)
throw new NullPointerException("Parameter out cannot be null.");
if (factory == null)
throw new NullPointerException("Parameter factory cannot be null");
return processing(factory, out, args);
}
private static int processing(AnnotationProcessorFactory factory,
PrintWriter out,
String... args) {
if (out == null)
out = new PrintWriter(System.err, true);
com.sun.tools.apt.main.Main compiler =
new com.sun.tools.apt.main.Main("apt", out);
return compiler.compile(args, factory);
}
}
| 4,721 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Main.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/main/Main.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.main;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.MalformedURLException;
import javax.tools.JavaFileManager;
import javax.tools.StandardLocation;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.util.*;
import com.sun.tools.apt.comp.AnnotationProcessingError;
import com.sun.tools.apt.comp.UsageMessageNeededException;
import com.sun.tools.apt.util.Bark;
import com.sun.mirror.apt.AnnotationProcessorFactory;
import static com.sun.tools.javac.file.Paths.pathToURLs;
/** This class provides a commandline interface to the apt build-time
* tool.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b>
*/
@SuppressWarnings("deprecation")
public class Main {
/** For testing: enter any options you want to be set implicitly
* here.
*/
static String[] forcedOpts = {
// Preserve parameter names from class files if the class was
// compiled with debug enabled
"-XDsave-parameter-names"
};
/** The name of the compiler, for use in diagnostics.
*/
String ownName;
/** The writer to use for diagnostic output.
*/
PrintWriter out;
/** Instantiated factory to use in lieu of discovery process.
*/
AnnotationProcessorFactory providedFactory = null;
/** Map representing original command-line arguments.
*/
Map<String,String> origOptions = new HashMap<String, String>();
/** Classloader to use for finding factories.
*/
ClassLoader aptCL = null;
/** Result codes.
*/
static final int
EXIT_OK = 0, // Compilation completed with no errors.
EXIT_ERROR = 1, // Completed but reported errors.
EXIT_CMDERR = 2, // Bad command-line arguments
EXIT_SYSERR = 3, // System error or resource exhaustion.
EXIT_ABNORMAL = 4; // Compiler terminated abnormally
/** This class represents an option recognized by the main program
*/
private class Option {
/** Whether or not the option is used only aptOnly.
*/
boolean aptOnly = false;
/** Option string.
*/
String name;
/** Documentation key for arguments.
*/
String argsNameKey;
/** Documentation key for description.
*/
String descrKey;
/** Suffix option (-foo=bar or -foo:bar)
*/
boolean hasSuffix;
Option(String name, String argsNameKey, String descrKey) {
this.name = name;
this.argsNameKey = argsNameKey;
this.descrKey = descrKey;
char lastChar = name.charAt(name.length()-1);
hasSuffix = lastChar == ':' || lastChar == '=';
}
Option(String name, String descrKey) {
this(name, null, descrKey);
}
public String toString() {
return name;
}
/** Does this option take a (separate) operand?
*/
boolean hasArg() {
return argsNameKey != null && !hasSuffix;
}
/** Does argument string match option pattern?
* @param arg The command line argument string.
*/
boolean matches(String arg) {
return hasSuffix ? arg.startsWith(name) : arg.equals(name);
}
/** For javac-only options, print nothing.
*/
void help() {
}
String helpSynopsis() {
return name +
(argsNameKey == null ? "" :
((hasSuffix ? "" : " ") +
getLocalizedString(argsNameKey)));
}
/** Print a line of documentation describing this option, if non-standard.
*/
void xhelp() {}
/** Process the option (with arg). Return true if error detected.
*/
boolean process(String option, String arg) {
options.put(option, arg);
return false;
}
/** Process the option (without arg). Return true if error detected.
*/
boolean process(String option) {
if (hasSuffix)
return process(name, option.substring(name.length()));
else
return process(option, option);
}
};
private class SharedOption extends Option {
SharedOption(String name, String argsNameKey, String descrKey) {
super(name, argsNameKey, descrKey);
}
SharedOption(String name, String descrKey) {
super(name, descrKey);
}
void help() {
String s = " " + helpSynopsis();
out.print(s);
for (int j = s.length(); j < 29; j++) out.print(" ");
Bark.printLines(out, getLocalizedString(descrKey));
}
}
private class AptOption extends Option {
AptOption(String name, String argsNameKey, String descrKey) {
super(name, argsNameKey, descrKey);
aptOnly = true;
}
AptOption(String name, String descrKey) {
super(name, descrKey);
aptOnly = true;
}
/** Print a line of documentation describing this option, if standard.
*/
void help() {
String s = " " + helpSynopsis();
out.print(s);
for (int j = s.length(); j < 29; j++) out.print(" ");
Bark.printLines(out, getLocalizedString(descrKey));
}
}
/** A nonstandard or extended (-X) option
*/
private class XOption extends Option {
XOption(String name, String argsNameKey, String descrKey) {
super(name, argsNameKey, descrKey);
}
XOption(String name, String descrKey) {
this(name, null, descrKey);
}
void help() {}
void xhelp() {}
};
/** A nonstandard or extended (-X) option
*/
private class AptXOption extends Option {
AptXOption(String name, String argsNameKey, String descrKey) {
super(name, argsNameKey, descrKey);
aptOnly = true;
}
AptXOption(String name, String descrKey) {
this(name, null, descrKey);
}
void xhelp() {
String s = " " + helpSynopsis();
out.print(s);
for (int j = s.length(); j < 29; j++) out.print(" ");
Log.printLines(out, getLocalizedString(descrKey));
}
};
/** A hidden (implementor) option
*/
private class HiddenOption extends Option {
HiddenOption(String name) {
super(name, null, null);
}
HiddenOption(String name, String argsNameKey) {
super(name, argsNameKey, null);
}
void help() {}
void xhelp() {}
};
private class AptHiddenOption extends HiddenOption {
AptHiddenOption(String name) {
super(name);
aptOnly = true;
}
AptHiddenOption(String name, String argsNameKey) {
super(name, argsNameKey);
aptOnly = true;
}
}
private Option[] recognizedOptions = {
new Option("-g", "opt.g"),
new Option("-g:none", "opt.g.none") {
boolean process(String option) {
options.put("-g:", "none");
return false;
}
},
new Option("-g:{lines,vars,source}", "opt.g.lines.vars.source") {
boolean matches(String s) {
return s.startsWith("-g:");
}
boolean process(String option) {
String suboptions = option.substring(3);
options.put("-g:", suboptions);
// enter all the -g suboptions as "-g:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-g:" + tok;
options.put(opt, opt);
}
return false;
}
},
new XOption("-Xlint", "opt.Xlint"),
new XOption("-Xlint:{"
+ "all,"
+ "cast,deprecation,divzero,empty,unchecked,fallthrough,path,serial,finally,overrides,"
+ "-cast,-deprecation,-divzero,-empty,-unchecked,-fallthrough,-path,-serial,-finally,-overrides,"
+ "none}",
"opt.Xlint.suboptlist") {
boolean matches(String s) {
return s.startsWith("-Xlint:");
}
boolean process(String option) {
String suboptions = option.substring(7);
options.put("-Xlint:", suboptions);
// enter all the -Xlint suboptions as "-Xlint:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-Xlint:" + tok;
options.put(opt, opt);
}
return false;
}
},
new Option("-nowarn", "opt.nowarn"),
new Option("-verbose", "opt.verbose"),
// -deprecation is retained for command-line backward compatibility
new Option("-deprecation", "opt.deprecation") {
boolean process(String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new SharedOption("-classpath", "opt.arg.path", "opt.classpath"),
new SharedOption("-cp", "opt.arg.path", "opt.classpath") {
boolean process(String option, String arg) {
return super.process("-classpath", arg);
}
},
new Option("-sourcepath", "opt.arg.path", "opt.sourcepath"),
new Option("-bootclasspath", "opt.arg.path", "opt.bootclasspath") {
boolean process(String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(option, arg);
}
},
new XOption("-Xbootclasspath/p:", "opt.arg.path", "opt.Xbootclasspath.p"),
new XOption("-Xbootclasspath/a:", "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption("-Xbootclasspath:", "opt.arg.path", "opt.bootclasspath") {
boolean process(String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process("-bootclasspath", arg);
}
},
new Option("-extdirs", "opt.arg.dirs", "opt.extdirs"),
new XOption("-Djava.ext.dirs=", "opt.arg.dirs", "opt.extdirs") {
boolean process(String option, String arg) {
return super.process("-extdirs", arg);
}
},
new Option("-endorseddirs", "opt.arg.dirs", "opt.endorseddirs"),
new XOption("-Djava.endorsed.dirs=","opt.arg.dirs", "opt.endorseddirs") {
boolean process(String option, String arg) {
return super.process("-endorseddirs", arg);
}
},
new Option("-proc:{none, only}", "opt.proc.none.only") {
public boolean matches(String s) {
return s.equals("-proc:none") || s.equals("-proc:only");
}
},
new Option("-processor", "opt.arg.class", "opt.processor"),
new Option("-processorpath", "opt.arg.path", "opt.processorpath"),
new SharedOption("-d", "opt.arg.path", "opt.d"),
new SharedOption("-s", "opt.arg.path", "opt.s"),
new Option("-encoding", "opt.arg.encoding", "opt.encoding"),
new SharedOption("-source", "opt.arg.release", "opt.source") {
boolean process(String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
error("err.invalid.source", operand);
return true;
} else if (source.compareTo(Source.JDK1_5) > 0) {
error("err.unsupported.source.version", operand);
return true;
}
return super.process(option, operand);
}
},
new Option("-target", "opt.arg.release", "opt.target") {
boolean process(String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
error("err.invalid.target", operand);
return true;
} else if (target.compareTo(Target.JDK1_5) > 0) {
error("err.unsupported.target.version", operand);
return true;
}
return super.process(option, operand);
}
},
new AptOption("-version", "opt.version") {
boolean process(String option) {
Bark.printLines(out, ownName + " " + AptJavaCompiler.version());
return super.process(option);
}
},
new HiddenOption("-fullversion"),
new AptOption("-help", "opt.help") {
boolean process(String option) {
Main.this.help();
return super.process(option);
}
},
new SharedOption("-X", "opt.X") {
boolean process(String option) {
Main.this.xhelp();
return super.process(option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new AptOption("-J", "opt.arg.flag", "opt.J") {
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
boolean process(String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
new SharedOption("-A", "opt.proc.flag", "opt.A") {
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
boolean matches(String arg) {
return arg.startsWith("-A");
}
boolean hasArg() {
return false;
}
boolean process(String option) {
return process(option, option);
}
},
new AptOption("-nocompile", "opt.nocompile"),
new AptOption("-print", "opt.print"),
new AptOption("-factorypath", "opt.arg.path", "opt.factorypath"),
new AptOption("-factory", "opt.arg.class", "opt.factory"),
new AptXOption("-XListAnnotationTypes", "opt.XListAnnotationTypes"),
new AptXOption("-XListDeclarations", "opt.XListDeclarations"),
new AptXOption("-XPrintAptRounds", "opt.XPrintAptRounds"),
new AptXOption("-XPrintFactoryInfo", "opt.XPrintFactoryInfo"),
/*
* Option to treat both classes and source files as
* declarations that can be given on the command line and
* processed as the result of an apt round.
*/
new AptXOption("-XclassesAsDecls", "opt.XClassesAsDecls"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption("-moreinfo") {
boolean process(String option) {
Type.moreInfo = true;
return super.process(option);
}
},
// treat warnings as errors
new HiddenOption("-Werror"),
// use complex inference from context in the position of a method call argument
new HiddenOption("-complexinference"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption("-prompt"),
// dump stack on error
new HiddenOption("-doe"),
// display warnings for generic unchecked and unsafe operations
new HiddenOption("-warnunchecked") {
boolean process(String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new HiddenOption("-Xswitchcheck") {
boolean process(String option) {
options.put("-Xlint:switchcheck", option);
return false;
}
},
// generate trace output for subtyping operations
new HiddenOption("-debugsubtyping"),
new XOption("-Xmaxerrs", "opt.arg.number", "opt.maxerrs"),
new XOption("-Xmaxwarns", "opt.arg.number", "opt.maxwarns"),
new XOption("-Xstdout", "opt.arg.file", "opt.Xstdout") {
boolean process(String option, String arg) {
try {
out = new PrintWriter(new FileWriter(arg), true);
} catch (java.io.IOException e) {
error("err.error.writing.file", arg, e);
return true;
}
return super.process(option, arg);
}
},
new XOption("-Xprint", "opt.print"),
new XOption("-XprintRounds", "opt.printRounds"),
new XOption("-XprintProcessorInfo", "opt.printProcessorInfo"),
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption("-O"),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption("-Xjcov"),
/* This is a back door to the compiler's option table.
* -Dx=y sets the option x to the value y.
* -Dx sets the option x to the value x.
*/
new HiddenOption("-XD") {
String s;
boolean matches(String s) {
this.s = s;
return s.startsWith(name);
}
boolean process(String option) {
s = s.substring(name.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
new HiddenOption("sourcefile") {
String s;
boolean matches(String s) {
this.s = s;
return s.endsWith(".java") ||
(options.get("-XclassesAsDecls") != null);
}
boolean process(String option) {
if (s.endsWith(".java")) {
if (!sourceFileNames.contains(s))
sourceFileNames.add(s);
} else if (options.get("-XclassesAsDecls") != null) {
classFileNames.add(s);
}
return false;
}
},
};
/**
* Construct a compiler instance.
*/
public Main(String name) {
this(name, new PrintWriter(System.err, true));
}
/**
* Construct a compiler instance.
*/
public Main(String name, PrintWriter out) {
this.ownName = name;
this.out = out;
}
/** A table of all options that's passed to the JavaCompiler constructor. */
private Options options = null;
/** The list of source files to process
*/
java.util.List<String> sourceFileNames = new java.util.LinkedList<String>();
/** The list of class files to process
*/
java.util.List<String> classFileNames = new java.util.LinkedList<String>();
/** List of top level names of generated source files from most recent apt round.
*/
java.util.Set<String> genSourceFileNames = new java.util.LinkedHashSet<String>();
/** List of names of generated class files from most recent apt round.
*/
java.util.Set<String> genClassFileNames = new java.util.LinkedHashSet<String>();
/**
* List of all the generated source file names across all apt rounds.
*/
java.util.Set<String> aggregateGenSourceFileNames = new java.util.LinkedHashSet<String>();
/**
* List of all the generated class file names across all apt rounds.
*/
java.util.Set<String> aggregateGenClassFileNames = new java.util.LinkedHashSet<String>();
/**
* List of all the generated file names across all apt rounds.
*/
java.util.Set<java.io.File> aggregateGenFiles = new java.util.LinkedHashSet<java.io.File>();
/**
* Set of all factories that have provided a processor on some apt round.
*/
java.util.Set<Class<? extends AnnotationProcessorFactory> > productiveFactories =
new java.util.LinkedHashSet<Class<? extends AnnotationProcessorFactory> >();
/** Print a string that explains usage.
*/
void help() {
Bark.printLines(out, getLocalizedString("msg.usage.header", ownName));
for (int i=0; i < recognizedOptions.length; i++) {
recognizedOptions[i].help();
}
Bark.printLines(out, getLocalizedString("msg.usage.footer"));
out.println();
}
/** Print a string that explains usage for X options.
*/
void xhelp() {
for (int i=0; i<recognizedOptions.length; i++) {
recognizedOptions[i].xhelp();
}
out.println();
Bark.printLines(out, getLocalizedString("msg.usage.nonstandard.footer"));
}
/** Report a usage error.
*/
void error(String key, Object... args) {
warning(key, args);
help();
}
/** Report a warning.
*/
void warning(String key, Object... args) {
Bark.printLines(out, ownName + ": "
+ getLocalizedString(key, args));
}
/** Process command line arguments: store all command line options
* in `options' table and return all source filenames.
* @param args The array of command line arguments.
*/
protected java.util.List<String> processArgs(String[] flags) {
int ac = 0;
while (ac < flags.length) {
String flag = flags[ac];
ac++;
int j;
for (j=0; j < recognizedOptions.length; j++)
if (recognizedOptions[j].matches(flag))
break;
if (j == recognizedOptions.length) {
error("err.invalid.flag", flag);
return null;
}
Option option = recognizedOptions[j];
if (option.hasArg()) {
if (ac == flags.length) {
error("err.req.arg", flag);
return null;
}
String operand = flags[ac];
ac++;
if (option.process(flag, operand))
return null;
} else {
if (option.process(flag))
return null;
}
}
String sourceString = options.get("-source");
Source source = (sourceString != null)
? Source.lookup(sourceString)
: Source.JDK1_5; // JDK 5 is the latest supported source version
String targetString = options.get("-target");
Target target = (targetString != null)
? Target.lookup(targetString)
: Target.JDK1_5; // JDK 5 is the latest supported source version
// We don't check source/target consistency for CLDC, as J2ME
// profiles are not aligned with J2SE targets; moreover, a
// single CLDC target may have many profiles. In addition,
// this is needed for the continued functioning of the JSR14
// prototype.
if (Character.isDigit(target.name.charAt(0)) &&
target.compareTo(source.requiredTarget()) < 0) {
if (targetString != null) {
if (sourceString == null) {
warning("warn.target.default.source.conflict",
targetString,
source.requiredTarget().name);
} else {
warning("warn.source.target.conflict",
sourceString,
source.requiredTarget().name);
}
return null;
} else {
options.put("-target", source.requiredTarget().name);
}
}
return sourceFileNames;
}
/** Programmatic interface for main function.
* @param args The command line parameters.
*/
public int compile(String[] args, AnnotationProcessorFactory factory) {
int returnCode = 0;
providedFactory = factory;
Context context = new Context();
JavacFileManager.preRegister(context);
options = Options.instance(context);
Bark bark;
/*
* Process the command line options to create the intial
* options data. This processing is at least partially reused
* by any recursive apt calls.
*/
// For testing: assume all arguments in forcedOpts are
// prefixed to command line arguments.
processArgs(forcedOpts);
/*
* A run of apt only gets passed the most recently generated
* files; the initial run of apt gets passed the files from
* the command line.
*/
java.util.List<String> origFilenames;
try {
// assign args the result of parse to capture results of
// '@file' expansion
origFilenames = processArgs((args=CommandLine.parse(args)));
if (options.get("suppress-tool-api-removal-message") == null) {
Bark.printLines(out, getLocalizedString("misc.Deprecation"));
}
if (origFilenames == null) {
return EXIT_CMDERR;
} else if (origFilenames.size() == 0) {
// it is allowed to compile nothing if just asking for help
if (options.get("-help") != null ||
options.get("-X") != null)
return EXIT_OK;
}
} catch (java.io.FileNotFoundException e) {
Bark.printLines(out, ownName + ": " +
getLocalizedString("err.file.not.found",
e.getMessage()));
return EXIT_SYSERR;
} catch (IOException ex) {
ioMessage(ex);
return EXIT_SYSERR;
} catch (OutOfMemoryError ex) {
resourceMessage(ex);
return EXIT_SYSERR;
} catch (StackOverflowError ex) {
resourceMessage(ex);
return EXIT_SYSERR;
} catch (FatalError ex) {
feMessage(ex);
return EXIT_SYSERR;
} catch (sun.misc.ServiceConfigurationError sce) {
sceMessage(sce);
return EXIT_ABNORMAL;
} catch (Throwable ex) {
bugMessage(ex);
return EXIT_ABNORMAL;
}
boolean firstRound = true;
boolean needSourcePath = false;
boolean needClassPath = false;
boolean classesAsDecls = options.get("-XclassesAsDecls") != null;
/*
* Create augumented classpath and sourcepath values.
*
* If any of the prior apt rounds generated any new source
* files, the n'th apt round (and any javac invocation) has the
* source destination path ("-s path") as the last element of
* the "-sourcepath" to the n'th call.
*
* If any of the prior apt rounds generated any new class files,
* the n'th apt round (and any javac invocation) has the class
* destination path ("-d path") as the last element of the
* "-classpath" to the n'th call.
*/
String augmentedSourcePath = "";
String augmentedClassPath = "";
String baseClassPath = "";
try {
/*
* Record original options for future annotation processor
* invocations.
*/
origOptions = new HashMap<String, String>(options.size());
for(String s: options.keySet()) {
String value;
if (s.equals(value = options.get(s)))
origOptions.put(s, (String)null);
else
origOptions.put(s, value);
}
origOptions = Collections.unmodifiableMap(origOptions);
JavacFileManager fm = (JavacFileManager) context.get(JavaFileManager.class);
{
// Note: it might be necessary to check for an empty
// component ("") of the source path or class path
String sourceDest = options.get("-s");
if (fm.hasLocation(StandardLocation.SOURCE_PATH)) {
for(File f: fm.getLocation(StandardLocation.SOURCE_PATH))
augmentedSourcePath += (f + File.pathSeparator);
augmentedSourcePath += (sourceDest == null)?".":sourceDest;
} else {
augmentedSourcePath = ".";
if (sourceDest != null)
augmentedSourcePath += (File.pathSeparator + sourceDest);
}
String classDest = options.get("-d");
if (fm.hasLocation(StandardLocation.CLASS_PATH)) {
for(File f: fm.getLocation(StandardLocation.CLASS_PATH))
baseClassPath += (f + File.pathSeparator);
// put baseClassPath into map to handle any
// value needed for the classloader
options.put("-classpath", baseClassPath);
augmentedClassPath = baseClassPath + ((classDest == null)?".":classDest);
} else {
baseClassPath = ".";
if (classDest != null)
augmentedClassPath = baseClassPath + (File.pathSeparator + classDest);
}
assert options.get("-classpath") != null;
}
/*
* Create base and augmented class loaders
*/
ClassLoader augmentedAptCL = null;
{
/*
* Use a url class loader to look for classes on the
* user-specified class path. Prepend computed bootclass
* path, which includes extdirs, to the URLClassLoader apt
* uses.
*/
String aptclasspath = "";
String bcp = "";
Iterable<? extends File> bootclasspath = fm.getLocation(StandardLocation.PLATFORM_CLASS_PATH);
if (bootclasspath != null) {
for(File f: bootclasspath)
bcp += (f + File.pathSeparator);
}
// If the factory path is set, use that path
if (providedFactory == null)
aptclasspath = options.get("-factorypath");
if (aptclasspath == null)
aptclasspath = options.get("-classpath");
assert aptclasspath != null;
aptclasspath = (bcp + aptclasspath);
aptCL = new URLClassLoader(pathToURLs(aptclasspath));
if (providedFactory == null &&
options.get("-factorypath") != null) // same CL even if new class files written
augmentedAptCL = aptCL;
else {
// Create class loader in case new class files are
// written
augmentedAptCL = new URLClassLoader(pathToURLs(augmentedClassPath.
substring(baseClassPath.length())),
aptCL);
}
}
int round = 0; // For -XPrintAptRounds
do {
round++;
Context newContext = new Context();
Options newOptions = Options.instance(newContext); // creates a new context
newOptions.putAll(options);
// populate with old options... don't bother reparsing command line, etc.
// if genSource files, must add destination to source path
if (genSourceFileNames.size() > 0 && !firstRound) {
newOptions.put("-sourcepath", augmentedSourcePath);
needSourcePath = true;
}
aggregateGenSourceFileNames.addAll(genSourceFileNames);
sourceFileNames.addAll(genSourceFileNames);
genSourceFileNames.clear();
// Don't really need to track this; just have to add -d
// "foo" to class path if any class files are generated
if (genClassFileNames.size() > 0) {
newOptions.put("-classpath", augmentedClassPath);
aptCL = augmentedAptCL;
needClassPath = true;
}
aggregateGenClassFileNames.addAll(genClassFileNames);
classFileNames.addAll(genClassFileNames);
genClassFileNames.clear();
options = newOptions;
if (options.get("-XPrintAptRounds") != null) {
out.println("apt Round : " + round);
out.println("filenames: " + sourceFileNames);
if (classesAsDecls)
out.println("classnames: " + classFileNames);
out.println("options: " + options);
}
returnCode = compile(args, newContext);
firstRound = false;
// Check for reported errors before continuing
bark = Bark.instance(newContext);
} while(((genSourceFileNames.size() != 0 ) ||
(classesAsDecls && genClassFileNames.size() != 0)) &&
bark.nerrors == 0);
} catch (UsageMessageNeededException umne) {
help();
return EXIT_CMDERR; // will cause usage message to be printed
}
/*
* Do not compile if a processor has reported an error or if
* there are no source files to process. A more sophisticated
* test would also fail for syntax errors caught by javac.
*/
if (options.get("-nocompile") == null &&
options.get("-print") == null &&
bark.nerrors == 0 &&
(origFilenames.size() > 0 || aggregateGenSourceFileNames.size() > 0 )) {
/*
* Need to create new argument string for calling javac:
* 1. apt specific arguments (e.g. -factory) must be stripped out
* 2. proper settings for sourcepath and classpath must be used
* 3. generated class names must be added
* 4. class file names as declarations must be removed
*/
int newArgsLength = args.length +
(needSourcePath?1:0) +
(needClassPath?1:0) +
aggregateGenSourceFileNames.size();
// Null out apt-specific options and don't copy over into
// newArgs. This loop should be a lot faster; the options
// array should be replaced with a better data structure
// which includes a map from strings to options.
//
// If treating classes as declarations, must strip out
// class names from the javac argument list
argLoop:
for(int i = 0; i < args.length; i++) {
int matchPosition = -1;
// "-A" by itself is recognized by apt but not javac
if (args[i] != null && args[i].equals("-A")) {
newArgsLength--;
args[i] = null;
continue argLoop;
} else {
optionLoop:
for(int j = 0; j < recognizedOptions.length; j++) {
if (args[i] != null && recognizedOptions[j].matches(args[i])) {
matchPosition = j;
break optionLoop;
}
}
if (matchPosition != -1) {
Option op = recognizedOptions[matchPosition];
if (op.aptOnly) {
newArgsLength--;
args[i] = null;
if (op.hasArg()) {
newArgsLength--;
args[i+1] = null;
}
} else {
if (op.hasArg()) { // skip over next string
i++;
continue argLoop;
}
if ((options.get("-XclassesAsDecls") != null) &&
(matchPosition == (recognizedOptions.length-1)) ){
// Remove class file names from
// consideration by javac.
if (! args[i].endsWith(".java")) {
newArgsLength--;
args[i] = null;
}
}
}
}
}
}
String newArgs[] = new String[newArgsLength];
int j = 0;
for(int i=0; i < args.length; i++) {
if (args[i] != null)
newArgs[j++] = args[i];
}
if (needClassPath)
newArgs[j++] = "-XD-classpath=" + augmentedClassPath;
if (needSourcePath) {
newArgs[j++] = "-XD-sourcepath=" + augmentedSourcePath;
for(String s: aggregateGenSourceFileNames)
newArgs[j++] = s;
}
returnCode = com.sun.tools.javac.Main.compile(newArgs);
}
return returnCode;
}
/** Programmatic interface for main function.
* @param args The command line parameters.
*/
int compile(String[] args, Context context) {
boolean assertionsEnabled = false;
assert assertionsEnabled = true;
if (!assertionsEnabled) {
// Bark.printLines(out, "fatal error: assertions must be enabled when running javac");
// return EXIT_ABNORMAL;
}
int exitCode = EXIT_OK;
AptJavaCompiler comp = null;
try {
context.put(Bark.outKey, out);
comp = AptJavaCompiler.instance(context);
if (comp == null)
return EXIT_SYSERR;
java.util.List<String> nameList = new java.util.LinkedList<String>();
nameList.addAll(sourceFileNames);
if (options.get("-XclassesAsDecls") != null)
nameList.addAll(classFileNames);
List<Symbol.ClassSymbol> cs
= comp.compile(List.from(nameList.toArray(new String[0])),
origOptions,
aptCL,
providedFactory,
productiveFactories,
aggregateGenFiles);
/*
* If there aren't new source files, we shouldn't bother
* running javac if there were errors.
*
* If there are new files, we should try running javac in
* case there were typing errors.
*
*/
if (comp.errorCount() != 0 ||
options.get("-Werror") != null && comp.warningCount() != 0)
return EXIT_ERROR;
} catch (IOException ex) {
ioMessage(ex);
return EXIT_SYSERR;
} catch (OutOfMemoryError ex) {
resourceMessage(ex);
return EXIT_SYSERR;
} catch (StackOverflowError ex) {
resourceMessage(ex);
return EXIT_SYSERR;
} catch (FatalError ex) {
feMessage(ex);
return EXIT_SYSERR;
} catch (UsageMessageNeededException umne) {
help();
return EXIT_CMDERR; // will cause usage message to be printed
} catch (AnnotationProcessingError ex) {
apMessage(ex);
return EXIT_ABNORMAL;
} catch (sun.misc.ServiceConfigurationError sce) {
sceMessage(sce);
return EXIT_ABNORMAL;
} catch (Throwable ex) {
bugMessage(ex);
return EXIT_ABNORMAL;
} finally {
if (comp != null) {
comp.close();
genSourceFileNames.addAll(comp.getSourceFileNames());
genClassFileNames.addAll(comp.getClassFileNames());
}
sourceFileNames = new java.util.LinkedList<String>();
classFileNames = new java.util.LinkedList<String>();
}
return exitCode;
}
/** Print a message reporting an internal error.
*/
void bugMessage(Throwable ex) {
Bark.printLines(out, getLocalizedString("msg.bug",
AptJavaCompiler.version()));
ex.printStackTrace(out);
}
/** Print a message reporting an fatal error.
*/
void apMessage(AnnotationProcessingError ex) {
Bark.printLines(out, getLocalizedString("misc.Problem"));
ex.getCause().printStackTrace(out);
}
/** Print a message about sun.misc.Service problem.
*/
void sceMessage(sun.misc.ServiceConfigurationError ex) {
Bark.printLines(out, getLocalizedString("misc.SunMiscService"));
ex.printStackTrace(out);
}
/** Print a message reporting an fatal error.
*/
void feMessage(Throwable ex) {
Bark.printLines(out, ex.toString());
}
/** Print a message reporting an input/output error.
*/
void ioMessage(Throwable ex) {
Bark.printLines(out, getLocalizedString("msg.io"));
ex.printStackTrace(out);
}
/** Print a message reporting an out-of-resources error.
*/
void resourceMessage(Throwable ex) {
Bark.printLines(out, getLocalizedString("msg.resource"));
ex.printStackTrace(out);
}
/* ************************************************************************
* Internationalization
*************************************************************************/
/** Find a localized string in the resource bundle.
* @param key The key for the localized string.
*/
private static String getLocalizedString(String key, Object... args) {
return getText(key, args);
}
private static final String javacRB =
"com.sun.tools.javac.resources.javac";
private static final String aptRB =
"com.sun.tools.apt.resources.apt";
private static ResourceBundle messageRBjavac;
private static ResourceBundle messageRBapt;
/** Initialize ResourceBundle.
*/
private static void initResource() {
try {
messageRBapt = ResourceBundle.getBundle(aptRB);
messageRBjavac = ResourceBundle.getBundle(javacRB);
} catch (MissingResourceException e) {
Error x = new FatalError("Fatal Error: Resource for apt or javac is missing");
x.initCause(e);
throw x;
}
}
/** Get and format message string from resource.
*/
private static String getText(String key, Object... _args) {
String[] args = new String[_args.length];
for (int i=0; i<_args.length; i++) {
args[i] = "" + _args[i];
}
if (messageRBapt == null || messageRBjavac == null )
initResource();
try {
return MessageFormat.format(messageRBapt.getString("apt." + key),
(Object[]) args);
} catch (MissingResourceException e) {
try {
return MessageFormat.format(messageRBjavac.getString("javac." + key),
(Object[]) args);
} catch (MissingResourceException f) {
String msg = "apt or javac message file broken: key={0} "
+ "arguments={1}, {2}";
return MessageFormat.format(msg, (Object[]) args);
}
}
}
}
| 47,549 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AptJavaCompiler.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/main/AptJavaCompiler.java | /*
* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.main;
import java.io.*;
import java.util.Map;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.apt.comp.*;
import com.sun.tools.apt.util.Bark;
import com.sun.mirror.apt.AnnotationProcessorFactory;
import com.sun.tools.javac.parser.DocCommentScanner;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b>
*/
@SuppressWarnings("deprecation")
public class AptJavaCompiler extends com.sun.tools.javac.main.JavaCompiler {
/** The context key for the compiler. */
protected static final Context.Key<AptJavaCompiler> compilerKey =
new Context.Key<AptJavaCompiler>();
/** Get the JavaCompiler instance for this context. */
public static AptJavaCompiler instance(Context context) {
AptJavaCompiler instance = context.get(compilerKey);
if (instance == null)
instance = new AptJavaCompiler(context);
return instance;
}
java.util.Set<String> genSourceFileNames;
java.util.Set<String> genClassFileNames;
public java.util.Set<String> getSourceFileNames() {
return genSourceFileNames;
}
/** List of names of generated class files.
*/
public java.util.Set<String> getClassFileNames() {
return genClassFileNames;
}
java.util.Set<java.io.File> aggregateGenFiles = java.util.Collections.emptySet();
public java.util.Set<java.io.File> getAggregateGenFiles() {
return aggregateGenFiles;
}
/** The bark to be used for error reporting.
*/
Bark bark;
/** The log to be used for error reporting.
*/
Log log;
/** The annotation framework
*/
Apt apt;
private static Context preRegister(Context context) {
Bark.preRegister(context);
if (context.get(JavaFileManager.class) == null)
JavacFileManager.preRegister(context);
return context;
}
/** Construct a new compiler from a shared context.
*/
public AptJavaCompiler(Context context) {
super(preRegister(context));
context.put(compilerKey, this);
apt = Apt.instance(context);
ClassReader classReader = ClassReader.instance(context);
classReader.preferSource = true;
// TEMPORARY NOTE: bark==log, but while refactoring, we maintain their
// original identities, to remember the original intent.
log = Log.instance(context);
bark = Bark.instance(context);
Options options = Options.instance(context);
classOutput = options.get("-retrofit") == null;
nocompile = options.get("-nocompile") != null;
print = options.get("-print") != null;
classesAsDecls= options.get("-XclassesAsDecls") != null;
genSourceFileNames = new java.util.LinkedHashSet<String>();
genClassFileNames = new java.util.LinkedHashSet<String>();
// this forces a copy of the line map to be kept in the tree,
// for use by com.sun.mirror.util.SourcePosition.
lineDebugInfo = true;
}
/* Switches:
*/
/** Emit class files. This switch is always set, except for the first
* phase of retrofitting, where signatures are parsed.
*/
public boolean classOutput;
/** The internal printing annotation processor should be used.
*/
public boolean print;
/** Compilation should not be done after annotation processing.
*/
public boolean nocompile;
/** Are class files being treated as declarations
*/
public boolean classesAsDecls;
/** Try to open input stream with given name.
* Report an error if this fails.
* @param filename The file name of the input stream to be opened.
*/
// PROVIDED FOR EXTREME BACKWARDS COMPATIBILITY
// There are some very obscure errors that can arise while translating
// the contents of a file from bytes to characters. In Tiger, these
// diagnostics were ignored. This method provides compatibility with
// that behavior. It would be better to honor those diagnostics, in which
// case, this method can be deleted.
@Override
public CharSequence readSource(JavaFileObject filename) {
try {
inputFiles.add(filename);
boolean prev = bark.setDiagnosticsIgnored(true);
try {
return filename.getCharContent(false);
}
finally {
bark.setDiagnosticsIgnored(prev);
}
} catch (IOException e) {
bark.error(Position.NOPOS, "cant.read.file", filename);
return null;
}
}
/** Parse contents of input stream.
* @param filename The name of the file from which input stream comes.
* @param input The input stream to be parsed.
*/
// PROVIDED FOR BACKWARDS COMPATIBILITY
// In Tiger, diagnostics from the scanner and parser were ignored.
// This method provides compatibility with that behavior.
// It would be better to honor those diagnostics, in which
// case, this method can be deleted.
@Override
protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
boolean prev = bark.setDiagnosticsIgnored(true);
try {
return super.parse(filename, content);
}
finally {
bark.setDiagnosticsIgnored(prev);
}
}
@Override
protected boolean keepComments() {
return true; // make doc comments available to mirror API impl.
}
/** Track when the JavaCompiler has been used to compile something. */
private boolean hasBeenUsed = false;
/** Main method: compile a list of files, return all compiled classes
* @param filenames The names of all files to be compiled.
*/
public List<ClassSymbol> compile(List<String> filenames,
Map<String, String> origOptions,
ClassLoader aptCL,
AnnotationProcessorFactory providedFactory,
java.util.Set<Class<? extends AnnotationProcessorFactory> > productiveFactories,
java.util.Set<java.io.File> aggregateGenFiles)
throws Throwable {
// as a JavaCompiler can only be used once, throw an exception if
// it has been used before.
assert !hasBeenUsed : "attempt to reuse JavaCompiler";
hasBeenUsed = true;
this.aggregateGenFiles = aggregateGenFiles;
long msec = System.currentTimeMillis();
ListBuffer<ClassSymbol> classes = new ListBuffer<ClassSymbol>();
try {
JavacFileManager fm = (JavacFileManager)fileManager;
//parse all files
ListBuffer<JCCompilationUnit> trees = new ListBuffer<JCCompilationUnit>();
for (List<String> l = filenames; l.nonEmpty(); l = l.tail) {
if (classesAsDecls) {
if (! l.head.endsWith(".java") ) { // process as class file
ClassSymbol cs = reader.enterClass(names.fromString(l.head));
try {
cs.complete();
} catch(Symbol.CompletionFailure cf) {
bark.aptError("CantFindClass", l);
continue;
}
classes.append(cs); // add to list of classes
continue;
}
}
JavaFileObject fo = fm.getJavaFileObjectsFromStrings(List.of(l.head)).iterator().next();
trees.append(parse(fo));
}
//enter symbols for all files
List<JCCompilationUnit> roots = trees.toList();
if (errorCount() == 0) {
boolean prev = bark.setDiagnosticsIgnored(true);
try {
enter.main(roots);
}
finally {
bark.setDiagnosticsIgnored(prev);
}
}
if (errorCount() == 0) {
apt.main(roots,
classes,
origOptions, aptCL,
providedFactory,
productiveFactories);
genSourceFileNames.addAll(apt.getSourceFileNames());
genClassFileNames.addAll(apt.getClassFileNames());
}
} catch (Abort ex) {
}
if (verbose)
log.printVerbose("total", Long.toString(System.currentTimeMillis() - msec));
chk.reportDeferredDiagnostics();
printCount("error", errorCount());
printCount("warn", warningCount());
return classes.toList();
}
}
| 10,485 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
CommandLine.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/main/CommandLine.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.main;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.StreamTokenizer;
import com.sun.tools.javac.util.ListBuffer;
/**
* Various utility methods for processing Java tool command line arguments.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CommandLine {
/**
* Process Win32-style command files for the specified command line
* arguments and return the resulting arguments. A command file argument
* is of the form '@file' where 'file' is the name of the file whose
* contents are to be parsed for additional arguments. The contents of
* the command file are parsed using StreamTokenizer and the original
* '@file' argument replaced with the resulting tokens. Recursive command
* files are not supported. The '@' character itself can be quoted with
* the sequence '@@'.
*/
public static String[] parse(String[] args)
throws IOException
{
ListBuffer<String> newArgs = new ListBuffer<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.length() > 1 && arg.charAt(0) == '@') {
arg = arg.substring(1);
if (arg.charAt(0) == '@') {
newArgs.append(arg);
} else {
loadCmdFile(arg, newArgs);
}
} else {
newArgs.append(arg);
}
}
return newArgs.toList().toArray(new String[newArgs.length()]);
}
private static void loadCmdFile(String name, ListBuffer<String> args)
throws IOException
{
Reader r = new BufferedReader(new FileReader(name));
StreamTokenizer st = new StreamTokenizer(r);
st.resetSyntax();
st.wordChars(' ', 255);
st.whitespaceChars(0, ' ');
st.commentChar('#');
st.quoteChar('"');
st.quoteChar('\'');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
args.append(st.sval);
}
r.close();
}
}
| 3,525 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AptEnv.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/AptEnv.java | /*
* Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror;
import com.sun.tools.apt.mirror.declaration.DeclarationMaker;
import com.sun.tools.apt.mirror.type.TypeMaker;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;
/**
* The environment for a run of apt.
*/
@SuppressWarnings("deprecation")
public class AptEnv {
public Names names; // javac's name table
public Symtab symtab; // javac's predefined symbols
public Types jctypes; // javac's type utilities
public Enter enter; // javac's enter phase
public Attr attr; // javac's attr phase (to evaluate
// constant initializers)
public TypeMaker typeMaker; // apt's internal type utilities
public DeclarationMaker declMaker; // apt's internal declaration utilities
private static final Context.Key<AptEnv> aptEnvKey =
new Context.Key<AptEnv>();
public static AptEnv instance(Context context) {
AptEnv instance = context.get(aptEnvKey);
if (instance == null) {
instance = new AptEnv(context);
}
return instance;
}
private AptEnv(Context context) {
context.put(aptEnvKey, this);
names = Names.instance(context);
symtab = Symtab.instance(context);
jctypes = Types.instance(context);
enter = Enter.instance(context);
attr = Attr.instance(context);
typeMaker = TypeMaker.instance(context);
declMaker = DeclarationMaker.instance(context);
}
/**
* Does a symbol have a given flag? Forces symbol completion.
*/
public static boolean hasFlag(Symbol sym, long flag) {
return (getFlags(sym) & flag) != 0;
}
/**
* Returns a symbol's flags. Forces completion.
*/
public static long getFlags(Symbol sym) {
complete(sym);
return sym.flags();
}
/**
* Completes a symbol, ignoring completion failures.
*/
private static void complete(Symbol sym) {
while (true) {
try {
sym.complete();
return;
} catch (CompletionFailure e) {
// Should never see two in a row, but loop just to be sure.
}
}
}
}
| 3,722 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/DeclarationImpl.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Collection;
import java.util.EnumSet;
import javax.tools.JavaFileObject;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.apt.mirror.util.SourcePositionImpl;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Position;
import static com.sun.mirror.declaration.Modifier.*;
import static com.sun.tools.javac.code.Kinds.*;
/**
* Implementation of Declaration
*/
@SuppressWarnings("deprecation")
public abstract class DeclarationImpl implements Declaration {
protected final AptEnv env;
public final Symbol sym;
protected static final DeclarationFilter identityFilter =
new DeclarationFilter();
/**
* "sym" should be completed before this constructor is called.
*/
protected DeclarationImpl(AptEnv env, Symbol sym) {
this.env = env;
this.sym = sym;
}
/**
* {@inheritDoc}
* <p> ParameterDeclarationImpl overrides this implementation.
*/
public boolean equals(Object obj) {
if (obj instanceof DeclarationImpl) {
DeclarationImpl that = (DeclarationImpl) obj;
return sym == that.sym && env == that.env;
} else {
return false;
}
}
/**
* {@inheritDoc}
* <p> ParameterDeclarationImpl overrides this implementation.
*/
public int hashCode() {
return sym.hashCode() + env.hashCode();
}
/**
* {@inheritDoc}
*/
public String getDocComment() {
// Our doc comment is contained in a map in our toplevel,
// indexed by our tree. Find our enter environment, which gives
// us our toplevel. It also gives us a tree that contains our
// tree: walk it to find our tree. This is painful.
Env<AttrContext> enterEnv = getEnterEnv();
if (enterEnv == null)
return null;
JCTree tree = TreeInfo.declarationFor(sym, enterEnv.tree);
return enterEnv.toplevel.docComments.get(tree);
}
/**
* {@inheritDoc}
*/
public Collection<AnnotationMirror> getAnnotationMirrors() {
Collection<AnnotationMirror> res =
new ArrayList<AnnotationMirror>();
for (Attribute.Compound a : sym.getAnnotationMirrors()) {
res.add(env.declMaker.getAnnotationMirror(a, this));
}
return res;
}
/**
* {@inheritDoc}
* Overridden by ClassDeclarationImpl to handle @Inherited.
*/
public <A extends Annotation> A getAnnotation(Class<A> annoType) {
return getAnnotation(annoType, sym);
}
protected <A extends Annotation> A getAnnotation(Class<A> annoType,
Symbol annotated) {
if (!annoType.isAnnotation()) {
throw new IllegalArgumentException(
"Not an annotation type: " + annoType);
}
String name = annoType.getName();
for (Attribute.Compound attr : annotated.getAnnotationMirrors()) {
if (name.equals(attr.type.tsym.flatName().toString())) {
return AnnotationProxyMaker.generateAnnotation(env, attr,
annoType);
}
}
return null;
}
// Cache for modifiers.
private EnumSet<Modifier> modifiers = null;
/**
* {@inheritDoc}
*/
public Collection<Modifier> getModifiers() {
if (modifiers == null) {
modifiers = EnumSet.noneOf(Modifier.class);
long flags = AptEnv.getFlags(sym);
if (0 != (flags & Flags.PUBLIC)) modifiers.add(PUBLIC);
if (0 != (flags & Flags.PROTECTED)) modifiers.add(PROTECTED);
if (0 != (flags & Flags.PRIVATE)) modifiers.add(PRIVATE);
if (0 != (flags & Flags.ABSTRACT)) modifiers.add(ABSTRACT);
if (0 != (flags & Flags.STATIC)) modifiers.add(STATIC);
if (0 != (flags & Flags.FINAL)) modifiers.add(FINAL);
if (0 != (flags & Flags.TRANSIENT)) modifiers.add(TRANSIENT);
if (0 != (flags & Flags.VOLATILE)) modifiers.add(VOLATILE);
if (0 != (flags & Flags.SYNCHRONIZED)) modifiers.add(SYNCHRONIZED);
if (0 != (flags & Flags.NATIVE)) modifiers.add(NATIVE);
if (0 != (flags & Flags.STRICTFP)) modifiers.add(STRICTFP);
}
return modifiers;
}
/**
* {@inheritDoc}
* Overridden in some subclasses.
*/
public String getSimpleName() {
return sym.name.toString();
}
/**
* {@inheritDoc}
*/
public SourcePosition getPosition() {
// Find the toplevel. From there use a tree-walking utility
// that finds the tree for our symbol, and with it the position.
Env<AttrContext> enterEnv = getEnterEnv();
if (enterEnv == null)
return null;
JCTree.JCCompilationUnit toplevel = enterEnv.toplevel;
JavaFileObject sourcefile = toplevel.sourcefile;
if (sourcefile == null)
return null;
int pos = TreeInfo.positionFor(sym, toplevel);
return new SourcePositionImpl(sourcefile, pos, toplevel.lineMap);
}
/**
* Applies a visitor to this declaration.
*
* @param v the visitor operating on this declaration
*/
public void accept(DeclarationVisitor v) {
v.visitDeclaration(this);
}
private Collection<Symbol> members = null; // cache for getMembers()
/**
* Returns the symbols of type or package members (and constructors)
* that are not synthetic or otherwise unwanted.
* Caches the result if "cache" is true.
*/
protected Collection<Symbol> getMembers(boolean cache) {
if (members != null) {
return members;
}
LinkedList<Symbol> res = new LinkedList<Symbol>();
for (Scope.Entry e = sym.members().elems; e != null; e = e.sibling) {
if (e.sym != null && !unwanted(e.sym)) {
res.addFirst(e.sym);
}
}
return cache ? (members = res) : res;
}
/**
* Tests whether this is a symbol that should never be seen by clients,
* such as a synthetic class.
* Note that a class synthesized by the compiler may not be flagged as
* synthetic: see bugid 4959932.
*/
private static boolean unwanted(Symbol s) {
return AptEnv.hasFlag(s, Flags.SYNTHETIC) ||
(s.kind == TYP &&
!DeclarationMaker.isJavaIdentifier(s.name.toString()));
}
/**
* Returns this declaration's enter environment, or null if it
* has none.
*/
private Env<AttrContext> getEnterEnv() {
// Get enclosing class of sym, or sym itself if it is a class
// or package.
TypeSymbol ts = (sym.kind != PCK)
? sym.enclClass()
: (PackageSymbol) sym;
return (ts != null)
? env.enter.getEnv(ts)
: null;
}
}
| 8,707 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PackageDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/PackageDeclarationImpl.java | /*
* Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.ArrayList;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of PackageDeclaration.
*/
@SuppressWarnings("deprecation")
public class PackageDeclarationImpl extends DeclarationImpl
implements PackageDeclaration {
private PackageSymbol sym;
public PackageDeclarationImpl(AptEnv env, PackageSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns the qualified name.
*/
public String toString() {
return getQualifiedName();
}
/**
* {@inheritDoc}
*/
public String getQualifiedName() {
return sym.getQualifiedName().toString();
}
/**
* {@inheritDoc}
*/
public Collection<ClassDeclaration> getClasses() {
return identityFilter.filter(getAllTypes(),
ClassDeclaration.class);
}
/**
* {@inheritDoc}
*/
public Collection<EnumDeclaration> getEnums() {
return identityFilter.filter(getAllTypes(),
EnumDeclaration.class);
}
/**
* {@inheritDoc}
*/
public Collection<InterfaceDeclaration> getInterfaces() {
return identityFilter.filter(getAllTypes(),
InterfaceDeclaration.class);
}
/**
* {@inheritDoc}
*/
public Collection<AnnotationTypeDeclaration> getAnnotationTypes() {
return identityFilter.filter(getAllTypes(),
AnnotationTypeDeclaration.class);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitPackageDeclaration(this);
}
// Cache of all top-level type declarations in this package.
private Collection<TypeDeclaration> allTypes = null;
/**
* Caches and returns all top-level type declarations in this package.
* Omits synthetic types.
*/
private Collection<TypeDeclaration> getAllTypes() {
if (allTypes != null) {
return allTypes;
}
allTypes = new ArrayList<TypeDeclaration>();
for (Symbol s : getMembers(false)) {
allTypes.add(env.declMaker.getTypeDeclaration((ClassSymbol) s));
}
return allTypes;
}
}
| 3,738 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationMirrorImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationMirrorImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.LinkedHashMap;
import java.util.Map;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.AnnotationType;
import com.sun.mirror.util.SourcePosition;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Pair;
/**
* Implementation of AnnotationMirror
*/
@SuppressWarnings("deprecation")
public class AnnotationMirrorImpl implements AnnotationMirror {
protected final AptEnv env;
protected final Attribute.Compound anno;
protected final Declaration decl;
AnnotationMirrorImpl(AptEnv env, Attribute.Compound anno, Declaration decl) {
this.env = env;
this.anno = anno;
this.decl = decl;
}
/**
* Returns a string representation of this annotation.
* String is of one of the forms:
* @com.example.foo(name1=val1, name2=val2)
* @com.example.foo(val)
* @com.example.foo
* Omit parens for marker annotations, and omit "value=" when allowed.
*/
public String toString() {
StringBuilder sb = new StringBuilder("@");
Constants.Formatter fmtr = Constants.getFormatter(sb);
fmtr.append(anno.type.tsym);
int len = anno.values.length();
if (len > 0) { // omit parens for marker annotations
sb.append('(');
boolean first = true;
for (Pair<MethodSymbol, Attribute> val : anno.values) {
if (!first) {
sb.append(", ");
}
first = false;
Name name = val.fst.name;
if (len > 1 || name != env.names.value) {
fmtr.append(name);
sb.append('=');
}
sb.append(new AnnotationValueImpl(env, val.snd, this));
}
sb.append(')');
}
return fmtr.toString();
}
/**
* {@inheritDoc}
*/
public AnnotationType getAnnotationType() {
return (AnnotationType) env.typeMaker.getType(anno.type);
}
/**
* {@inheritDoc}
*/
public Map<AnnotationTypeElementDeclaration, AnnotationValue>
getElementValues() {
Map<AnnotationTypeElementDeclaration, AnnotationValue> res =
new LinkedHashMap<AnnotationTypeElementDeclaration,
AnnotationValue>(); // whew!
for (Pair<MethodSymbol, Attribute> val : anno.values) {
res.put(getElement(val.fst),
new AnnotationValueImpl(env, val.snd, this));
}
return res;
}
public SourcePosition getPosition() {
// Return position of the declaration on which this annotation
// appears.
return (decl == null) ? null : decl.getPosition();
}
public Declaration getDeclaration() {
return this.decl;
}
/**
* Returns the annotation type element for a symbol.
*/
private AnnotationTypeElementDeclaration getElement(MethodSymbol m) {
return (AnnotationTypeElementDeclaration)
env.declMaker.getExecutableDeclaration(m);
}
}
| 4,564 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ClassDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/ClassDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.util.ArrayList;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.ClassType;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of ClassDeclaration
*/
@SuppressWarnings("deprecation")
public class ClassDeclarationImpl extends TypeDeclarationImpl
implements ClassDeclaration {
ClassDeclarationImpl(AptEnv env, ClassSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
* Overridden here to handle @Inherited.
*/
public <A extends Annotation> A getAnnotation(Class<A> annoType) {
boolean inherited = annoType.isAnnotationPresent(Inherited.class);
for (Type t = sym.type;
t.tsym != env.symtab.objectType.tsym && !t.isErroneous();
t = env.jctypes.supertype(t)) {
A result = getAnnotation(annoType, t.tsym);
if (result != null || !inherited) {
return result;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public ClassType getSuperclass() {
// java.lang.Object has no superclass
if (sym == env.symtab.objectType.tsym) {
return null;
}
Type t = env.jctypes.supertype(sym.type);
return (ClassType) env.typeMaker.getType(t);
}
/**
* {@inheritDoc}
*/
public Collection<ConstructorDeclaration> getConstructors() {
ArrayList<ConstructorDeclaration> res =
new ArrayList<ConstructorDeclaration>();
for (Symbol s : getMembers(true)) {
if (s.isConstructor()) {
MethodSymbol m = (MethodSymbol) s;
res.add((ConstructorDeclaration)
env.declMaker.getExecutableDeclaration(m));
}
}
return res;
}
/**
* {@inheritDoc}
*/
public Collection<MethodDeclaration> getMethods() {
return identityFilter.filter(super.getMethods(),
MethodDeclaration.class);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitClassDeclaration(this);
}
}
| 3,666 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/TypeDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.Name;
/**
* Implementation of TypeDeclaration
*/
@SuppressWarnings("deprecation")
public class TypeDeclarationImpl extends MemberDeclarationImpl
implements TypeDeclaration {
public ClassSymbol sym;
/**
* "sym" should be completed before this constructor is called.
*/
protected TypeDeclarationImpl(AptEnv env, ClassSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns the type's name, with any type parameters (including those
* of outer classes). Type names are qualified.
*/
public String toString() {
return toString(env, sym);
}
/**
* {@inheritDoc}
*/
public PackageDeclaration getPackage() {
return env.declMaker.getPackageDeclaration(sym.packge());
}
/**
* {@inheritDoc}
*/
public String getQualifiedName() {
return sym.toString();
}
/**
* {@inheritDoc}
*/
public Collection<InterfaceType> getSuperinterfaces() {
return env.typeMaker.getTypes(env.jctypes.interfaces(sym.type),
InterfaceType.class);
}
/**
* {@inheritDoc}
*/
public Collection<FieldDeclaration> getFields() {
ArrayList<FieldDeclaration> res = new ArrayList<FieldDeclaration>();
for (Symbol s : getMembers(true)) {
if (s.kind == Kinds.VAR) {
res.add(env.declMaker.getFieldDeclaration((VarSymbol) s));
}
}
return res;
}
/**
* {@inheritDoc}
*/
public Collection<? extends MethodDeclaration> getMethods() {
ArrayList<MethodDeclaration> res = new ArrayList<MethodDeclaration>();
for (Symbol s : getMembers(true)) {
if (s.kind == Kinds.MTH && !s.isConstructor() &&
!env.names.clinit.equals(s.name) ) { // screen out static initializers
MethodSymbol m = (MethodSymbol) s;
res.add((MethodDeclaration)
env.declMaker.getExecutableDeclaration(m));
}
}
return res;
}
/**
* {@inheritDoc}
*/
public Collection<TypeDeclaration> getNestedTypes() {
ArrayList<TypeDeclaration> res = new ArrayList<TypeDeclaration>();
for (Symbol s : getMembers(true)) {
if (s.kind == Kinds.TYP) {
res.add(env.declMaker.getTypeDeclaration((ClassSymbol) s));
}
}
return res;
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitTypeDeclaration(this);
}
/**
* Returns a type's name, with any type parameters (including those
* of outer classes). Type names are qualified.
*/
static String toString(AptEnv env, ClassSymbol c) {
StringBuilder sb = new StringBuilder();
if (c.isInner()) {
// c is an inner class, so include type params of outer.
ClassSymbol enclosing = c.owner.enclClass();
sb.append(toString(env, enclosing))
.append('.')
.append(c.name);
} else {
sb.append(c);
}
sb.append(typeParamsToString(env, c));
return sb.toString();
}
}
| 4,863 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
EnumConstantDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/EnumConstantDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.VarSymbol;
/**
* Implementation of EnumConstantDeclaration
*/
@SuppressWarnings("deprecation")
public class EnumConstantDeclarationImpl extends FieldDeclarationImpl
implements EnumConstantDeclaration {
EnumConstantDeclarationImpl(AptEnv env, VarSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public EnumDeclaration getDeclaringType() {
return (EnumDeclaration) super.getDeclaringType();
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitEnumConstantDeclaration(this);
}
}
| 2,049 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ConstructorDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/ConstructorDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.ArrayList;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* Implementation of ConstructorDeclaration
*/
@SuppressWarnings("deprecation")
public class ConstructorDeclarationImpl extends ExecutableDeclarationImpl
implements ConstructorDeclaration {
ConstructorDeclarationImpl(AptEnv env, MethodSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
* Returns the simple name of the declaring class.
*/
public String getSimpleName() {
return sym.enclClass().name.toString();
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitConstructorDeclaration(this);
}
}
| 2,184 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationValueImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationValueImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.SourcePosition;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.TypeTags;
/**
* Implementation of AnnotationValue
*/
@SuppressWarnings("deprecation")
public class AnnotationValueImpl implements AnnotationValue {
protected final AptEnv env;
protected final Attribute attr;
protected final AnnotationMirrorImpl annotation;
AnnotationValueImpl(AptEnv env, Attribute attr, AnnotationMirrorImpl annotation) {
this.env = env;
this.attr = attr;
this.annotation = annotation;
}
/**
* {@inheritDoc}
*/
public String toString() {
StringBuilder sb = new StringBuilder();
Constants.Formatter fmtr = Constants.getFormatter(sb);
fmtr.append(getValue());
return fmtr.toString();
}
/**
* {@inheritDoc}
*/
public Object getValue() {
ValueVisitor vv = new ValueVisitor();
attr.accept(vv);
return vv.value;
}
public SourcePosition getPosition() {
// Imprecise implementation; just return position of enclosing
// annotation.
return (annotation == null) ? null : annotation.getPosition();
}
private class ValueVisitor implements Attribute.Visitor {
public Object value;
public void visitConstant(Attribute.Constant c) {
value = Constants.decodeConstant(c.value, c.type);
}
public void visitClass(Attribute.Class c) {
value = env.typeMaker.getType(
env.jctypes.erasure(c.type));
}
public void visitEnum(Attribute.Enum e) {
value = env.declMaker.getFieldDeclaration(e.value);
}
public void visitCompound(Attribute.Compound c) {
value = new AnnotationMirrorImpl(env, c,
(annotation == null) ?
null :
annotation.getDeclaration());
}
public void visitArray(Attribute.Array a) {
ArrayList<AnnotationValue> vals =
new ArrayList<AnnotationValue>(a.values.length);
for (Attribute elem : a.values) {
vals.add(new AnnotationValueImpl(env, elem, annotation));
}
value = vals;
}
public void visitError(Attribute.Error e) {
value = "<error>"; // javac will already have logged an error msg
}
}
}
| 3,957 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MemberDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/MemberDeclarationImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
/**
* Implementation of MemberDeclaration
*/
@SuppressWarnings("deprecation")
public abstract class MemberDeclarationImpl extends DeclarationImpl
implements MemberDeclaration {
protected MemberDeclarationImpl(AptEnv env, Symbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public TypeDeclaration getDeclaringType() {
ClassSymbol c = getDeclaringClassSymbol();
return (c == null)
? null
: env.declMaker.getTypeDeclaration(c);
}
/**
* {@inheritDoc}
* For methods, constructors, and types.
*/
public Collection<TypeParameterDeclaration> getFormalTypeParameters() {
ArrayList<TypeParameterDeclaration> res =
new ArrayList<TypeParameterDeclaration>();
for (Type t : sym.type.getTypeArguments()) {
res.add(env.declMaker.getTypeParameterDeclaration(t.tsym));
}
return res;
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitMemberDeclaration(this);
}
/**
* Returns the ClassSymbol of the declaring type,
* or null if this is a top-level type.
*/
private ClassSymbol getDeclaringClassSymbol() {
return sym.owner.enclClass();
}
/**
* Returns the formal type parameters of a type, member or constructor
* as an angle-bracketed string. Each parameter consists of the simple
* type variable name and any bounds (with no implicit "extends Object"
* clause added). Type names are qualified.
* Returns "" if there are no type parameters.
*/
protected static String typeParamsToString(AptEnv env, Symbol sym) {
if (sym.type.getTypeArguments().isEmpty()) {
return "";
}
StringBuilder s = new StringBuilder();
for (Type t : sym.type.getTypeArguments()) {
Type.TypeVar tv = (Type.TypeVar) t;
s.append(s.length() == 0 ? "<" : ", ")
.append(TypeParameterDeclarationImpl.toString(env, tv));
}
s.append(">");
return s.toString();
}
}
| 3,744 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
EnumDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/EnumDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of EnumDeclaration
*/
@SuppressWarnings("deprecation")
public class EnumDeclarationImpl extends ClassDeclarationImpl
implements EnumDeclaration {
EnumDeclarationImpl(AptEnv env, ClassSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public Collection<EnumConstantDeclaration> getEnumConstants() {
return identityFilter.filter(getFields(),
EnumConstantDeclaration.class);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitEnumDeclaration(this);
}
}
| 2,089 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ExecutableDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/ExecutableDeclarationImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.ReferenceType;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of ExecutableDeclaration
*/
@SuppressWarnings("deprecation")
public abstract class ExecutableDeclarationImpl extends MemberDeclarationImpl
implements ExecutableDeclaration {
public MethodSymbol sym;
protected ExecutableDeclarationImpl(AptEnv env, MethodSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns type parameters (if any), method name, and signature
* (value parameter types).
*/
public String toString() {
return sym.toString();
}
/**
* {@inheritDoc}
*/
public boolean isVarArgs() {
return AptEnv.hasFlag(sym, Flags.VARARGS);
}
/**
* {@inheritDoc}
*/
public Collection<ParameterDeclaration> getParameters() {
Collection<ParameterDeclaration> res =
new ArrayList<ParameterDeclaration>();
for (VarSymbol param : sym.params())
res.add(env.declMaker.getParameterDeclaration(param));
return res;
}
/**
* {@inheritDoc}
*/
public Collection<ReferenceType> getThrownTypes() {
ArrayList<ReferenceType> res = new ArrayList<ReferenceType>();
for (Type t : sym.type.getThrownTypes()) {
res.add((ReferenceType) env.typeMaker.getType(t));
}
return res;
}
}
| 2,884 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MethodDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/MethodDeclarationImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.mirror.type.TypeMirror;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* Implementation of MethodDeclaration
*/
@SuppressWarnings("deprecation")
public class MethodDeclarationImpl extends ExecutableDeclarationImpl
implements MethodDeclaration {
MethodDeclarationImpl(AptEnv env, MethodSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public TypeMirror getReturnType() {
return env.typeMaker.getType(sym.type.getReturnType());
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitMethodDeclaration(this);
}
}
| 2,067 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DeclarationMaker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/DeclarationMaker.java | /*
* Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.HashMap;
import java.util.Map;
import com.sun.mirror.declaration.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.main.JavaCompiler;
/**
* Utilities for constructing and caching declarations.
*/
@SuppressWarnings("deprecation")
public class DeclarationMaker {
private AptEnv env;
private Context context;
private JavaCompiler javacompiler;
private static final Context.Key<DeclarationMaker> declarationMakerKey =
new Context.Key<DeclarationMaker>();
public static DeclarationMaker instance(Context context) {
DeclarationMaker instance = context.get(declarationMakerKey);
if (instance == null) {
instance = new DeclarationMaker(context);
}
return instance;
}
private DeclarationMaker(Context context) {
context.put(declarationMakerKey, this);
env = AptEnv.instance(context);
this.context = context;
this.javacompiler = JavaCompiler.instance(context);
}
// Cache of package declarations
private Map<PackageSymbol, PackageDeclaration> packageDecls =
new HashMap<PackageSymbol, PackageDeclaration>();
/**
* Returns the package declaration for a package symbol.
*/
public PackageDeclaration getPackageDeclaration(PackageSymbol p) {
PackageDeclaration res = packageDecls.get(p);
if (res == null) {
res = new PackageDeclarationImpl(env, p);
packageDecls.put(p, res);
}
return res;
}
/**
* Returns the package declaration for the package with the given name.
* Name is fully-qualified, or "" for the unnamed package.
* Returns null if package declaration not found.
*/
public PackageDeclaration getPackageDeclaration(String name) {
PackageSymbol p = null;
if (name.equals("") )
p = env.symtab.unnamedPackage;
else {
if (!isJavaName(name))
return null;
Symbol s = nameToSymbol(name, false);
if (s instanceof PackageSymbol) {
p = (PackageSymbol) s;
if (!p.exists())
return null;
} else
return null;
}
return getPackageDeclaration(p);
}
// Cache of type declarations
private Map<ClassSymbol, TypeDeclaration> typeDecls =
new HashMap<ClassSymbol, TypeDeclaration>();
/**
* Returns the type declaration for a class symbol.
* Forces completion, and returns null on error.
*/
public TypeDeclaration getTypeDeclaration(ClassSymbol c) {
long flags = AptEnv.getFlags(c); // forces symbol completion
if (c.kind == Kinds.ERR) {
return null;
}
TypeDeclaration res = typeDecls.get(c);
if (res == null) {
if ((flags & Flags.ANNOTATION) != 0) {
res = new AnnotationTypeDeclarationImpl(env, c);
} else if ((flags & Flags.INTERFACE) != 0) {
res = new InterfaceDeclarationImpl(env, c);
} else if ((flags & Flags.ENUM) != 0) {
res = new EnumDeclarationImpl(env, c);
} else {
res = new ClassDeclarationImpl(env, c);
}
typeDecls.put(c, res);
}
return res;
}
/**
* Returns the type declaration for the type with the given canonical name.
* Returns null if type declaration not found.
*/
public TypeDeclaration getTypeDeclaration(String name) {
if (!isJavaName(name))
return null;
Symbol s = nameToSymbol(name, true);
if (s instanceof ClassSymbol) {
ClassSymbol c = (ClassSymbol) s;
return getTypeDeclaration(c);
} else
return null;
}
/**
* Returns a symbol given the type's or packages's canonical name,
* or null if the name isn't found.
*/
private Symbol nameToSymbol(String name, boolean classCache) {
Symbol s = null;
Name nameName = env.names.fromString(name);
if (classCache)
s = env.symtab.classes.get(nameName);
else
s = env.symtab.packages.get(nameName);
if (s != null && s.exists())
return s;
s = javacompiler.resolveIdent(name);
if (s.kind == Kinds.ERR )
return null;
if (s.kind == Kinds.PCK)
s.complete();
return s;
}
// Cache of method and constructor declarations
private Map<MethodSymbol, ExecutableDeclaration> executableDecls =
new HashMap<MethodSymbol, ExecutableDeclaration>();
/**
* Returns the method or constructor declaration for a method symbol.
*/
ExecutableDeclaration getExecutableDeclaration(MethodSymbol m) {
ExecutableDeclaration res = executableDecls.get(m);
if (res == null) {
if (m.isConstructor()) {
res = new ConstructorDeclarationImpl(env, m);
} else if (isAnnotationTypeElement(m)) {
res = new AnnotationTypeElementDeclarationImpl(env, m);
} else {
res = new MethodDeclarationImpl(env, m);
}
executableDecls.put(m, res);
}
return res;
}
// Cache of field declarations
private Map<VarSymbol, FieldDeclaration> fieldDecls =
new HashMap<VarSymbol, FieldDeclaration>();
/**
* Returns the field declaration for a var symbol.
*/
FieldDeclaration getFieldDeclaration(VarSymbol v) {
FieldDeclaration res = fieldDecls.get(v);
if (res == null) {
if (hasFlag(v, Flags.ENUM)) {
res = new EnumConstantDeclarationImpl(env, v);
} else {
res = new FieldDeclarationImpl(env, v);
}
fieldDecls.put(v, res);
}
return res;
}
/**
* Returns a parameter declaration.
*/
ParameterDeclaration getParameterDeclaration(VarSymbol v) {
return new ParameterDeclarationImpl(env, v);
}
/**
* Returns a type parameter declaration.
*/
public TypeParameterDeclaration getTypeParameterDeclaration(TypeSymbol t) {
return new TypeParameterDeclarationImpl(env, t);
}
/**
* Returns an annotation.
*/
AnnotationMirror getAnnotationMirror(Attribute.Compound a, Declaration decl) {
return new AnnotationMirrorImpl(env, a, decl);
}
/**
* Is a string a valid Java identifier?
*/
public static boolean isJavaIdentifier(String id) {
return javax.lang.model.SourceVersion.isIdentifier(id);
}
public static boolean isJavaName(String name) {
for(String id: name.split("\\.")) {
if (! isJavaIdentifier(id))
return false;
}
return true;
}
/**
* Is a method an annotation type element?
* It is if it's declared in an annotation type.
*/
private static boolean isAnnotationTypeElement(MethodSymbol m) {
return hasFlag(m.enclClass(), Flags.ANNOTATION);
}
/**
* Does a symbol have a given flag?
*/
private static boolean hasFlag(Symbol s, long flag) {
return AptEnv.hasFlag(s, flag);
}
}
| 8,765 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FieldDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/FieldDeclarationImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.TypeMirror;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.TypeTags;
/**
* Implementation of FieldDeclaration
*/
@SuppressWarnings("deprecation")
class FieldDeclarationImpl extends MemberDeclarationImpl
implements FieldDeclaration {
protected VarSymbol sym;
FieldDeclarationImpl(AptEnv env, VarSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns the field's name.
*/
public String toString() {
return getSimpleName();
}
/**
* {@inheritDoc}
*/
public TypeMirror getType() {
return env.typeMaker.getType(sym.type);
}
/**
* {@inheritDoc}
*/
public Object getConstantValue() {
Object val = sym.getConstValue();
// val may be null, indicating that this is not a constant.
return Constants.decodeConstant(val, sym.type);
}
/**
* {@inheritDoc}
*/
public String getConstantExpression() {
Object val = getConstantValue();
if (val == null) {
return null;
}
Constants.Formatter fmtr = Constants.getFormatter();
fmtr.append(val);
return fmtr.toString();
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitFieldDeclaration(this);
}
}
| 2,847 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationTypeDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of AnnotationTypeDeclaration
*/
@SuppressWarnings("deprecation")
public class AnnotationTypeDeclarationImpl extends InterfaceDeclarationImpl
implements AnnotationTypeDeclaration
{
AnnotationTypeDeclarationImpl(AptEnv env, ClassSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public Collection<AnnotationTypeElementDeclaration> getMethods() {
return identityFilter.filter(super.getMethods(),
AnnotationTypeElementDeclaration.class);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitAnnotationTypeDeclaration(this);
}
}
| 2,188 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationProxyMaker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationProxyMaker.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.lang.annotation.*;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.*;
import sun.reflect.annotation.*;
import com.sun.mirror.type.TypeMirror;
import com.sun.mirror.type.MirroredTypeException;
import com.sun.mirror.type.MirroredTypesException;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Pair;
/**
* A generator of dynamic proxy implementations of
* java.lang.annotation.Annotation.
*
* <p> The "dynamic proxy return form" of an attribute element value is
* the form used by sun.reflect.annotation.AnnotationInvocationHandler.
*/
@SuppressWarnings("deprecation")
class AnnotationProxyMaker {
private final AptEnv env;
private final Attribute.Compound attrs;
private final Class<? extends Annotation> annoType;
private AnnotationProxyMaker(AptEnv env,
Attribute.Compound attrs,
Class<? extends Annotation> annoType) {
this.env = env;
this.attrs = attrs;
this.annoType = annoType;
}
/**
* Returns a dynamic proxy for an annotation mirror.
*/
public static <A extends Annotation> A generateAnnotation(
AptEnv env, Attribute.Compound attrs, Class<A> annoType) {
AnnotationProxyMaker apm = new AnnotationProxyMaker(env, attrs, annoType);
return annoType.cast(apm.generateAnnotation());
}
/**
* Returns a dynamic proxy for an annotation mirror.
*/
private Annotation generateAnnotation() {
return AnnotationParser.annotationForMap(annoType,
getAllReflectedValues());
}
/**
* Returns a map from element names to their values in "dynamic
* proxy return form". Includes all elements, whether explicit or
* defaulted.
*/
private Map<String, Object> getAllReflectedValues() {
Map<String, Object> res = new LinkedHashMap<String, Object>();
for (Map.Entry<MethodSymbol, Attribute> entry :
getAllValues().entrySet()) {
MethodSymbol meth = entry.getKey();
Object value = generateValue(meth, entry.getValue());
if (value != null) {
res.put(meth.name.toString(), value);
} else {
// Ignore this element. May lead to
// IncompleteAnnotationException somewhere down the line.
}
}
return res;
}
/**
* Returns a map from element symbols to their values.
* Includes all elements, whether explicit or defaulted.
*/
private Map<MethodSymbol, Attribute> getAllValues() {
Map<MethodSymbol, Attribute> res =
new LinkedHashMap<MethodSymbol, Attribute>();
// First find the default values.
ClassSymbol sym = (ClassSymbol) attrs.type.tsym;
for (Scope.Entry e = sym.members().elems; e != null; e = e.sibling) {
if (e.sym.kind == Kinds.MTH) {
MethodSymbol m = (MethodSymbol) e.sym;
Attribute def = m.defaultValue;
if (def != null) {
res.put(m, def);
}
}
}
// Next find the explicit values, possibly overriding defaults.
for (Pair<MethodSymbol, Attribute> p : attrs.values) {
res.put(p.fst, p.snd);
}
return res;
}
/**
* Converts an element value to its "dynamic proxy return form".
* Returns an exception proxy on some errors, but may return null if
* a useful exception cannot or should not be generated at this point.
*/
private Object generateValue(MethodSymbol meth, Attribute attr) {
ValueVisitor vv = new ValueVisitor(meth);
return vv.getValue(attr);
}
private class ValueVisitor implements Attribute.Visitor {
private MethodSymbol meth; // annotation element being visited
private Class<?> runtimeType; // runtime type of annotation element
private Object value; // value in "dynamic proxy return form"
ValueVisitor(MethodSymbol meth) {
this.meth = meth;
}
Object getValue(Attribute attr) {
Method method; // runtime method of annotation element
try {
method = annoType.getMethod(meth.name.toString());
} catch (NoSuchMethodException e) {
return null;
}
runtimeType = method.getReturnType();
attr.accept(this);
if (!(value instanceof ExceptionProxy) &&
!AnnotationType.invocationHandlerReturnType(runtimeType)
.isInstance(value)) {
typeMismatch(method, attr);
}
return value;
}
public void visitConstant(Attribute.Constant c) {
value = Constants.decodeConstant(c.value, c.type);
}
public void visitClass(Attribute.Class c) {
value = new MirroredTypeExceptionProxy(
env.typeMaker.getType(c.type));
}
public void visitArray(Attribute.Array a) {
Type elemtype = env.jctypes.elemtype(a.type);
if (elemtype.tsym == env.symtab.classType.tsym) { // Class[]
// Construct a proxy for a MirroredTypesException
ArrayList<TypeMirror> elems = new ArrayList<TypeMirror>();
for (int i = 0; i < a.values.length; i++) {
Type elem = ((Attribute.Class) a.values[i]).type;
elems.add(env.typeMaker.getType(elem));
}
value = new MirroredTypesExceptionProxy(elems);
} else {
int len = a.values.length;
Class<?> runtimeTypeSaved = runtimeType;
runtimeType = runtimeType.getComponentType();
try {
Object res = Array.newInstance(runtimeType, len);
for (int i = 0; i < len; i++) {
a.values[i].accept(this);
if (value == null || value instanceof ExceptionProxy) {
return;
}
try {
Array.set(res, i, value);
} catch (IllegalArgumentException e) {
value = null; // indicates a type mismatch
return;
}
}
value = res;
} finally {
runtimeType = runtimeTypeSaved;
}
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void visitEnum(Attribute.Enum e) {
if (runtimeType.isEnum()) {
String constName = e.value.toString();
try {
value = Enum.valueOf((Class)runtimeType, constName);
} catch (IllegalArgumentException ex) {
value = new EnumConstantNotPresentExceptionProxy(
(Class<Enum<?>>)runtimeType, constName);
}
} else {
value = null; // indicates a type mismatch
}
}
public void visitCompound(Attribute.Compound c) {
try {
Class<? extends Annotation> nested =
runtimeType.asSubclass(Annotation.class);
value = generateAnnotation(env, c, nested);
} catch (ClassCastException ex) {
value = null; // indicates a type mismatch
}
}
public void visitError(Attribute.Error e) {
value = null; // indicates a type mismatch
}
/**
* Sets "value" to an ExceptionProxy indicating a type mismatch.
*/
private void typeMismatch(Method method, final Attribute attr) {
class AnnotationTypeMismatchExceptionProxy extends ExceptionProxy {
private static final long serialVersionUID = 8473323277815075163L;
transient final Method method;
AnnotationTypeMismatchExceptionProxy(Method method) {
this.method = method;
}
public String toString() {
return "<error>"; // eg: @Anno(value=<error>)
}
protected RuntimeException generateException() {
return new AnnotationTypeMismatchException(method,
attr.type.toString());
}
}
value = new AnnotationTypeMismatchExceptionProxy(method);
}
}
/**
* ExceptionProxy for MirroredTypeException.
* The toString, hashCode, and equals methods foward to the underlying
* type.
*/
private static final class MirroredTypeExceptionProxy extends ExceptionProxy {
private static final long serialVersionUID = 6662035281599933545L;
private MirroredTypeException ex;
MirroredTypeExceptionProxy(TypeMirror t) {
// It would be safer if we could construct the exception in
// generateException(), but there would be no way to do
// that properly following deserialization.
ex = new MirroredTypeException(t);
}
public String toString() {
return ex.getQualifiedName();
}
public int hashCode() {
TypeMirror t = ex.getTypeMirror();
return (t != null)
? t.hashCode()
: ex.getQualifiedName().hashCode();
}
public boolean equals(Object obj) {
TypeMirror t = ex.getTypeMirror();
return t != null &&
obj instanceof MirroredTypeExceptionProxy &&
t.equals(
((MirroredTypeExceptionProxy) obj).ex.getTypeMirror());
}
protected RuntimeException generateException() {
return (RuntimeException) ex.fillInStackTrace();
}
}
/**
* ExceptionProxy for MirroredTypesException.
* The toString, hashCode, and equals methods foward to the underlying
* types.
*/
private static final class MirroredTypesExceptionProxy extends ExceptionProxy {
private static final long serialVersionUID = -6670822532616693951L;
private MirroredTypesException ex;
MirroredTypesExceptionProxy(Collection<TypeMirror> ts) {
// It would be safer if we could construct the exception in
// generateException(), but there would be no way to do
// that properly following deserialization.
ex = new MirroredTypesException(ts);
}
public String toString() {
return ex.getQualifiedNames().toString();
}
public int hashCode() {
Collection<TypeMirror> ts = ex.getTypeMirrors();
return (ts != null)
? ts.hashCode()
: ex.getQualifiedNames().hashCode();
}
public boolean equals(Object obj) {
Collection<TypeMirror> ts = ex.getTypeMirrors();
return ts != null &&
obj instanceof MirroredTypesExceptionProxy &&
ts.equals(
((MirroredTypesExceptionProxy) obj).ex.getTypeMirrors());
}
protected RuntimeException generateException() {
return (RuntimeException) ex.fillInStackTrace();
}
}
}
| 13,170 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Constants.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/Constants.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.TypeMirror;
import com.sun.tools.apt.mirror.type.TypeMirrorImpl;
import com.sun.tools.javac.code.Type;
import static com.sun.tools.javac.code.TypeTags.*;
/**
* Utility class for operating on constant expressions.
*/
@SuppressWarnings("deprecation")
class Constants {
/**
* Converts a constant in javac's internal representation (in which
* boolean, char, byte, short, and int are each represented by an Integer)
* into standard representation. Other values (including null) are
* returned unchanged.
*/
static Object decodeConstant(Object value, Type type) {
if (value instanceof Integer) {
int i = ((Integer) value).intValue();
switch (type.tag) {
case BOOLEAN: return Boolean.valueOf(i != 0);
case CHAR: return Character.valueOf((char) i);
case BYTE: return Byte.valueOf((byte) i);
case SHORT: return Short.valueOf((short) i);
}
}
return value;
}
/**
* Returns a formatter for generating the text of constant
* expressions. Equivalent to
* <tt>getFormatter(new StringBuilder())</tt>.
*/
static Formatter getFormatter() {
return new Formatter(new StringBuilder());
}
/**
* Returns a formatter for generating the text of constant
* expressions. Also generates the text of constant
* "pseudo-expressions" for annotations and array-valued
* annotation elements.
*
* @param buf where the expression is written
*/
static Formatter getFormatter(StringBuilder buf) {
return new Formatter(buf);
}
/**
* Utility class used to generate the text of constant
* expressions. Also generates the text of constant
* "pseudo-expressions" for annotations and array-valued
* annotation elements.
*/
static class Formatter {
private StringBuilder buf; // where the output goes
private Formatter(StringBuilder buf) {
this.buf = buf;
}
public String toString() {
return buf.toString();
}
/**
* Appends a constant whose type is not statically known
* by dispatching to the appropriate overloaded append method.
*/
void append(Object val) {
if (val instanceof String) {
append((String) val);
} else if (val instanceof Character) {
append((Character) val);
} else if (val instanceof Boolean) {
append((Boolean) val);
} else if (val instanceof Byte) {
append((Byte) val);
} else if (val instanceof Short) {
append((Short) val);
} else if (val instanceof Integer) {
append((Integer) val);
} else if (val instanceof Long) {
append((Long) val);
} else if (val instanceof Float) {
append((Float) val);
} else if (val instanceof Double) {
append((Double) val);
} else if (val instanceof TypeMirror) {
append((TypeMirrorImpl) val);
} else if (val instanceof EnumConstantDeclaration) {
append((EnumConstantDeclarationImpl) val);
} else if (val instanceof AnnotationMirror) {
append((AnnotationMirrorImpl) val);
} else if (val instanceof Collection<?>) {
append((Collection<?>) val);
} else {
appendUnquoted(val.toString());
}
}
/**
* Appends a string, escaped (as needed) and quoted.
*/
void append(String val) {
buf.append('"');
appendUnquoted(val);
buf.append('"');
}
/**
* Appends a Character, escaped (as needed) and quoted.
*/
void append(Character val) {
buf.append('\'');
appendUnquoted(val.charValue());
buf.append('\'');
}
void append(Boolean val) {
buf.append(val);
}
void append(Byte val) {
buf.append(String.format("0x%02x", val));
}
void append(Short val) {
buf.append(val);
}
void append(Integer val) {
buf.append(val);
}
void append(Long val) {
buf.append(val).append('L');
}
void append(Float val) {
if (val.isNaN()) {
buf.append("0.0f/0.0f");
} else if (val.isInfinite()) {
if (val.floatValue() < 0) {
buf.append('-');
}
buf.append("1.0f/0.0f");
} else {
buf.append(val).append('f');
}
}
void append(Double val) {
if (val.isNaN()) {
buf.append("0.0/0.0");
} else if (val.isInfinite()) {
if (val.doubleValue() < 0) {
buf.append('-');
}
buf.append("1.0/0.0");
} else {
buf.append(val);
}
}
/**
* Appends the class literal corresponding to a type. Should
* only be invoked for types that have an associated literal.
* e.g: "java.lang.String.class"
* "boolean.class"
* "int[].class"
*/
void append(TypeMirrorImpl t) {
appendUnquoted(t.type.toString());
buf.append(".class");
}
/**
* Appends the fully qualified name of an enum constant.
* e.g: "java.math.RoundingMode.UP"
*/
void append(EnumConstantDeclarationImpl e) {
appendUnquoted(e.sym.enclClass() + "." + e);
}
/**
* Appends the text of an annotation pseudo-expression.
* e.g: "@pkg.Format(linesep='\n')"
*/
void append(AnnotationMirrorImpl anno) {
appendUnquoted(anno.toString());
}
/**
* Appends the elements of a collection, enclosed within braces
* and separated by ", ". Useful for array-valued annotation
* elements.
*/
void append(Collection<?> vals) {
buf.append('{');
boolean first = true;
for (Object val : vals) {
if (first) {
first = false;
} else {
buf.append(", ");
}
append(((AnnotationValue) val).getValue());
}
buf.append('}');
}
/**
* For each char of a string, append using appendUnquoted(char).
*/
private void appendUnquoted(String s) {
for (char c : s.toCharArray()) {
appendUnquoted(c);
}
}
/**
* Appends a char (unquoted), using escapes for those that are not
* printable ASCII. We don't know what is actually printable in
* the locale in which this result will be used, so ASCII is our
* best guess as to the least common denominator.
*/
private void appendUnquoted(char c) {
switch (c) {
case '\b': buf.append("\\b"); break;
case '\t': buf.append("\\t"); break;
case '\n': buf.append("\\n"); break;
case '\f': buf.append("\\f"); break;
case '\r': buf.append("\\r"); break;
case '\"': buf.append("\\\""); break;
case '\'': buf.append("\\\'"); break;
case '\\': buf.append("\\\\"); break;
default:
if (isPrintableAscii(c)) {
buf.append(c);
} else {
buf.append(String.format("\\u%04x", (int) c));
}
}
}
/**
* Is c a printable ASCII character?
*/
private static boolean isPrintableAscii(char c) {
return c >= ' ' && c <= '~';
}
}
}
| 9,515 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ParameterDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/ParameterDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.TypeMirror;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.VarSymbol;
/**
* Implementation of ParameterDeclaration
*/
@SuppressWarnings("deprecation")
public class ParameterDeclarationImpl extends DeclarationImpl
implements ParameterDeclaration
{
protected VarSymbol sym;
ParameterDeclarationImpl(AptEnv env, VarSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns the simple name of the parameter.
*/
public String toString() {
return getType() + " " + sym.name;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
// Neither ParameterDeclarationImpl objects nor their symbols
// are cached by the current implementation, so check symbol
// owners and names.
if (obj instanceof ParameterDeclarationImpl) {
ParameterDeclarationImpl that = (ParameterDeclarationImpl) obj;
return sym.owner == that.sym.owner &&
sym.name == that.sym.name &&
env == that.env;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return sym.owner.hashCode() + sym.name.hashCode() + env.hashCode();
}
/**
* {@inheritDoc}
*/
public TypeMirror getType() {
return env.typeMaker.getType(sym.type);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitParameterDeclaration(this);
}
}
| 3,025 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeParameterDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/TypeParameterDeclarationImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.ReferenceType;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of TypeParameterDeclaration
*/
@SuppressWarnings("deprecation")
public class TypeParameterDeclarationImpl extends DeclarationImpl
implements TypeParameterDeclaration
{
protected TypeSymbol sym;
TypeParameterDeclarationImpl(AptEnv env, TypeSymbol sym) {
super(env, sym);
this.sym = sym;
}
/**
* Returns the type parameter's name along with any "extends" clause.
* Class names are qualified. No implicit "extends Object" is added.
*/
public String toString() {
return toString(env, (Type.TypeVar) sym.type);
}
/**
* {@inheritDoc}
*/
public Collection<ReferenceType> getBounds() {
ArrayList<ReferenceType> res = new ArrayList<ReferenceType>();
for (Type t : env.jctypes.getBounds((Type.TypeVar) sym.type)) {
res.add((ReferenceType) env.typeMaker.getType(t));
}
return res;
}
/**
* {@inheritDoc}
*/
public Declaration getOwner() {
Symbol owner = sym.owner;
return ((owner.kind & Kinds.TYP) != 0)
? env.declMaker.getTypeDeclaration((ClassSymbol) owner)
: env.declMaker.getExecutableDeclaration((MethodSymbol) owner);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitTypeParameterDeclaration(this);
}
/**
* Returns the type parameter's name along with any "extends" clause.
* See {@link #toString()} for details.
*/
static String toString(AptEnv env, Type.TypeVar tv) {
StringBuilder s = new StringBuilder();
s.append(tv);
boolean first = true;
for (Type bound : getExtendsBounds(env, tv)) {
s.append(first ? " extends " : " & ");
s.append(env.typeMaker.typeToString(bound));
first = false;
}
return s.toString();
}
/**
* Returns the bounds of a type variable, eliding java.lang.Object
* if it appears alone.
*/
private static Iterable<Type> getExtendsBounds(AptEnv env,
Type.TypeVar tv) {
return (tv.getUpperBound().tsym == env.symtab.objectType.tsym)
? com.sun.tools.javac.util.List.<Type>nil()
: env.jctypes.getBounds(tv);
}
}
| 3,947 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
InterfaceDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/InterfaceDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of InterfaceDeclaration
*/
@SuppressWarnings("deprecation")
public class InterfaceDeclarationImpl extends TypeDeclarationImpl
implements InterfaceDeclaration {
InterfaceDeclarationImpl(AptEnv env, ClassSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitInterfaceDeclaration(this);
}
}
| 1,873 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeElementDeclarationImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/declaration/AnnotationTypeElementDeclarationImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.declaration;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.DeclarationVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* Implementation of AnnotationTypeElementDeclaration
*/
@SuppressWarnings("deprecation")
public class AnnotationTypeElementDeclarationImpl extends MethodDeclarationImpl
implements AnnotationTypeElementDeclaration {
AnnotationTypeElementDeclarationImpl(AptEnv env, MethodSymbol sym) {
super(env, sym);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeDeclaration getDeclaringType() {
return (AnnotationTypeDeclaration) super.getDeclaringType();
}
/**
* {@inheritDoc}
*/
public AnnotationValue getDefaultValue() {
return (sym.defaultValue == null)
? null
: new AnnotationValueImpl(env, sym.defaultValue, null);
}
/**
* {@inheritDoc}
*/
public void accept(DeclarationVisitor v) {
v.visitAnnotationTypeElementDeclaration(this);
}
}
| 2,340 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationProcessorEnvironmentImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/apt/AnnotationProcessorEnvironmentImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.apt;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.*;
import com.sun.mirror.apt.*;
import com.sun.tools.apt.mirror.apt.*;
import com.sun.tools.apt.mirror.declaration.DeclarationMaker;
import com.sun.tools.apt.mirror.util.*;
import com.sun.tools.apt.util.Bark;
import com.sun.tools.javac.util.Context;
import com.sun.tools.apt.mirror.apt.FilerImpl;
import com.sun.tools.apt.mirror.apt.MessagerImpl;
import com.sun.tools.apt.mirror.apt.RoundStateImpl;
import com.sun.tools.apt.mirror.apt.RoundCompleteEventImpl;
import com.sun.tools.javac.util.Context;
import java.util.*;
import static com.sun.mirror.util.DeclarationVisitors.*;
/*
* Annotation Processor Environment implementation.
*/
@SuppressWarnings("deprecation")
public class AnnotationProcessorEnvironmentImpl implements AnnotationProcessorEnvironment {
Collection<TypeDeclaration> spectypedecls;
Collection<TypeDeclaration> typedecls;
Map<String, String> origOptions;
DeclarationMaker declMaker;
Declarations declUtils;
Types typeUtils;
Messager messager;
FilerImpl filer;
Bark bark;
Set<RoundCompleteListener> roundCompleteListeners;
public AnnotationProcessorEnvironmentImpl(Collection<TypeDeclaration> spectypedecls,
Collection<TypeDeclaration> typedecls,
Map<String, String> origOptions,
Context context) {
// Safer to copy collections before applying unmodifiable
// wrapper.
this.spectypedecls = Collections.unmodifiableCollection(spectypedecls);
this.typedecls = Collections.unmodifiableCollection(typedecls);
this.origOptions = Collections.unmodifiableMap(origOptions);
declMaker = DeclarationMaker.instance(context);
declUtils = DeclarationsImpl.instance(context);
typeUtils = TypesImpl.instance(context);
messager = MessagerImpl.instance(context);
filer = FilerImpl.instance(context);
bark = Bark.instance(context);
roundCompleteListeners = new LinkedHashSet<RoundCompleteListener>();
}
public Map<String,String> getOptions() {
return origOptions;
}
public Messager getMessager() {
return messager;
}
public Filer getFiler() {
return filer;
}
public Collection<TypeDeclaration> getSpecifiedTypeDeclarations() {
return spectypedecls;
}
public PackageDeclaration getPackage(String name) {
return declMaker.getPackageDeclaration(name);
}
public TypeDeclaration getTypeDeclaration(String name) {
return declMaker.getTypeDeclaration(name);
}
public Collection<TypeDeclaration> getTypeDeclarations() {
return typedecls;
}
public Collection<Declaration> getDeclarationsAnnotatedWith(
AnnotationTypeDeclaration a) {
/*
* create collection of Declarations annotated with a given
* annotation.
*/
CollectingAP proc = new CollectingAP(this, a);
proc.process();
return proc.decls;
}
private static class CollectingAP implements AnnotationProcessor {
AnnotationProcessorEnvironment env;
Collection<Declaration> decls;
AnnotationTypeDeclaration atd;
CollectingAP(AnnotationProcessorEnvironment env,
AnnotationTypeDeclaration atd) {
this.env = env;
this.atd = atd;
decls = new HashSet<Declaration>();
}
private class CollectingVisitor extends SimpleDeclarationVisitor {
public void visitDeclaration(Declaration d) {
for(AnnotationMirror am: d.getAnnotationMirrors()) {
if (am.getAnnotationType().getDeclaration().equals(CollectingAP.this.atd))
CollectingAP.this.decls.add(d);
}
}
}
public void process() {
for(TypeDeclaration d: env.getSpecifiedTypeDeclarations())
d.accept(getSourceOrderDeclarationScanner(new CollectingVisitor(),
NO_OP));
}
}
public Declarations getDeclarationUtils() {
return declUtils;
}
public Types getTypeUtils() {
return typeUtils;
}
public void addListener(AnnotationProcessorListener listener) {
if (listener == null)
throw new NullPointerException();
else {
if (listener instanceof RoundCompleteListener)
roundCompleteListeners.add((RoundCompleteListener)listener);
}
}
public void removeListener(AnnotationProcessorListener listener) {
if (listener == null)
throw new NullPointerException();
else
roundCompleteListeners.remove(listener);
}
public void roundComplete() {
RoundState roundState = new RoundStateImpl(bark.nerrors > 0,
filer.getSourceFileNames().size() > 0,
filer.getClassFileNames().size() > 0,
origOptions);
RoundCompleteEvent roundCompleteEvent = new RoundCompleteEventImpl(this, roundState);
filer.roundOver();
for(RoundCompleteListener rcl: roundCompleteListeners)
rcl.roundComplete(roundCompleteEvent);
}
}
| 6,786 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RoundCompleteEventImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/apt/RoundCompleteEventImpl.java | /*
* Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.apt;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.apt.RoundCompleteEvent;
import com.sun.mirror.apt.RoundState;
@SuppressWarnings("deprecation")
public class RoundCompleteEventImpl extends RoundCompleteEvent {
private static final long serialVersionUID = 7067621446720784300L;
public RoundCompleteEventImpl(AnnotationProcessorEnvironment source,
RoundState rs) {
super(source, rs);
}
}
| 1,725 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
MessagerImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/apt/MessagerImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.apt;
import javax.tools.JavaFileObject;
import com.sun.mirror.apt.Messager;
import com.sun.tools.apt.mirror.util.SourcePositionImpl;
import com.sun.mirror.util.SourcePosition;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Position;
import com.sun.tools.apt.util.Bark;
/**
* Implementation of Messager.
*/
@SuppressWarnings("deprecation")
public class MessagerImpl implements Messager {
private final Bark bark;
private static final Context.Key<MessagerImpl> messagerKey =
new Context.Key<MessagerImpl>();
public static MessagerImpl instance(Context context) {
MessagerImpl instance = context.get(messagerKey);
if (instance == null) {
instance = new MessagerImpl(context);
}
return instance;
}
private MessagerImpl(Context context) {
context.put(messagerKey, this);
bark = Bark.instance(context);
}
/**
* {@inheritDoc}
*/
public void printError(String msg) {
bark.aptError("Messager", msg);
}
/**
* {@inheritDoc}
*/
public void printError(SourcePosition pos, String msg) {
if (pos instanceof SourcePositionImpl) {
SourcePositionImpl posImpl = (SourcePositionImpl) pos;
JavaFileObject prev = bark.useSource(posImpl.getSource());
bark.aptError(posImpl.getJavacPosition(), "Messager", msg);
bark.useSource(prev);
} else
printError(msg);
}
/**
* {@inheritDoc}
*/
public void printWarning(String msg) {
bark.aptWarning("Messager", msg);
}
/**
* {@inheritDoc}
*/
public void printWarning(SourcePosition pos, String msg) {
if (pos instanceof SourcePositionImpl) {
SourcePositionImpl posImpl = (SourcePositionImpl) pos;
JavaFileObject prev = bark.useSource(posImpl.getSource());
bark.aptWarning(posImpl.getJavacPosition(), "Messager", msg);
bark.useSource(prev);
} else
printWarning(msg);
}
/**
* {@inheritDoc}
*/
public void printNotice(String msg) {
bark.aptNote("Messager", msg);
}
/**
* {@inheritDoc}
*/
public void printNotice(SourcePosition pos, String msg) {
if (pos instanceof SourcePositionImpl) {
SourcePositionImpl posImpl = (SourcePositionImpl) pos;
JavaFileObject prev = bark.useSource(posImpl.getSource());
bark.aptNote(posImpl.getJavacPosition(), "Messager", msg);
bark.useSource(prev);
} else
printNotice(msg);
}
}
| 3,929 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
FilerImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/apt/FilerImpl.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.apt;
import java.io.*;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Set;
import com.sun.mirror.apt.Filer;
import com.sun.tools.apt.mirror.declaration.DeclarationMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.Position;
import com.sun.tools.apt.util.Bark;
import static com.sun.mirror.apt.Filer.Location.*;
/**
* Implementation of Filer.
*/
@SuppressWarnings("deprecation")
public class FilerImpl implements Filer {
/*
* The Filer class must maintain a number of constraints. First,
* multiple attempts to open the same path within the same
* invocation of apt results in an IOException being thrown. For
* example, trying to open the same source file twice:
*
* createSourceFile("foo.Bar")
* ...
* createSourceFile("foo.Bar")
*
* is disallowed as is opening a text file that happens to have
* the same name as a source file:
*
* createSourceFile("foo.Bar")
* ...
* createTextFile(SOURCE_TREE, "foo", new File("Bar"), null)
*
* Additionally, creating a source file that corresponds to an
* already created class file (or vice versa) generates at least a
* warning. This is an error if -XclassesAsDecls is being used
* since you can't create the same type twice. However, if the
* Filer is used to create a text file named *.java that happens
* to correspond to an existing class file, a warning is *not*
* generated. Similarly, a warning is not generated for a binary
* file named *.class and an existing source file.
*
* The reason for this difference is that source files and class
* files are registered with apt and can get passed on as
* declarations to the next round of processing. Files that are
* just named *.java and *.class are not processed in that manner;
* although having extra source files and class files on the
* source path and class path can alter the behavior of the tool
* and any final compile.
*/
private enum FileKind {
SOURCE {
void register(File file, String name, FilerImpl that) throws IOException {
// Check for corresponding class file
if (that.filesCreated.contains(new File(that.locations.get(CLASS_TREE),
that.nameToPath(name, ".class")))) {
that.bark.aptWarning("CorrespondingClassFile", name);
if (that.opts.get("-XclassesAsDecls") != null)
throw new IOException();
}
that.sourceFileNames.add(file.getPath());
}
},
CLASS {
void register(File file, String name, FilerImpl that) throws IOException {
if (that.filesCreated.contains(new File(that.locations.get(SOURCE_TREE),
that.nameToPath(name, ".java")))) {
that.bark.aptWarning("CorrespondingSourceFile", name);
if (that.opts.get("-XclassesAsDecls") != null)
throw new IOException();
}
// Track the binary name instead of the filesystem location
that.classFileNames.add(name);
}
},
OTHER {
// Nothing special to do
void register(File file, String name, FilerImpl that) throws IOException {}
};
abstract void register(File file, String name, FilerImpl that) throws IOException;
}
private final Options opts;
private final DeclarationMaker declMaker;
private final com.sun.tools.apt.main.AptJavaCompiler comp;
// Platform's default encoding
private final static String DEFAULT_ENCODING =
new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
private String encoding; // name of charset used for source files
private final EnumMap<Location, File> locations; // where new files go
private static final Context.Key<FilerImpl> filerKey =
new Context.Key<FilerImpl>();
// Set of files opened.
private Collection<Flushable> wc;
private Bark bark;
// All created files.
private final Set<File> filesCreated;
// Names of newly created source files
private HashSet<String> sourceFileNames = new HashSet<String>();
// Names of newly created class files
private HashSet<String> classFileNames = new HashSet<String>();
private boolean roundOver;
public static FilerImpl instance(Context context) {
FilerImpl instance = context.get(filerKey);
if (instance == null) {
instance = new FilerImpl(context);
}
return instance;
}
// flush all output streams;
public void flush() {
for(Flushable opendedFile: wc) {
try {
opendedFile.flush();
if (opendedFile instanceof FileOutputStream) {
try {
((FileOutputStream) opendedFile).getFD().sync() ;
} catch (java.io.SyncFailedException sfe) {}
}
} catch (IOException e) { }
}
}
private FilerImpl(Context context) {
context.put(filerKey, this);
opts = Options.instance(context);
declMaker = DeclarationMaker.instance(context);
bark = Bark.instance(context);
comp = com.sun.tools.apt.main.AptJavaCompiler.instance(context);
roundOver = false;
this.filesCreated = comp.getAggregateGenFiles();
// Encoding
encoding = opts.get("-encoding");
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
wc = new HashSet<Flushable>();
// Locations
locations = new EnumMap<Location, File>(Location.class);
String s = opts.get("-s"); // location for new source files
String d = opts.get("-d"); // location for new class files
locations.put(SOURCE_TREE, new File(s != null ? s : "."));
locations.put(CLASS_TREE, new File(d != null ? d : "."));
}
/**
* {@inheritDoc}
*/
public PrintWriter createSourceFile(String name) throws IOException {
String pathname = nameToPath(name, ".java");
File file = new File(locations.get(SOURCE_TREE),
pathname);
PrintWriter pw = getPrintWriter(file, encoding, name, FileKind.SOURCE);
return pw;
}
/**
* {@inheritDoc}
*/
public OutputStream createClassFile(String name) throws IOException {
String pathname = nameToPath(name, ".class");
File file = new File(locations.get(CLASS_TREE),
pathname);
OutputStream os = getOutputStream(file, name, FileKind.CLASS);
return os;
}
/**
* {@inheritDoc}
*/
public PrintWriter createTextFile(Location loc,
String pkg,
File relPath,
String charsetName) throws IOException {
File file = (pkg.length() == 0)
? relPath
: new File(nameToPath(pkg), relPath.getPath());
if (charsetName == null) {
charsetName = encoding;
}
return getPrintWriter(loc, file.getPath(), charsetName, null, FileKind.OTHER);
}
/**
* {@inheritDoc}
*/
public OutputStream createBinaryFile(Location loc,
String pkg,
File relPath) throws IOException {
File file = (pkg.length() == 0)
? relPath
: new File(nameToPath(pkg), relPath.getPath());
return getOutputStream(loc, file.getPath(), null, FileKind.OTHER);
}
/**
* Converts the canonical name of a top-level type or package to a
* pathname. Suffix is ".java" or ".class" or "".
*/
private String nameToPath(String name, String suffix) throws IOException {
if (!DeclarationMaker.isJavaIdentifier(name.replace('.', '_'))) {
bark.aptWarning("IllegalFileName", name);
throw new IOException();
}
return name.replace('.', File.separatorChar) + suffix;
}
private String nameToPath(String name) throws IOException {
return nameToPath(name, "");
}
/**
* Returns a writer for a text file given its location, its
* pathname relative to that location, and its encoding.
*/
private PrintWriter getPrintWriter(Location loc, String pathname,
String encoding, String name, FileKind kind) throws IOException {
File file = new File(locations.get(loc), pathname);
return getPrintWriter(file, encoding, name, kind);
}
/**
* Returns a writer for a text file given its encoding.
*/
private PrintWriter getPrintWriter(File file,
String encoding, String name, FileKind kind) throws IOException {
prepareFile(file, name, kind);
PrintWriter pw =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),
encoding)));
wc.add(pw);
return pw;
}
/**
* Returns an output stream for a binary file given its location
* and its pathname relative to that location.
*/
private OutputStream getOutputStream(Location loc, String pathname, String name, FileKind kind)
throws IOException {
File file = new File(locations.get(loc), pathname);
return getOutputStream(file, name, kind);
}
private OutputStream getOutputStream(File file, String name, FileKind kind) throws IOException {
prepareFile(file, name, kind);
OutputStream os = new FileOutputStream(file);
wc.add(os);
return os;
}
public Set<String> getSourceFileNames() {
return sourceFileNames;
}
public Set<String> getClassFileNames() {
return classFileNames;
}
public void roundOver() {
roundOver = true;
}
/**
* Checks that the file has not already been created during this
* invocation. If not, creates intermediate directories, and
* deletes the file if it already exists.
*/
private void prepareFile(File file, String name, FileKind kind) throws IOException {
if (roundOver) {
bark.aptWarning("NoNewFilesAfterRound", file.toString());
throw new IOException();
}
if (filesCreated.contains(file)) {
bark.aptWarning("FileReopening", file.toString());
throw new IOException();
} else {
if (file.exists()) {
file.delete();
} else {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
if(!parent.mkdirs()) {
bark.aptWarning("BadParentDirectory", file.toString());
throw new IOException();
}
}
}
kind.register(file, name, this);
filesCreated.add(file);
}
}
}
| 12,874 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
RoundStateImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/apt/RoundStateImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.apt;
import com.sun.mirror.apt.RoundState;
import java.util.Map;
@SuppressWarnings("deprecation")
public class RoundStateImpl implements RoundState {
private final boolean finalRound;
private final boolean errorRaised;
private final boolean sourceFilesCreated;
private final boolean classFilesCreated;
public RoundStateImpl(boolean errorRaised,
boolean sourceFilesCreated,
boolean classFilesCreated,
Map<String,String> options) {
/*
* In the default mode of operation, this round is the final
* round if an error was raised OR there were no new source
* files generated. If classes are being treated as
* declarations, this is the final round if an error was
* raised OR neither new source files nor new class files were
* generated.
*/
this.finalRound =
errorRaised ||
(!sourceFilesCreated &&
!(classFilesCreated && options.keySet().contains("-XclassesAsDecls")) );
this.errorRaised = errorRaised;
this.sourceFilesCreated = sourceFilesCreated;
this.classFilesCreated = classFilesCreated;
}
public boolean finalRound() {
return finalRound;
}
public boolean errorRaised() {
return errorRaised;
}
public boolean sourceFilesCreated() {
return sourceFilesCreated;
}
public boolean classFilesCreated() {
return classFilesCreated;
}
public String toString() {
return
"[final round: " + finalRound +
", error raised: " + errorRaised +
", source files created: " + sourceFilesCreated +
", class files created: " + classFilesCreated + "]";
}
}
| 3,056 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeMaker.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/TypeMaker.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.type.*;
import com.sun.mirror.type.PrimitiveType.Kind;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.util.Context;
import static com.sun.tools.javac.code.TypeTags.*;
/**
* Utilities for constructing type objects.
*/
@SuppressWarnings("deprecation")
public class TypeMaker {
private final AptEnv env;
private final VoidType voidType;
private PrimitiveType[] primTypes = new PrimitiveType[VOID];
// VOID is past all prim types
private static final Context.Key<TypeMaker> typeMakerKey =
new Context.Key<TypeMaker>();
public static TypeMaker instance(Context context) {
TypeMaker instance = context.get(typeMakerKey);
if (instance == null) {
instance = new TypeMaker(context);
}
return instance;
}
private TypeMaker(Context context) {
context.put(typeMakerKey, this);
env = AptEnv.instance(context);
voidType = new VoidTypeImpl(env);
primTypes[BOOLEAN] = new PrimitiveTypeImpl(env, Kind.BOOLEAN);
primTypes[BYTE] = new PrimitiveTypeImpl(env, Kind.BYTE);
primTypes[SHORT] = new PrimitiveTypeImpl(env, Kind.SHORT);
primTypes[INT] = new PrimitiveTypeImpl(env, Kind.INT);
primTypes[LONG] = new PrimitiveTypeImpl(env, Kind.LONG);
primTypes[CHAR] = new PrimitiveTypeImpl(env, Kind.CHAR);
primTypes[FLOAT] = new PrimitiveTypeImpl(env, Kind.FLOAT);
primTypes[DOUBLE] = new PrimitiveTypeImpl(env, Kind.DOUBLE);
}
/**
* Returns the TypeMirror corresponding to a javac Type object.
*/
public TypeMirror getType(Type t) {
if (t.isPrimitive()) {
return primTypes[t.tag];
}
switch (t.tag) {
case ERROR: // fall through
case CLASS: return getDeclaredType((Type.ClassType) t);
case WILDCARD: return new WildcardTypeImpl(env, (Type.WildcardType) t);
case TYPEVAR: return new TypeVariableImpl(env, (Type.TypeVar) t);
case ARRAY: return new ArrayTypeImpl(env, (Type.ArrayType) t);
case VOID: return voidType;
default: throw new AssertionError();
}
}
/**
* Returns the declared type corresponding to a given ClassType.
*/
public DeclaredType getDeclaredType(Type.ClassType t) {
return
hasFlag(t.tsym, Flags.ANNOTATION) ? new AnnotationTypeImpl(env, t) :
hasFlag(t.tsym, Flags.INTERFACE) ? new InterfaceTypeImpl(env, t) :
hasFlag(t.tsym, Flags.ENUM) ? new EnumTypeImpl(env, t) :
new ClassTypeImpl(env, t);
}
/**
* Returns a collection of types corresponding to a list of javac Type
* objects.
*/
public Collection<TypeMirror> getTypes(Iterable<Type> types) {
return getTypes(types, TypeMirror.class);
}
/**
* Returns a collection of types corresponding to a list of javac Type
* objects. The element type of the result is specified explicitly.
*/
public <T extends TypeMirror> Collection<T> getTypes(Iterable<Type> types,
Class<T> resType) {
ArrayList<T> res = new ArrayList<T>();
for (Type t : types) {
TypeMirror mir = getType(t);
if (resType.isInstance(mir)) {
res.add(resType.cast(mir));
}
}
return res;
}
/**
* Returns the string representation of a type.
* Bounds of type variables are not included; bounds of wildcard types are.
* Type names are qualified.
*/
public String typeToString(Type t) {
switch (t.tag) {
case ARRAY:
return typeToString(env.jctypes.elemtype(t)) + "[]";
case CLASS:
Type.ClassType c = (Type.ClassType) t;
return DeclaredTypeImpl.toString(env, c);
case WILDCARD:
Type.WildcardType a = (Type.WildcardType) t;
return WildcardTypeImpl.toString(env, a);
default:
return t.tsym.toString();
}
}
/**
* Does a symbol have a given flag?
*/
private static boolean hasFlag(Symbol s, long flag) {
return AptEnv.hasFlag(s, flag);
}
}
| 5,729 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
PrimitiveTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/PrimitiveTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.type.PrimitiveType;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
import static com.sun.mirror.type.PrimitiveType.Kind.*;
/**
* Implementation of PrimitiveType.
*/
@SuppressWarnings("deprecation")
class PrimitiveTypeImpl extends TypeMirrorImpl implements PrimitiveType {
private final Kind kind; // the kind of primitive
PrimitiveTypeImpl(AptEnv env, Kind kind) {
super(env, getType(env, kind));
this.kind = kind;
}
/**
* {@inheritDoc}
*/
public Kind getKind() {
return kind;
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitPrimitiveType(this);
}
/**
* Returns the javac type corresponding to a kind of primitive type.
*/
private static Type getType(AptEnv env, Kind kind) {
switch (kind) {
case BOOLEAN: return env.symtab.booleanType;
case BYTE: return env.symtab.byteType;
case SHORT: return env.symtab.shortType;
case INT: return env.symtab.intType;
case LONG: return env.symtab.longType;
case CHAR: return env.symtab.charType;
case FLOAT: return env.symtab.floatType;
case DOUBLE: return env.symtab.doubleType;
default: throw new AssertionError();
}
}
}
| 2,677 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
WildcardTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/WildcardTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
/**
* Implementation of WildcardType
*/
@SuppressWarnings("deprecation")
public class WildcardTypeImpl extends TypeMirrorImpl implements WildcardType {
protected Type.WildcardType type;
WildcardTypeImpl(AptEnv env, Type.WildcardType type) {
super(env, type);
this.type = type;
}
/**
* Returns the string form of a wildcard type, consisting of "?"
* and any "extends" or "super" clause.
* Delimiting brackets are not included. Class names are qualified.
*/
public String toString() {
return toString(env, type);
}
/**
* {@inheritDoc}
*/
public Collection<ReferenceType> getUpperBounds() {
return type.isSuperBound()
? Collections.<ReferenceType>emptyList()
: typeToCollection(type.type);
}
/**
* {@inheritDoc}
*/
public Collection<ReferenceType> getLowerBounds() {
return type.isExtendsBound()
? Collections.<ReferenceType>emptyList()
: typeToCollection(type.type);
}
/**
* Gets the ReferenceType for a javac Type object, and returns
* it in a singleton collection. If type is null, returns an empty
* collection.
*/
private Collection<ReferenceType> typeToCollection(Type type) {
ArrayList<ReferenceType> res = new ArrayList<ReferenceType>(1);
if (type != null) {
res.add((ReferenceType) env.typeMaker.getType(type));
}
return res;
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitWildcardType(this);
}
/**
* Returns the string form of a wildcard type, consisting of "?"
* and any "extends" or "super" clause.
* See {@link #toString()} for details.
*/
static String toString(AptEnv env, Type.WildcardType wildThing) {
return wildThing.toString();
}
}
| 3,485 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeVariableImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/TypeVariableImpl.java | /*
* Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import java.util.Collection;
import java.util.ArrayList;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Type;
/**
* Implementation of TypeVariable
*/
@SuppressWarnings("deprecation")
public class TypeVariableImpl extends TypeMirrorImpl implements TypeVariable {
protected Type.TypeVar type;
TypeVariableImpl(AptEnv env, Type.TypeVar type) {
super(env, type);
this.type = type;
}
/**
* Returns the simple name of this type variable. Bounds are
* not included.
*/
public String toString() {
return type.tsym.name.toString();
}
/**
* {@inheritDoc}
*/
public TypeParameterDeclaration getDeclaration() {
TypeSymbol sym = type.tsym;
return env.declMaker.getTypeParameterDeclaration(sym);
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitTypeVariable(this);
}
}
| 2,356 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypeMirrorImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/TypeMirrorImpl.java | /*
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
/**
* Implementation of TypeMirror
*/
@SuppressWarnings("deprecation")
public abstract class TypeMirrorImpl implements TypeMirror {
protected final AptEnv env;
public final Type type;
protected TypeMirrorImpl(AptEnv env, Type type) {
this.env = env;
this.type = type;
}
/**
* {@inheritDoc}
*/
public String toString() {
return type.toString();
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj) {
if (obj instanceof TypeMirrorImpl) {
TypeMirrorImpl that = (TypeMirrorImpl) obj;
return env.jctypes.isSameType(this.type, that.type);
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return Types.hashCode(type);
}
}
| 2,228 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
VoidTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/VoidTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.type.VoidType;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
/**
* Implementation of VoidType.
*/
@SuppressWarnings("deprecation")
class VoidTypeImpl extends TypeMirrorImpl implements VoidType {
VoidTypeImpl(AptEnv env) {
super(env, env.symtab.voidType);
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitVoidType(this);
}
}
| 1,700 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
InterfaceTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/InterfaceTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
/**
* Implementation of InterfaceType
*/
@SuppressWarnings("deprecation")
public class InterfaceTypeImpl extends DeclaredTypeImpl
implements InterfaceType {
InterfaceTypeImpl(AptEnv env, Type.ClassType type) {
super(env, type);
}
/**
* {@inheritDoc}
*/
public InterfaceDeclaration getDeclaration() {
return (InterfaceDeclaration) super.getDeclaration();
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitInterfaceType(this);
}
}
| 1,996 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ArrayTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/ArrayTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
/**
* Implementation of ArrayType
*/
@SuppressWarnings("deprecation")
public class ArrayTypeImpl extends TypeMirrorImpl implements ArrayType {
protected Type.ArrayType type;
ArrayTypeImpl(AptEnv env, Type.ArrayType type) {
super(env, type);
this.type = type;
}
/**
* {@inheritDoc}
*/
public TypeMirror getComponentType() {
return env.typeMaker.getType(type.elemtype);
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitArrayType(this);
}
}
| 1,952 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
ClassTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/ClassTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
/**
* Implementation of ClassType
*/
@SuppressWarnings("deprecation")
public class ClassTypeImpl extends DeclaredTypeImpl implements ClassType {
ClassTypeImpl(AptEnv env, Type.ClassType type) {
super(env, type);
}
/**
* {@inheritDoc}
*/
public ClassDeclaration getDeclaration() {
return (ClassDeclaration) super.getDeclaration();
}
/**
* {@inheritDoc}
*/
public ClassType getSuperclass() {
// java.lang.Object has no superclass
if (type.tsym == env.symtab.objectType.tsym) {
return null;
}
Type sup = env.jctypes.supertype(type);
return (ClassType) env.typeMaker.getType(sup);
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitClassType(this);
}
}
| 2,260 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
EnumTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/EnumTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
/**
* Implementation of EnumType
*/
@SuppressWarnings("deprecation")
public class EnumTypeImpl extends ClassTypeImpl implements EnumType {
EnumTypeImpl(AptEnv env, Type.ClassType type) {
super(env, type);
}
/**
* {@inheritDoc}
*/
public EnumDeclaration getDeclaration() {
return (EnumDeclaration) super.getDeclaration();
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitEnumType(this);
}
}
| 1,927 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DeclaredTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/DeclaredTypeImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import java.util.Collection;
import com.sun.mirror.declaration.TypeDeclaration;
import com.sun.mirror.type.*;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
/**
* Implementation of DeclaredType
*/
@SuppressWarnings("deprecation")
abstract class DeclaredTypeImpl extends TypeMirrorImpl
implements DeclaredType {
protected Type.ClassType type;
protected DeclaredTypeImpl(AptEnv env, Type.ClassType type) {
super(env, type);
this.type = type;
}
/**
* Returns a string representation of this declared type.
* This includes the type's name and any actual type arguments.
* Type names are qualified.
*/
public String toString() {
return toString(env, type);
}
/**
* {@inheritDoc}
*/
public TypeDeclaration getDeclaration() {
return env.declMaker.getTypeDeclaration((ClassSymbol) type.tsym);
}
/**
* {@inheritDoc}
*/
public DeclaredType getContainingType() {
if (type.getEnclosingType().tag == TypeTags.CLASS) {
// This is the type of an inner class.
return (DeclaredType) env.typeMaker.getType(type.getEnclosingType());
}
ClassSymbol enclosing = type.tsym.owner.enclClass();
if (enclosing != null) {
// Nested but not inner. Return the raw type of the enclosing
// class or interface.
// See java.lang.reflect.ParameterizedType.getOwnerType().
return (DeclaredType) env.typeMaker.getType(
env.jctypes.erasure(enclosing.type));
}
return null;
}
/**
* {@inheritDoc}
*/
public Collection<TypeMirror> getActualTypeArguments() {
return env.typeMaker.getTypes(type.getTypeArguments());
}
/**
* {@inheritDoc}
*/
public Collection<InterfaceType> getSuperinterfaces() {
return env.typeMaker.getTypes(env.jctypes.interfaces(type),
InterfaceType.class);
}
/**
* Returns a string representation of this declared type.
* See {@link #toString()} for details.
*/
static String toString(AptEnv env, Type.ClassType c) {
return c.toString();
}
}
| 3,619 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
AnnotationTypeImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/type/AnnotationTypeImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.type;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.Type;
/**
* Implementation of AnnotationType
*/
@SuppressWarnings("deprecation")
public class AnnotationTypeImpl extends InterfaceTypeImpl
implements AnnotationType {
AnnotationTypeImpl(AptEnv env, Type.ClassType type) {
super(env, type);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeDeclaration getDeclaration() {
return (AnnotationTypeDeclaration) super.getDeclaration();
}
/**
* {@inheritDoc}
*/
public void accept(TypeVisitor v) {
v.visitAnnotationType(this);
}
}
| 2,013 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
TypesImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/util/TypesImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.util;
import java.util.Collection;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.Types;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.apt.mirror.declaration.*;
import com.sun.tools.apt.mirror.type.TypeMirrorImpl;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.ListBuffer;
/**
* Implementation of Types utility methods for annotation processors
*/
@SuppressWarnings("deprecation")
public class TypesImpl implements Types {
private final AptEnv env;
private static final Context.Key<Types> typesKey =
new Context.Key<Types>();
public static Types instance(Context context) {
Types instance = context.get(typesKey);
if (instance == null) {
instance = new TypesImpl(context);
}
return instance;
}
private TypesImpl(Context context) {
context.put(typesKey, this);
env = AptEnv.instance(context);
}
/**
* {@inheritDoc}
*/
public boolean isSubtype(TypeMirror t1, TypeMirror t2) {
return env.jctypes.isSubtype(((TypeMirrorImpl) t1).type,
((TypeMirrorImpl) t2).type);
}
/**
* {@inheritDoc}
*/
public boolean isAssignable(TypeMirror t1, TypeMirror t2) {
return env.jctypes.isAssignable(((TypeMirrorImpl) t1).type,
((TypeMirrorImpl) t2).type);
}
/**
* {@inheritDoc}
*/
public TypeMirror getErasure(TypeMirror t) {
return env.typeMaker.getType(
env.jctypes.erasure(((TypeMirrorImpl) t).type));
}
/**
* {@inheritDoc}
*/
public PrimitiveType getPrimitiveType(PrimitiveType.Kind kind) {
Type prim = null;
switch (kind) {
case BOOLEAN: prim = env.symtab.booleanType; break;
case BYTE: prim = env.symtab.byteType; break;
case SHORT: prim = env.symtab.shortType; break;
case INT: prim = env.symtab.intType; break;
case LONG: prim = env.symtab.longType; break;
case CHAR: prim = env.symtab.charType; break;
case FLOAT: prim = env.symtab.floatType; break;
case DOUBLE: prim = env.symtab.doubleType; break;
default: assert false;
}
return (PrimitiveType) env.typeMaker.getType(prim);
}
/**
* {@inheritDoc}
*/
public VoidType getVoidType() {
return (VoidType) env.typeMaker.getType(env.symtab.voidType);
}
/**
* {@inheritDoc}
*/
public ArrayType getArrayType(TypeMirror componentType) {
if (componentType instanceof VoidType) {
throw new IllegalArgumentException("void");
}
return (ArrayType) env.typeMaker.getType(
new Type.ArrayType(((TypeMirrorImpl) componentType).type,
env.symtab.arrayClass));
}
/**
* {@inheritDoc}
*/
public TypeVariable getTypeVariable(TypeParameterDeclaration tparam) {
return (TypeVariable) env.typeMaker.getType(
((DeclarationImpl) tparam).sym.type);
}
/**
* {@inheritDoc}
*/
public WildcardType getWildcardType(Collection<ReferenceType> upperBounds,
Collection<ReferenceType> lowerBounds) {
BoundKind kind;
Type bound;
int uppers = upperBounds.size();
int downers = lowerBounds.size();
if (uppers + downers > 1) {
throw new IllegalArgumentException("Multiple bounds not allowed");
} else if (uppers + downers == 0) {
kind = BoundKind.UNBOUND;
bound = env.symtab.objectType;
} else if (uppers == 1) {
assert downers == 0;
kind = BoundKind.EXTENDS;
bound = ((TypeMirrorImpl) upperBounds.iterator().next()).type;
} else {
assert uppers == 0 && downers == 1;
kind = BoundKind.SUPER;
bound = ((TypeMirrorImpl) lowerBounds.iterator().next()).type;
}
if (bound instanceof Type.WildcardType)
throw new IllegalArgumentException(bound.toString());
return (WildcardType) env.typeMaker.getType(
new Type.WildcardType(bound, kind, env.symtab.boundClass));
}
/**
* {@inheritDoc}
*/
public DeclaredType getDeclaredType(TypeDeclaration decl,
TypeMirror... typeArgs) {
ClassSymbol sym = ((TypeDeclarationImpl) decl).sym;
if (typeArgs.length == 0)
return (DeclaredType) env.typeMaker.getType(
env.jctypes.erasure(sym.type));
if (sym.type.getEnclosingType().isParameterized())
throw new IllegalArgumentException(decl.toString());
return getDeclaredType(sym.type.getEnclosingType(), sym, typeArgs);
}
/**
* {@inheritDoc}
*/
public DeclaredType getDeclaredType(DeclaredType containing,
TypeDeclaration decl,
TypeMirror... typeArgs) {
if (containing == null)
return getDeclaredType(decl, typeArgs);
ClassSymbol sym = ((TypeDeclarationImpl) decl).sym;
Type outer = ((TypeMirrorImpl) containing).type;
if (outer.tsym != sym.owner.enclClass())
throw new IllegalArgumentException(containing.toString());
if (!outer.isParameterized())
return getDeclaredType(decl, typeArgs);
return getDeclaredType(outer, sym, typeArgs);
}
private DeclaredType getDeclaredType(Type outer,
ClassSymbol sym,
TypeMirror... typeArgs) {
if (typeArgs.length != sym.type.getTypeArguments().length())
throw new IllegalArgumentException(
"Incorrect number of type arguments");
ListBuffer<Type> targs = new ListBuffer<Type>();
for (TypeMirror t : typeArgs) {
if (!(t instanceof ReferenceType || t instanceof WildcardType))
throw new IllegalArgumentException(t.toString());
targs.append(((TypeMirrorImpl) t).type);
}
//### Need a way to check that type args match formals.
return (DeclaredType) env.typeMaker.getType(
new Type.ClassType(outer, targs.toList(), sym));
}
}
| 7,970 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
SourcePositionImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/util/SourcePositionImpl.java | /*
* Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.util;
import java.io.File;
import javax.tools.JavaFileObject;
import com.sun.mirror.util.SourcePosition;
import com.sun.tools.javac.util.Position;
/**
* Implementation of SourcePosition
*/
@SuppressWarnings("deprecation")
public class SourcePositionImpl implements SourcePosition {
private JavaFileObject sourcefile;
private int pos; // file position, in javac's internal format
private Position.LineMap linemap;
public SourcePositionImpl(JavaFileObject sourcefile, int pos, Position.LineMap linemap) {
this.sourcefile = sourcefile;
this.pos = pos;
this.linemap = linemap;
assert sourcefile != null;
assert linemap != null;
}
public int getJavacPosition() {
return pos;
}
public JavaFileObject getSource() {
return sourcefile;
}
/**
* Returns a string representation of this position in the
* form "sourcefile:line", or "sourcefile" if no line number is available.
*/
public String toString() {
int ln = line();
return (ln == Position.NOPOS)
? sourcefile.getName()
: sourcefile.getName() + ":" + ln;
}
/**
* {@inheritDoc}
*/
public File file() {
return new File(sourcefile.toUri());
}
/**
* {@inheritDoc}
*/
public int line() {
return linemap.getLineNumber(pos);
}
/**
* {@inheritDoc}
*/
public int column() {
return linemap.getColumnNumber(pos);
}
}
| 2,782 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
DeclarationsImpl.java | /FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/src/share/classes/com/sun/tools/apt/mirror/util/DeclarationsImpl.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.apt.mirror.util;
import com.sun.mirror.declaration.*;
import com.sun.mirror.util.Declarations;
import com.sun.tools.apt.mirror.declaration.DeclarationImpl;
import com.sun.tools.apt.mirror.declaration.MethodDeclarationImpl;
import com.sun.tools.apt.mirror.util.DeclarationsImpl;
import com.sun.tools.apt.mirror.AptEnv;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.util.Context;
import static com.sun.tools.javac.code.Kinds.*;
/**
* Implementation of Declarations utility methods for annotation processors
*/
@SuppressWarnings("deprecation")
public class DeclarationsImpl implements Declarations {
private final AptEnv env;
private static final Context.Key<Declarations> declarationsKey =
new Context.Key<Declarations>();
public static Declarations instance(Context context) {
Declarations instance = context.get(declarationsKey);
if (instance == null) {
instance = new DeclarationsImpl(context);
}
return instance;
}
private DeclarationsImpl(Context context) {
context.put(declarationsKey, this);
env = AptEnv.instance(context);
}
/**
* {@inheritDoc}
* See sections 8.3 and 8.4.6 of
* <cite>The Java™ Language Specification</cite>
*/
public boolean hides(MemberDeclaration sub, MemberDeclaration sup) {
Symbol hider = ((DeclarationImpl) sub).sym;
Symbol hidee = ((DeclarationImpl) sup).sym;
// Fields only hide fields; methods only methods; types only types.
// Names must match. Nothing hides itself (just try it).
if (hider == hidee ||
hider.kind != hidee.kind ||
hider.name != hidee.name) {
return false;
}
// Only static methods can hide other methods.
// Methods only hide methods with matching signatures.
if (hider.kind == MTH) {
if ((hider.flags() & Flags.STATIC) == 0 ||
!env.jctypes.isSubSignature(hider.type, hidee.type)) {
return false;
}
}
// Hider must be in a subclass of hidee's class.
// Note that if M1 hides M2, and M2 hides M3, and M3 is accessible
// in M1's class, then M1 and M2 both hide M3.
ClassSymbol hiderClass = hider.owner.enclClass();
ClassSymbol hideeClass = hidee.owner.enclClass();
if (hiderClass == null || hideeClass == null ||
!hiderClass.isSubClass(hideeClass, env.jctypes)) {
return false;
}
// Hidee must be accessible in hider's class.
// The method isInheritedIn is poorly named: it checks only access.
return hidee.isInheritedIn(hiderClass, env.jctypes);
}
/**
* {@inheritDoc}
* See section 8.4.6.1 of
* <cite>The Java™ Language Specification</cite>
*/
public boolean overrides(MethodDeclaration sub, MethodDeclaration sup) {
MethodSymbol overrider = ((MethodDeclarationImpl) sub).sym;
MethodSymbol overridee = ((MethodDeclarationImpl) sup).sym;
ClassSymbol origin = (ClassSymbol) overrider.owner;
return overrider.name == overridee.name &&
// not reflexive as per JLS
overrider != overridee &&
// we don't care if overridee is static, though that wouldn't
// compile
!overrider.isStatic() &&
// overrider, whose declaring type is the origin, must be
// in a subtype of overridee's type
env.jctypes.asSuper(origin.type, overridee.owner) != null &&
// check access and signatures; don't check return types
overrider.overrides(overridee, origin, env.jctypes, false);
}
}
| 5,076 | Java | .java | openjdk-mirror/jdk7u-langtools | 9 | 3 | 0 | 2012-05-07T19:45:34Z | 2012-05-08T17:47:06Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.