com.github.javaparser.ast.PackageDeclaration Java Examples

The following examples show how to use com.github.javaparser.ast.PackageDeclaration. 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: JavaSourceUtils.java    From dolphin with Apache License 2.0 6 votes vote down vote up
public static String mergeContent(CompilationUnit one, CompilationUnit two) throws Exception {

        // 包声明不同,返回null
        if (!one.getPackage().equals(two.getPackage())) return null;

        CompilationUnit cu = new CompilationUnit();

        // add package declaration to the compilation unit
        PackageDeclaration pd = new PackageDeclaration();
        pd.setName(one.getPackage().getName());
        cu.setPackage(pd);

        // check and merge file comment;
        Comment fileComment = mergeSelective(one.getComment(), two.getComment());
        cu.setComment(fileComment);

        // check and merge imports
        List<ImportDeclaration> ids = mergeListNoDuplicate(one.getImports(), two.getImports());
        cu.setImports(ids);

        // check and merge Types
        List<TypeDeclaration> types = mergeTypes(one.getTypes(), two.getTypes());
        cu.setTypes(types);

        return cu.toString();
    }
 
Example #3
Source File: ImpSort.java    From impsort-maven-plugin with Apache License 2.0 5 votes vote down vote up
static void removeSamePackageImports(Set<Import> imports,
    Optional<PackageDeclaration> packageDeclaration) {
  String packageName = packageDeclaration.map(p -> p.getName().toString()).orElse("");
  imports.removeIf(i -> {
    String imp = i.getImport();
    if (packageName.isEmpty()) {
      return !imp.contains(".");
    }
    return imp.startsWith(packageName) && imp.lastIndexOf(".") <= packageName.length();
  });

}
 
Example #4
Source File: JavaparserTest.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
  CompilationUnit cu = new CompilationUnit();
  // set the package
  cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("java.parser.test")));

  // create the type declaration
  ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "GeneratedClass");
  ASTHelper.addTypeDeclaration(cu, type);

  // create a method
  MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
  method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
  ASTHelper.addMember(type, method);

  // add a parameter to the method
  Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 0), "args");
  param.setVarArgs(true);
  ASTHelper.addParameter(method, param);

  // add a body to the method
  BlockStmt block = new BlockStmt();
  method.setBody(block);

  // add a statement do the method body
  NameExpr clazz = new NameExpr("System");
  FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
  MethodCallExpr call = new MethodCallExpr(field, "println");
  ASTHelper.addArgument(call, new StringLiteralExpr("Hello World!"));
  ASTHelper.addStmt(block, call);

  unit = cu;
}
 
Example #5
Source File: PackageDeclarationMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public PackageDeclaration doMerge(PackageDeclaration first, PackageDeclaration second) {
  PackageDeclaration packageDeclaration = new PackageDeclaration();

  packageDeclaration.setName(first.getName());
  packageDeclaration.setAnnotations(mergeCollections(first.getAnnotations(),second.getAnnotations()));

  return packageDeclaration;
}
 
Example #6
Source File: ApiManager.java    From actframework with Apache License 2.0 5 votes vote down vote up
private static String name(Node node) {
    S.Buffer buffer = S.newBuffer();
    Node parent = node.getParentNode();
    if (null != parent) {
        buffer.append(name(parent));
    }
    if (node instanceof NamedNode) {
        buffer.append(".").append(((NamedNode) node).getName());
    } else if (node instanceof CompilationUnit) {
        CompilationUnit unit = $.cast(node);
        PackageDeclaration pkg = unit.getPackage();
        return pkg.getPackageName();
    }
    return buffer.toString();
}
 
