com.github.javaparser.ast.comments.JavadocComment Java Examples

The following examples show how to use com.github.javaparser.ast.comments.JavadocComment. 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: ImpSort.java    From impsort-maven-plugin with Apache License 2.0 7 votes vote down vote up
private static Set<String> tokensInUse(CompilationUnit unit) {

    // Extract tokens from the java code:
    Stream<Node> packageDecl =
        unit.getPackageDeclaration().isPresent()
            ? Stream.of(unit.getPackageDeclaration().get()).map(PackageDeclaration::getAnnotations)
                .flatMap(NodeList::stream)
            : Stream.empty();
    Stream<String> typesInCode = Stream.concat(packageDecl, unit.getTypes().stream())
        .map(Node::getTokenRange).filter(Optional::isPresent).map(Optional::get)
        .filter(r -> r != TokenRange.INVALID).flatMap(r -> {
          // get all JavaTokens as strings from each range
          return StreamSupport.stream(r.spliterator(), false);
        }).map(JavaToken::asString);

    // Extract referenced class names from parsed javadoc comments:
    Stream<String> typesInJavadocs = unit.getAllComments().stream()
        .filter(c -> c instanceof JavadocComment).map(JavadocComment.class::cast)
        .map(JavadocComment::parse).flatMap(ImpSort::parseJavadoc);

    return Stream.concat(typesInCode, typesInJavadocs)
        .filter(t -> t != null && !t.isEmpty() && Character.isJavaIdentifierStart(t.charAt(0)))
        .collect(Collectors.toSet());
  }
 
Example #2
Source File: PackageDocScanParser.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
private void processInterfaceExtend(Map<String, Class> classMap, Map<String, Map<String, JavadocComment>> serviceMethodMap) {
    for (Map.Entry<String, Class> entry : classMap.entrySet()) {
        int simpleNameStart = entry.getKey().lastIndexOf(".");
        String serviceName = entry.getKey().substring(simpleNameStart + 1);
        Class[] classes = entry.getValue().getInterfaces();
        for (Class z : classes) {
            Map<String, JavadocComment> methodDocMap = serviceMethodMap.get(serviceName);
            if (methodDocMap != null) {
                logger.info(z.getName());
                int nameStart = z.getName().lastIndexOf(".");
                String name = z.getName().substring(nameStart + 1);
                Map<String, JavadocComment> childInterfaceDoc = serviceMethodMap.get(name);
                if (childInterfaceDoc != null && childInterfaceDoc.size() > 0) {
                    methodDocMap.putAll(childInterfaceDoc);
                }
            }
        }
    }
}
 
Example #3
Source File: PackageDocScanParser.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
private Map<String, JavadocComment> parseDoc(File classFile) {
    Map<String, JavadocComment> classDoc = new HashMap<>();
    try {
        CompilationUnit cu = StaticJavaParser.parse(classFile, StandardCharsets.UTF_8);
        new VoidVisitorAdapter<Object>() {
            @Override
            public void visit(JavadocComment comment, Object arg) {
                super.visit(comment, arg);
                if (comment.getCommentedNode().get() instanceof MethodDeclaration) {
                    MethodDeclaration node = (MethodDeclaration) comment.getCommentedNode().get();
                    classDoc.put(methodName(node), comment);
                }
            }
        }.visit(cu, null);
    } catch (Exception e) {
        logger.info("ERROR PROCESSING ", e);
    }
    return classDoc;
}
 
