Java Code Examples for com.sun.source.util.DocTrees#getDocCommentTree()

The following examples show how to use com.sun.source.util.DocTrees#getDocCommentTree() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public boolean run(DocletEnvironment root) {
    DocTrees docTrees = root.getDocTrees();
    System.out.println("classes:" + ElementFilter.typesIn(root.getIncludedElements()));

    Element klass = ElementFilter.typesIn(root.getIncludedElements()).iterator().next();
    String text = "";
    try {
        DocCommentTree dcTree = docTrees.getDocCommentTree(klass, overviewpath);
        text = dcTree.getFullBody().toString();
    } catch (IOException ioe) {
        throw new Error(ioe);
    }

    if (text.length() < 64)
        System.err.println("text: '" + text + "'");
    else
        System.err.println("text: '"
                + text.substring(0, 20)
                + "..."
                + text.substring(text.length() - 20)
                + "'");
    return text.startsWith("ABC") && text.endsWith("XYZ");
}
 
Example 2
Source File: InlineTagsWithBraces.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public boolean run(DocletEnvironment root) {
        DocTrees trees = root.getDocTrees();
        TypeElement cd = ElementFilter.typesIn(root.getIncludedElements()).iterator().next();
        DocCommentTree docCommentTree = trees.getDocCommentTree(cd);
        List<? extends DocTree> tags = docCommentTree.getBody();

        for (int i = 0; i < tags.size(); i++) {
            System.out.println(tags.get(0).getKind());
//            if (!tags[i].name().equals(expectedTags[i]) ||
//                        !tags[i].text().equals(expectedText[i])) {
//                throw new Error("Tag \"" + tags[i] + "\" not as expected");
//            }
        }

        return true;
    }
 
Example 3
Source File: BeakerxDoclet.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private static MethodInspect getInspect(Element element, DocTrees docTrees) {
  DocCommentTree eeDocComment = docTrees.getDocCommentTree(element);
  List<String> signature = new ArrayList<>();
  if (element instanceof ExecutableElement) {
    ExecutableElement eElement = (ExecutableElement) element;
    for (VariableElement v : eElement.getParameters()) {
      String n = v.asType().toString();
      if (v.asType().toString().contains("<")) {
        n = v.asType().toString().substring(0, v.asType().toString().indexOf("<"));
      }
      signature.add(n + " " + v.getSimpleName());
    }
  }
  String comment = (eeDocComment != null) ? eeDocComment.getFullBody().toString() : "";
  String name = element.toString().subSequence(0, element.toString().indexOf("(")).toString();
  MethodInspect methodInspect = new MethodInspect(name, comment, String.join(", ", signature));
  return methodInspect;
}
 
Example 4
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean resolveContext(CompilationInfo javac, JavadocContext jdctx) throws IOException {
    jdctx.doc = javac.getDocument();
    // find class context: class, method, ...
    DocTrees trees = javac.getDocTrees();
    TreePath javadocFor = JavadocCompletionUtils.findJavadoc(javac, this.caretOffset);
    if (javadocFor == null) {
        return false;
    }
    jdctx.javadocFor = javadocFor;
    DocCommentTree docCommentTree = trees.getDocCommentTree(javadocFor);
    if (docCommentTree == null) {
        return false;
    }
    jdctx.comment = docCommentTree;
    Element elm = trees.getElement(javadocFor);
    if (elm == null) {
        return false;
    }
    jdctx.handle = ElementHandle.create(elm);
    jdctx.commentFor = elm;
    jdctx.jdts = JavadocCompletionUtils.findJavadocTokenSequence(javac, this.caretOffset);
    if (jdctx.jdts == null) {
        return false;
    }
    jdctx.positions = (DocSourcePositions) trees.getSourcePositions();
    return jdctx.positions != null;
}
 
Example 5
Source File: JavadocHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private DocCommentTree parseDocComment(JavacTask task, String javadoc) {
    DocTrees trees = DocTrees.instance(task);
    try {
        return trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), javax.tools.JavaFileObject.Kind.HTML) {
            @Override @DefinedBy(Api.COMPILER)
            public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                return "<body>" + javadoc + "</body>";
            }
        });
    } catch (URISyntaxException ex) {
        return null;
    }
}
 
Example 6
Source File: JavadocFormatter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**Format javadoc to plain text.
 *
 * @param header element caption that should be used
 * @param javadoc to format
 * @return javadoc formatted to plain text
 */
public String formatJavadoc(String header, String javadoc) {
    try {
        StringBuilder result = new StringBuilder();

        result.append(escape(CODE_HIGHLIGHT)).append(header).append(escape(CODE_RESET)).append("\n");

        if (javadoc == null) {
            return result.toString();
        }

        JavacTask task = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, null);
        DocTrees trees = DocTrees.instance(task);
        DocCommentTree docComment = trees.getDocCommentTree(new SimpleJavaFileObject(new URI("mem://doc.html"), Kind.HTML) {
            @Override @DefinedBy(Api.COMPILER)
            public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                return "<body>" + javadoc + "</body>";
            }
        });

        new FormatJavadocScanner(result, task).scan(docComment, null);

        addNewLineIfNeeded(result);

        return result.toString();
    } catch (URISyntaxException ex) {
        throw new InternalError("Unexpected exception", ex);
    }
}
 