Example #7
Source File: FormTask.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void execute(PathResolver pathResolver) throws Exception {
    CompilationUnit cu = new CompilationUnit();
    String basePackage = BasePackageDetector.detect();
    cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr(basePackage + "form")));

    ClassOrInterfaceDeclaration formClass = new ClassOrInterfaceDeclaration(
            ModifierSet.PUBLIC, false, CaseConverter.pascalCase(tableName) + "Form");
    ASTHelper.addTypeDeclaration(cu, formClass);
    formClass.setExtends(Collections.singletonList(
            new ClassOrInterfaceType("FormBase")
    ));

    fields.stream()
            .filter(f -> !f.isId())
            .forEach(f -> ASTHelper.addMember(formClass, fieldDeclaration(f)));
    fields.stream()
            .filter(f -> !f.isId())
            .forEach(f -> ASTHelper.addMember(formClass, getterDeclaration(f)));
    fields.stream()
            .filter(f -> !f.isId())
            .forEach(f -> ASTHelper.addMember(formClass, setterDeclaration(f)));

    try (Writer writer = new OutputStreamWriter(pathResolver.destinationAsStream(destination))) {
        writer.write(cu.toString());
    }
}
 
Example #8
Source File: ImpSortTest.java    From impsort-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveSamePackageImports() {
  Set<Import> imports = Stream
      .of(new Import(false, "abc.Blah", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.ef.Blah.Blah", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.ef.Blah2", "", "", LineEnding.AUTO.getChars()),
          new Import(false, "abcd.efg.Blah2", "", "", LineEnding.AUTO.getChars()))
      .collect(Collectors.toSet());
  assertEquals(4, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports, Optional.empty());
  assertEquals(4, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports,
      Optional.of(new PackageDeclaration(new Name("abcd.ef"))));
  assertEquals(3, imports.size());
  assertTrue(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertFalse(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
  ImpSort.removeSamePackageImports(imports, Optional.of(new PackageDeclaration(new Name("abc"))));
  assertEquals(2, imports.size());
  assertFalse(imports.stream().anyMatch(imp -> "abc.Blah".equals(imp.getImport())));
  assertFalse(imports.stream().anyMatch(imp -> "abcd.ef.Blah2".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.ef.Blah.Blah".equals(imp.getImport())));
  assertTrue(imports.stream().anyMatch(imp -> "abcd.efg.Blah2".equals(imp.getImport())));
}
 
Example #9
Source File: AbsControllerParser.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
private void parseClassDoc(ClassOrInterfaceDeclaration c) {

        c.getParentNode().get().findFirst(PackageDeclaration.class).ifPresent(pd -> {
            controllerNode.setPackageName(pd.getNameAsString());
        });

        boolean generateDocs = c.getAnnotationByName("ApiDoc").isPresent();
        controllerNode.setGenerateDocs(generateDocs);

        c.getJavadoc().ifPresent(d -> {
            String description = d.getDescription().toText();
            controllerNode.setDescription(Utils.isNotEmpty(description) ? description : c.getNameAsString());
            List<JavadocBlockTag> blockTags = d.getBlockTags();
            if (blockTags != null) {
                for (JavadocBlockTag blockTag : blockTags) {
                    if ("author".equalsIgnoreCase(blockTag.getTagName())) {
                        controllerNode.setAuthor(blockTag.getContent().toText());
                    }
                    if ("description".equalsIgnoreCase(blockTag.getTagName())) {
                        controllerNode.setDescription(blockTag.getContent().toText());
                    }
                }
            }
        });

        if (controllerNode.getDescription() == null) {
            controllerNode.setDescription(c.getNameAsString());
        }
    }
 
Example #10
Source File: FileService.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * This method returns all root folders' absolute paths of the given java files
 * (like the src folder or the src/main/java folder of maven projects)
 * 
 * @param allJavaFiles
 * @return javaRoots
 * @throws FileNotFoundException
 */
public List<String> findJavaRoots(List<String> allJavaFiles) throws FileNotFoundException {
	Set<String> javaRoots = new HashSet<>();

	for (String javaFile : allJavaFiles) {
		FileInputStream filepath = new FileInputStream(javaFile);

		CompilationUnit compilationUnit;
                       
		try {
			compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(filepath));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			continue;
		}

		File file = new File(javaFile);
		List<PackageDeclaration> packageDeclarations = compilationUnit.findAll(PackageDeclaration.class);
		if (!packageDeclarations.isEmpty()) {
			// current java file should contain exactly one package declaration
			PackageDeclaration packageDeclaration = packageDeclarations.get(0);
			String rootPackage = packageDeclaration.getNameAsString().split("\\.")[0];
			String javaRoot = file.getAbsolutePath()
					.split(Pattern.quote(File.separator) + rootPackage + Pattern.quote(File.separator))[0];

                               // If we have a made-up package name the path will not exist, so we don't add it
                               if (Files.exists(Paths.get(javaRoot))) {
                                   javaRoots.add(javaRoot);
                               }
		}
	}
	return new ArrayList<>(javaRoots);
}
 
Example #11
Source File: ClassReader.java    From jig with Apache License 2.0 5 votes vote down vote up
TypeSourceResult read(JavaSource javaSource) {
    CompilationUnit cu = StaticJavaParser.parse(javaSource.toInputStream());

    String packageName = cu.getPackageDeclaration()
            .map(PackageDeclaration::getNameAsString)
            .map(name -> name + ".")
            .orElse("");

    ClassVisitor typeVisitor = new ClassVisitor(packageName);
    cu.accept(typeVisitor, null);

    return typeVisitor.toTypeSourceResult();
}
 
Example #12
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final PackageDeclaration n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printAnnotations(n.getAnnotations(), false, arg);
    printer.print("package ");
    n.getName().accept(this, arg);
    printer.println(";");
    printer.println();

    printOrphanCommentsEnding(n);
}
 
Example #13
Source File: JavaFileAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected String calculatePrefix(@Nonnull Qualifier<?> topQualifier) {
    PackageDeclaration aPackage = Nodes.getCompilationUnit(topQualifier.getNode()).getPackage();
    if (aPackage == null) {
        return "";
    }
    return prepend(aPackage.getName(), new StringBuilder("")).append(".").toString();
}
 
Example #14
Source File: FlywayTask.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void execute(PathResolver pathResolver) throws Exception {
    CompilationUnit cu = new CompilationUnit();
    cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("db.migration")));
    List<ImportDeclaration> imports = new ArrayList<>();
    imports.add(new ImportDeclaration(ASTHelper.createNameExpr("org.flywaydb.core.api.migration.BaseJavaMigration"), false, false));
    imports.add(new ImportDeclaration(ASTHelper.createNameExpr("org.flywaydb.core.api.migration.Context"), false, false));
    imports.add(new ImportDeclaration(ASTHelper.createNameExpr("java.sql.Statement"), false, false));
    cu.setImports(imports);

    String version = LocalDateTime.now().format(VERSION_FMT);
    ClassOrInterfaceDeclaration migrationClass = new ClassOrInterfaceDeclaration(
            ModifierSet.PUBLIC, false, "V" + version + "__Create"
            + CaseConverter.pascalCase(tableName));
    ASTHelper.addTypeDeclaration(cu, migrationClass);

    List<ClassOrInterfaceType> extendsList = new ArrayList<>();
    extendsList.add(new ClassOrInterfaceType("BaseJavaMigration"));
    migrationClass.setExtends(extendsList);

    MethodDeclaration migrateMethod = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "migrate");
    ASTHelper.addMember(migrationClass, migrateMethod);
    ASTHelper.addParameter(migrateMethod, ASTHelper.createParameter(
            ASTHelper.createReferenceType("Context", 0), "context"
    ));
    migrateMethod.setThrows(Collections.singletonList(ASTHelper.createNameExpr("Exception")));

    List<AnnotationExpr> annotations = new ArrayList<>();
    annotations.add(new MarkerAnnotationExpr(ASTHelper.createNameExpr("Override")));
    migrateMethod.setAnnotations(annotations);

    BlockStmt block = new BlockStmt();
    migrateMethod.setBody(block);

    TryStmt tryStmt = new TryStmt(createStatementExecuteBlock(), null, null);
    tryStmt.setResources(Collections.singletonList(createAssignStatement()));
    ASTHelper.addStmt(block, tryStmt);

    try (Writer writer = new OutputStreamWriter(
            pathResolver.destinationAsStream(
                    "src/main/java/db/migration/" + migrationClass.getName() + ".java"))) {
        writer.write(cu.toString());
    }
}
 