Example #4
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Extract the content of a doc annotation. The content is always handle as a string.
 * The javadoc * and all tabs/space before it are removed as well as the first space after it if present.
 * </p>
 *
 * <p>
 * The end of the annotation content is either the end of the content block or the start of an other annotation.
 * (i.e it reach a <code>\n@</code> string.
 * </p>
 *
 * @param anno The annotation we are looking for. (must start with @)
 * @param jdoc The javadoc block from were the content will be extracted.
 * @return the content of the annotation, one entry in the list for each annotation encountered.
 */
public static Set<String> extractDocAnnotation(String anno, JavadocComment jdoc){
    String content = jdoc.getContent().replaceAll("\n[ \t]+\\* ?","\n"); //remove the * at the beginning of a line
    Set<String> result = new LinkedHashSet<>();

    while(content.contains(anno)){
        int begin = content.indexOf(anno)+ (anno).length();
        int end = content.indexOf("\n@",begin); //next annotation

        if(end > 0){
            result.add(content.substring(begin,end).trim());
            content = content.substring(end);
        }else {
            result.add(content.substring(begin).trim());
            content = ""; //no more
        }
    }

    return result;
}
 
Example #5
Source File: ControllerSourceVisitor.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Add the javadoc content.
 * @param comment JavadocComment on the route method.
 * @param route The route model that we construct.
 */
@Override
public void visit(JavadocComment comment, ControllerRouteModel route) {
    //extract the body sample annotation if present
    route.setBodySamples(extractBodySample(comment));

    //extract the response codes annotation if present
    route.setResponseCodes(extractResponseCodes(comment));

    //extract the response descriptions annotation if present
    route.setResponseDescriptions(extractResponseDescription(comment));

    //extract the response bodies annotation if present
    route.setResponseBodies(extractResponseBodies(comment));

    //extract the description before the jdoc annotation
    route.setDescription(extractDescription(comment));
}
 
Example #6
Source File: Javadoc.java    From actframework with Apache License 2.0 6 votes vote down vote up
/**
 * Create a JavadocComment, by formatting the text of the Javadoc using the given indentation.
 */
public JavadocComment toComment(String indentation) {
    for (char c : indentation.toCharArray()) {
        if (!Character.isWhitespace(c)) {
            throw new IllegalArgumentException("The indentation string should be composed only by whitespace characters");
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append(EOL);
    final String text = toText();
    if (!text.isEmpty()) {
        for (String line : text.split(EOL)) {
            sb.append(indentation);
            sb.append(" * ");
            sb.append(line);
            sb.append(EOL);
        }
    }
    sb.append(indentation);
    sb.append(" ");
    return new JavadocComment(sb.toString());
}
 
Example #7
Source File: AutoDoc.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 * Write the method parameters and it's doc to target api doc
 *
 * @param doc     target doc
 * @param comment parameters and method doc
 **/
private void fillParamDoc(APIDoc doc, JavadocComment comment, StringBuilder methodDesBuilder) {
    Javadoc javadoc = comment.parse();
    toString(javadoc.getDescription(), methodDesBuilder);
    doc.setDesc(methodDesBuilder.toString());
    methodDesBuilder.setLength(0);
    List<JavadocBlockTag> tags = javadoc.getBlockTags();
    if (comment.getCommentedNode().isPresent()) {
        Node node = comment.getCommentedNode().get();
        if (node instanceof MethodDeclaration) {
            MethodDeclaration method = (MethodDeclaration) node;
            for (Parameter p : method.getParameters()) {
                String type = p.getType().asString();
                String name = p.getName().asString();
                List<Param> params = doc.getParams();
                Param param = new Param();
                param.setName(name);
                param.setType(type);
                for (JavadocBlockTag t : tags) {
                    if (t.getName().isPresent()) {
                        if (name.endsWith(t.getName().get())) {
                            toString(t.getContent(), methodDesBuilder);
                            param.setComment(methodDesBuilder.toString());
                            methodDesBuilder.setLength(0);
                        }
                    }
                }
                if (params == null) {
                    params = new ArrayList<>();
                    doc.setParams(params);
                }
                params.add(param);
            }
        }
    }
}
 
Example #8
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration node, Void arg) {
    super.visit(node, arg);

    replaceParentClassesForAtomics(node);

    node.setName(translateQueueName(node.getNameAsString()));
    if (MPSC_LINKED_ATOMIC_QUEUE_NAME.equals(node.getNameAsString())) {
        /*
         * Special case for MPSC
         */
        node.removeModifier(Keyword.ABSTRACT);
    }

    if (isCommentPresent(node, GEN_DIRECTIVE_CLASS_CONTAINS_ORDERED_FIELD_ACCESSORS)) {
        node.setComment(null);
        removeStaticFieldsAndInitialisers(node);
        patchAtomicFieldUpdaterAccessorMethods(node);
    }

    for (MethodDeclaration method : node.getMethods()) {
        if (isCommentPresent(method, GEN_DIRECTIVE_METHOD_IGNORE)) {
            method.remove();
        }
    }

    node.setJavadocComment(formatMultilineJavadoc(0,
            "NOTE: This class was automatically generated by "
                    + JavaParsingAtomicLinkedQueueGenerator.class.getName(),
            "which can found in the jctools-build module. The original source file is " + sourceFileName + ".")
            + node.getJavadocComment().orElse(new JavadocComment("")).getContent());
}
 
Example #9
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration node, Void arg) {
    super.visit(node, arg);

    replaceParentClassesForAtomics(node);

    node.setName(translateQueueName(node.getNameAsString()));

    if (isCommentPresent(node, GEN_DIRECTIVE_CLASS_CONTAINS_ORDERED_FIELD_ACCESSORS)) {
        node.setComment(null);
        removeStaticFieldsAndInitialisers(node);
        patchAtomicFieldUpdaterAccessorMethods(node);
    }

    for (MethodDeclaration method : node.getMethods()) {
        if (isCommentPresent(method, GEN_DIRECTIVE_METHOD_IGNORE)) {
            method.remove();
        }
    }

    if (!node.getMethodsByName("failFastOffer").isEmpty()) {
        MethodDeclaration deprecatedMethodRedirect = node.addMethod("weakOffer", Keyword.PUBLIC);
        patchMethodAsDeprecatedRedirector(deprecatedMethodRedirect, "failFastOffer", PrimitiveType.intType(),
                new Parameter(classType("E"), "e"));
    }

    node.setJavadocComment(formatMultilineJavadoc(0,
            "NOTE: This class was automatically generated by "
                    + JavaParsingAtomicArrayQueueGenerator.class.getName(),
            "which can found in the jctools-build module. The original source file is " + sourceFileName + ".")
            + node.getJavadocComment().orElse(new JavadocComment("")).getContent());
}
 
Example #10
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Get a text description from JavaDoc block comment.
 *
 * @param jdoc the javadoc block comment.
 * @return The description as String.
 */
public static String extractDescription(JavadocComment jdoc){
    String content = jdoc.getContent().replaceAll("\n[ \t]+\\* ?","\n"); //remove the * at the beginning of a line
    int end = content.indexOf("\n@"); //look for the first annotation

    //The first charater is always a new line

    if(end>0) {
        return content.substring(1, end).trim();
    }

    return content.substring(1).trim();
}
 
Example #11
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Return the response bodies as String from a JavaDoc comment block.
 *
 * @param jdoc The javadoc block comment.
 * @return the response bodies as String
 */
public static List<String> extractResponseBodies(JavadocComment jdoc){
	List<String> list = new ArrayList<>();
	list.addAll(extractDocAnnotation(DOC_RESPONSE_BODY,jdoc));

	return list;
}
 
Example #12
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Return the response descriptions as String from a JavaDoc comment block.
 *
 * @param jdoc The javadoc block comment.
 * @return the response descriptions as String
 */
public static List<String> extractResponseDescription(JavadocComment jdoc){
	List<String> list = new ArrayList<>();
	list.addAll(extractDocAnnotation(DOC_RESPONSE_DESCRIPTION,jdoc));

	return list;
}
 
Example #13
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Return the response codes as String from a JavaDoc comment block.
 *
 * @param jdoc The javadoc block comment.
 * @return the response codes as String
 */
public static List<String> extractResponseCodes(JavadocComment jdoc){
	List<String> list = new ArrayList<>();
	list.addAll(extractDocAnnotation(DOC_RESPONSE_CODE,jdoc));

	return list;
}
 
Example #14
Source File: JavadocCommentMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override
public JavadocComment doMerge(JavadocComment first, JavadocComment second) {
  JavadocComment comment = new JavadocComment();

  if(first.getContent().length() > second.getContent().length()){
    comment.setContent(first.getContent());
    copyPosition(first,comment);
  }else {
    comment.setContent(second.getContent());
    copyPosition(second,comment);
  }

  return comment;
}
 
Example #15
Source File: PackageInfoReader.java    From jig with Apache License 2.0 5 votes vote down vote up
private Optional<Javadoc> getJavadoc(CompilationUnit cu) {
    // NodeWithJavadoc#getJavadocでやってることと同じことをする
    return cu.getComment()
            .filter(comment -> comment instanceof JavadocComment)
            .map(comment -> (JavadocComment) comment)
            .map(JavadocComment::parse);
}
 
Example #16
Source File: JavadocUtils.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a javadoc comment object given a comment string.
 *
 * @param comment Comment.
 * @param indentation Indentation.
 * @return Javadoc comment object.
 */
public JavadocComment createJavadocComment(String comment, String indentation) {
  JavadocSnippet javadocSnippet = new JavadocSnippet("");
  if (StringUtils.isNotEmpty(comment)) {
    javadocSnippet = new JavadocSnippet(comment);
  }

  JavadocDescription description = new JavadocDescription();
  description.addElement(javadocSnippet);
  Javadoc javadoc = new Javadoc(description);
  return javadoc.toComment(indentation);
}
 
Example #17
Source File: PackageDocScanParser.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<String, JavadocComment>> parse() {
    Map<String, Map<String, JavadocComment>> serviceMethodsMap = new HashMap<>();
    Map<String, Class> classMap = packageScan();
    for (Map.Entry<String, Class> entry : classMap.entrySet()) {
        String path = PackageParser.getSrcPath(entry.getKey());
        File srcFile = new File(path);
        int simpleNameStart = entry.getKey().lastIndexOf(".");
        String serviceName = entry.getKey().substring(simpleNameStart + 1);
        serviceMethodsMap.put(serviceName, parseDoc(srcFile));
    }
    processInterfaceExtend(classMap, serviceMethodsMap);
    return serviceMethodsMap;
}
 
Example #18
Source File: JavaParserTest.java    From molicode with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    CompilationUnit compilationUnit = new CompilationUnit();
    ClassOrInterfaceDeclaration myClass = compilationUnit
            .addClass("MyClass")
            .setPublic(true);
    myClass.addField(int.class, "A_CONSTANT", PUBLIC, STATIC);
    myClass.addField(String.class, "name", PRIVATE);
    Comment comment= new JavadocComment();
    comment.setContent("你大爷!");
    myClass.addMethod("helloWorld", PUBLIC).setParameters(NodeList.nodeList()).setComment(comment);
    String code = myClass.toString();
    System.out.println(code);
}
 