Example 7
Source File: Example.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prints an element.
 *
 * @param trees the utility class
 * @param e the element to be printed
 */
public void printElement(DocTrees trees, Element e) {
    DocCommentTree docCommentTree = trees.getDocCommentTree(e);
    if (docCommentTree != null) {
        System.out.println("Element (" + e.getKind() + ": "
                + e + ") has the following comments:");
        System.out.println("Entire body: " + docCommentTree.getFullBody());
        System.out.println("Block tags: " + docCommentTree.getBlockTags());
    }
}
 
Example 8
Source File: BreakIteratorWarning.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public boolean run(DocletEnvironment root) {
    TypeElement cd = ElementFilter.typesIn(root.getIncludedElements()).iterator().next();
    VariableElement fd = getFields(cd).get(0);
    DocTrees docTrees = root.getDocTrees();
    DocCommentTree docCommentTree = docTrees.getDocCommentTree(fd);
    List<? extends DocTree> firstSentence = docCommentTree.getFirstSentence();
    return true;
}
 
Example 9
Source File: NoStar.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public boolean run(DocletEnvironment root) {
    Set<TypeElement> classes = ElementFilter.typesIn(root.getIncludedElements());
    if (classes.size() != 1)
        throw new Error("1 " + Arrays.asList(classes));
    TypeElement self = classes.iterator().next();
    DocTrees trees = root.getDocTrees();
    DocCommentTree docCommentTree = trees.getDocCommentTree(self);
    String c = docCommentTree.getFullBody().toString();
    System.out.println("\"" + c + "\"");
    return c.equals("First sentence.\n0\n 1\n  2\n   3\n    4\n     5");
}
 
Example 10
Source File: DocCommentTreeApiTester.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests getting a DocCommentTree from an element, as well
 * as test if break iterator setter/getter works correctly.
 *
 * @param javaFileName a test file to be processed
 * @param expected the expected output
 * @throws java.io.IOException
 */
public void runElementAndBreakIteratorTests(String javaFileName, String expected) throws IOException {
    List<File> javaFiles = new ArrayList<>();
    javaFiles.add(new File(testSrc, javaFileName));

    List<File> dirs = new ArrayList<>();
    dirs.add(new File(testSrc));

    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
        fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);

        final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        final DocTrees trees = DocTrees.instance(t);

        Iterable<? extends Element> elements = t.analyze();

        Element klass = elements.iterator().next();
        DocCommentTree dcTree = trees.getDocCommentTree(klass);

        List<? extends DocTree> firstSentence = dcTree.getFirstSentence();
        StringWriter sw = new StringWriter();
        DocPretty pretty = new DocPretty(sw);
        pretty.print(firstSentence);
        check("getDocCommentTree(Element)", expected, sw.toString());

        BreakIterator bi = BreakIterator.getSentenceInstance(Locale.FRENCH);
        trees.setBreakIterator(bi);
        BreakIterator nbi = trees.getBreakIterator();
        if (bi.equals(nbi)) {
            pass++;
            check("getDocCommentTree(Element) with BreakIterator", expected, sw.toString());
        } else {
            fail++;
            System.err.println("BreakIterators don't match");
        }
    }
}
 
Example 11
Source File: DocCommentTreeApiTester.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests DocTrees.getDocCommentTree(Element e, String relpath) using relative path.
 *
 * @param javaFileName the reference java file
 * @param fileName the relative html file
 * @throws java.lang.Exception ouch
 */
public void runRelativePathTest(String javaFileName, String fileName) throws Exception  {
    List<File> javaFiles = new ArrayList<>();
    javaFiles.add(new File(testSrc, javaFileName));

    List<File> dirs = new ArrayList<>();
    dirs.add(new File(testSrc));

    try (StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null)) {
        fm.setLocation(javax.tools.StandardLocation.SOURCE_PATH, dirs);
        Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(javaFiles);

        final JavacTask t = javac.getTask(null, fm, null, null, null, fos);
        final DocTrees trees = DocTrees.instance(t);

        Iterable<? extends Element> elements = t.analyze();

        Element klass = elements.iterator().next();

        DocCommentTree dcTree = trees.getDocCommentTree(klass, fileName);
        StringWriter sw = new StringWriter();
        printer.print(dcTree, sw);
        String found = sw.toString();

        FileObject htmlFo = fm.getFileForInput(javax.tools.StandardLocation.SOURCE_PATH,
                t.getElements().getPackageOf(klass).getQualifiedName().toString(),
                fileName);

        String expected = getExpected(htmlFo.openReader(true));
        astcheck(fileName, expected, found);
    }
}
 