Example #15
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration n, Void arg) {
    out.println("PackageDeclaration: " + (extended ? n : ""));
    super.visit(n, arg);
}
 
Example #16
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration n, Void arg) {
    super.visit(n, arg);
    // Change the package of the output
    n.setName("org.jctools.queues.atomic");
}
 
Example #17
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration n, Object ignored) {
  packageName = n.getNameAsString();
  super.visit(n, ignored);
}
 
Example #18
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration packageDeclaration, Void arg) {
    packageName = packageDeclaration.getNameAsString();
    super.visit(packageDeclaration, arg);
}
 
Example #19
Source File: ParameterNameVisitor.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration n, Object arg) {
  this.pkg = n.getName().toString();
  super.visit(n, arg);
}
 
Example #20
Source File: SourceCodeProcessHandler.java    From molicode with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(PackageDeclaration n, Void arg) {
    sourceCodeDto.setPackageName(n.getNameAsString());
    super.visit(n, arg);
}
 
Example #21
Source File: AnnotatedClassPostProcessor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
String packageName() {
    return unitClass.getPackageDeclaration().map(PackageDeclaration::getNameAsString).orElse("");
}
 
Example #22
Source File: MyShellCallback.java    From mapper-generator-javafx with Apache License 2.0 4 votes vote down vote up
/**
 * merge java bean
 *
 * @param newCompilationUnit      新的
 * @param existingCompilationUnit 旧的
 * @return merge 后的
 */