Example #19
Source File: Javadoc.java    From actframework with Apache License 2.0 4 votes vote down vote up
/**
 * Create a JavadocComment, by formatting the text of the Javadoc using no indentation (expecting the pretty printer to do the formatting.)
 */
public JavadocComment toComment() {
    return toComment("");
}
 
Example #20
Source File: JavadocParser.java    From actframework with Apache License 2.0 4 votes vote down vote up
public static Javadoc parse(JavadocComment comment) {
    return parse(comment.getContent());
}
 
Example #21
Source File: JavadocCommentMerger.java    From dolphin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean doIsEquals(JavadocComment first, JavadocComment second) {
  return similarity(first.getContent(), second.getContent()) > 0.9d;
}
 
Example #22
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void visit(final JavadocComment n, final Void arg) {
    printer.print("/**");
    printer.print(n.getContent());
    printer.println("*/");
}
 
Example #23
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(JavadocComment n, Void arg) {
    out.println("JavadocComment: " + (extended ? n : n.getContent()));
    super.visit(n, arg);
}
 
Example #24
Source File: ControllerSourceVisitor.java    From wisdom with Apache License 2.0 3 votes vote down vote up
/**
 * Visit the Controller JavaDoc block.
 * <p>
 * Add the JavadocComment as the ControllerModel description.
 * Set the ControllerModel version as the javadoc version tag if it exists.
 * </p>
 *
 * @param jdoc {@inheritDoc}
 * @param controller The ControllerModel we are building.
 */