Example 12
Source File: JavadocConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/** Returns an AST node for the javadoc comment of a specified class, method, or field element. */
static Javadoc convertJavadoc(
    TreePath path, String source, JavacEnvironment env, boolean reportWarnings) {
  DocTrees docTrees = DocTrees.instance(env.task());
  DocCommentTree docComment = docTrees.getDocCommentTree(path);
  if (docComment == null) {
    return null; // Declaration does not have a javadoc comment.
  }
  JavadocConverter converter =
      new JavadocConverter(
          env.treeUtilities().getElement(path),
          docComment,
          source,
          docTrees,
          path.getCompilationUnit(),
          reportWarnings);
  Javadoc result = new Javadoc();

  // First tag is the description.
  TagElement newTag = new TagElement().setTagKind(TagElement.TagKind.DESCRIPTION);
  converter.scan(docComment.getFirstSentence(), newTag);
  converter.scan(docComment.getBody(), newTag);
  if (!newTag.getFragments().isEmpty()) {
    List<TreeNode> fragments = newTag.getFragments();
    int start = fragments.get(0).getStartPosition();
    TreeNode lastFragment = fragments.get(fragments.size() - 1);
    int end = start + lastFragment.getLength();
    converter.setPos(newTag, start, end);
    result.addTag(newTag);
  }
  for (DocTree tag : docComment.getBlockTags()) {
    if (tag.getKind() != DocTree.Kind.ERRONEOUS) {
      newTag = new TagElement();
      converter.scan(tag, newTag);
      result.addTag(newTag);
    }
  }
  return result;
}
 
Example 13
Source File: BeakerxDoclet.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public boolean run(DocletEnvironment docEnv) {
  HashMap<String, ClassInspect> inspects = new HashMap<>();
  DocTrees docTrees = docEnv.getDocTrees();
  for (TypeElement t : ElementFilter.typesIn(docEnv.getIncludedElements())) {
    DocCommentTree docCommentTree = docTrees.getDocCommentTree(t);
    String comment = (docCommentTree != null) ? docCommentTree.getFullBody().toString() : "";
    ClassInspect classInspect = new ClassInspect(t.getSimpleName().toString(), t.getQualifiedName().toString(), comment);
    inspects.put(classInspect.getFullName(), classInspect);
    List<MethodInspect> constructors = new ArrayList<>();
    List<MethodInspect> methods = new ArrayList<>();
    for (Element ee : t.getEnclosedElements()) {
      if (ee.getModifiers().contains(Modifier.PUBLIC) || ee.getModifiers().contains(Modifier.PROTECTED)) {
        if (ee.getKind().equals(ElementKind.CONSTRUCTOR)) {
          constructors.add(getInspect(ee, docTrees));
        } else if (ee.getKind().equals(ElementKind.METHOD)) {
          methods.add(getInspect(ee, docTrees));
        }
      }
    }
    classInspect.setMethods(methods);
    classInspect.setConstructors(constructors);
  }
  SerializeInspect serializeInspect = new SerializeInspect();
  String json = serializeInspect.toJson(inspects);
  serializeInspect.saveToFile(json);
  return true;
}
 
Example 14
Source File: DumpJavaDoc.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public boolean run(DocletEnvironment docEnv) {
    final Elements utils = docEnv.getElementUtils();
    final DocTrees docTrees = docEnv.getDocTrees();
    
    try (OutputStream os = Files.newOutputStream(Paths.get(dumpFileName))) {
        final Properties javaDocMap = new Properties();
        for (Element element : docEnv.getIncludedElements()) {
            if (element.getKind() == ElementKind.CLASS) {
                final TypeElement classDoc = (TypeElement) element;
                final DocCommentTree classCommentTree = docTrees.getDocCommentTree(classDoc);
                
                if (classCommentTree != null) {
                    javaDocMap.put(classDoc.toString(), getAllComments(classCommentTree.getFullBody()));
                }
                
                for (Element member: classDoc.getEnclosedElements()) {
                    // Skip all non-public methods
                    if (!member.getModifiers().contains(Modifier.PUBLIC)) {
                        continue;
                    }
                    
                    if (member.getKind() == ElementKind.METHOD) {
                        final ExecutableElement method = (ExecutableElement) member;
                        final DocCommentTree methodCommentTree = docTrees.getDocCommentTree(method);
                        final String qualifiedName = utils.getBinaryName(classDoc) + "." + method.getSimpleName();
                        
                        if (methodCommentTree == null) {
                            javaDocMap.put(qualifiedName, "");
                        } else  {
                            javaDocMap.put(qualifiedName, getAllComments(methodCommentTree.getFullBody()));
                            for (DocTree tree: methodCommentTree.getBlockTags()) {
                                if (tree.getKind() == DocTree.Kind.RETURN) {
                                    final ReturnTree returnTree = (ReturnTree) tree;
                                    javaDocMap.put(qualifiedName + ".returnCommentTag", 
                                        getAllComments(returnTree.getDescription()));
                                } else if (tree.getKind() == DocTree.Kind.PARAM) {
                                    final ParamTree paramTree = (ParamTree) tree;
                                    final int index = getParamIndex(method, paramTree);
                                    if (index >= 0) {
                                        javaDocMap.put(qualifiedName + ".paramCommentTag." + index, 
                                            getAllComments(paramTree.getDescription()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        javaDocMap.store(os, "");
        os.flush();
    } catch (final IOException ex) {
        reporter.print(Diagnostic.Kind.ERROR, ex.getMessage());
    }
    
    return true;
}