private String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {

    Optional<PackageDeclaration> newPackageDeclaration = newCompilationUnit.getPackageDeclaration();
    newPackageDeclaration.ifPresent(existingCompilationUnit::setPackageDeclaration);

    //合并imports
    NodeList<ImportDeclaration> oldImports = existingCompilationUnit.getImports();
    NodeList<ImportDeclaration> newImports = newCompilationUnit.getImports();
    oldImports.addAll(newImports);
    Set<ImportDeclaration> importSet = new HashSet<>(oldImports);

    existingCompilationUnit.setImports(new NodeList<>(importSet));

    //处理类 comment
    TypeDeclaration<?> newType = newCompilationUnit.getTypes().get(0);
    TypeDeclaration<?> existType = existingCompilationUnit.getTypes().get(0);
    newType.getComment().ifPresent(existType::setComment);

    List<FieldDeclaration> existFields = existType.getFields();
    List<FieldDeclaration> newFields = newType.getFields();

    //合并fields
    int size = newFields.size();
    for (int i = 0; i < size; i++) {
        FieldDeclaration existField = newFields.get(0);
        VariableDeclarator existVar = existField.getVariables().get(0);
        for (FieldDeclaration newField : existFields) {
            VariableDeclarator newVar = newField.getVariables().get(0);
            // 名称相同
            if (newVar.getName().equals(existVar.getName())) {
                // 名称相同 且 类型相同
                if (newVar.getTypeAsString().equals(existVar.getTypeAsString())) {
                    newType.getComment().ifPresent(existType::setComment);
                } else {

                }
            }
        }

        //合并methods
    }

    return existingCompilationUnit.toString();
}
 
Example #23
Source File: PackageDeclarationMerger.java    From dolphin with Apache License 2.0 2 votes vote down vote up
@Override public boolean doIsEquals(PackageDeclaration first, PackageDeclaration second) {

    if(!first.getName().equals(second.getName())) return false;

    return true;
  }