@Override
public void visit(JavadocComment jdoc, ControllerModel controller) {
    controller.setDescription(extractDescription(jdoc));

    Set<String> version = extractDocAnnotation("@version",jdoc);
    if(!version.isEmpty()){
        controller.setVersion(version.iterator().next());
    }
}
 
Example #25
Source File: JavaSourceUtils.java    From dolphin with Apache License 2.0 3 votes vote down vote up
public static AnnotationDeclaration mergeType(AnnotationDeclaration one, AnnotationDeclaration two) {

        if (isAllNull(one, two)) return null;

        AnnotationDeclaration annotationDeclaration = null;

        if (isAllNotNull(one, two)) {

            annotationDeclaration = new AnnotationDeclaration();

            annotationDeclaration.setModifiers(
                    mergeModifiers(one.getModifiers(), two.getModifiers()));

            annotationDeclaration.setJavaDoc(
                    (JavadocComment) mergeSelective(one.getJavaDoc(), two.getJavaDoc()));

            annotationDeclaration.setComment(mergeSelective(one.getComment(), two.getComment()));

            annotationDeclaration.setAnnotations(
                    mergeListNoDuplicate(one.getAnnotations(), two.getAnnotations()));

            // merge content body
            annotationDeclaration.setMembers(mergeBodies(one.getMembers(), two.getMembers()));

            LOG.info("merge AnnotationDeclaration --> {}", annotationDeclaration.getName());

        } else {
            annotationDeclaration = findFirstNotNull(one, two);
            LOG.info("add AnnotationDeclaration --> {}", annotationDeclaration.getName());
        }

        return annotationDeclaration;
    }
 
Example #26
Source File: ExtractUtil.java    From wisdom with Apache License 2.0 2 votes vote down vote up
/**
 * Return the body samples as String from a JavaDoc comment block.
 *
 * @param jdoc The javadoc block comment.
 * @return the body samples as String
 */
public static Set<String> extractBodySample(JavadocComment jdoc){
	return extractDocAnnotation(DOC_BODY_SAMPLE,jdoc);
}