Java Code Examples for com.github.javaparser.StaticJavaParser

The following examples show how to use com.github.javaparser.StaticJavaParser. These examples are extracted from open source projects. 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 Project: joyqueue   Source File: PackageDocScanParser.java    License: 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 2
Source Project: jig   Source File: PackageInfoReader.java    License: Apache License 2.0 6 votes vote down vote up
Optional<PackageAlias> read(PackageInfoSource packageInfoSource) {
    CompilationUnit cu = StaticJavaParser.parse(packageInfoSource.toInputStream());

    Optional<PackageIdentifier> optPackageIdentifier = cu.getPackageDeclaration()
            .map(NodeWithName::getNameAsString)
            .map(PackageIdentifier::new);

    Optional<Alias> optAlias = getJavadoc(cu)
            .map(Javadoc::getDescription)
            .map(JavadocDescription::toText)
            .map(JavadocAliasSource::new)
            .map(JavadocAliasSource::toAlias);

    return optPackageIdentifier.flatMap(packageIdentifier -> optAlias.map(alias ->
            new PackageAlias(packageIdentifier, alias)));
}
 
Example 3
Source Project: Refactoring-Bot   Source File: AddOverrideAnnotation.java    License: MIT License 6 votes vote down vote up
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	String path = issue.getFilePath();

	FileInputStream in = new FileInputStream(gitConfig.getRepoFolder() + "/" + path);
	CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in));

	MethodDeclaration methodDeclarationToModify = RefactoringHelper
			.getMethodDeclarationByLineNumber(issue.getLine(), compilationUnit);
	if (methodDeclarationToModify == null) {
		throw new BotRefactoringException("Could not find a method declaration at specified line!");
	}
	if (isOverrideAnnotationExisting(methodDeclarationToModify)) {
		throw new BotRefactoringException("Method is already annotated with 'Override'!");
	}

	methodDeclarationToModify.addMarkerAnnotation(OVERRIDE_ANNOTATION_NAME);

	// Save changes to file
	PrintWriter out = new PrintWriter(gitConfig.getRepoFolder() + "/" + path);
	out.println(LexicalPreservingPrinter.print(compilationUnit));
	out.close();

	// Return commit message
	return "Added override annotation to method '" + methodDeclarationToModify.getNameAsString() + "'";
}
 
Example 4
Source Project: Refactoring-Bot   Source File: RemoveMethodParameterTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in an interface
 * implemented by the target class
 * 
 * @throws Exception
 */
@Test
public void testInterfaceRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfInterface);
	int lineNumberOfMethodWithParameterToBeRemoved = removeParameterTestClass.getLineOfMethodWithUnusedParameter(0,
			0, 0);
	String parameterName = "b";

	// act
	performRemoveParameter(filesToConsider, fileOfTestClass, lineNumberOfMethodWithParameterToBeRemoved,
			parameterName);

	// assert that method in interface has been refactored
	CompilationUnit cuRefactoredFileOfInterface = StaticJavaParser.parse(fileOfInterface);
	List<MethodDeclaration> methodDeclarations = cuRefactoredFileOfInterface.findAll(MethodDeclaration.class);
	assertThat(methodDeclarations).size().isEqualTo(1);
	assertThat(methodDeclarations.get(0).getParameterByName(parameterName).isPresent()).isFalse();
}
 
Example 5
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in a different class
 * which contains a method calling the refactored target method
 * 
 * @throws Exception
 */
@Test
public void testCallerClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileWithCallerMethod);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfMethodToBeRenamed(true);
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that caller method in different file has been refactored
	CompilationUnit cuRefactoredFileWithCallerMethod = StaticJavaParser.parse(fileWithCallerMethod);
	int lineNumberOfCallerInDifferentFile = renameMethodCallerTestClass.getLineOfCallerMethodInDifferentFile();
	assertThatNumberOfMethodCallsIsEqualToExpected(cuRefactoredFileWithCallerMethod,
			lineNumberOfCallerInDifferentFile, newMethodName, 1);
}
 
Example 6
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in the super class of
 * the target class (ancestor)
 * 
 * @throws Exception
 */
@Test
public void testSuperClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfSuperClass);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfMethodToBeRenamed(true);
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that target's super class has been refactored
	CompilationUnit cuRefactoredFileOfSuperClass = StaticJavaParser.parse(fileOfSuperClass);
	int lineNumberOfMethodInSuperClass = renameMethodSuperClass.getLineOfMethodToBeRenamed(true);
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfSuperClass, lineNumberOfMethodInSuperClass,
			newMethodName);
}
 
Example 7
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in the sub class of the
 * target class (descendant)
 * 
 * @throws Exception
 */
@Test
public void testSubClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfSubClass);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfMethodToBeRenamed(true);
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that target's sub class has been refactored
	CompilationUnit cuRefactoredFileOfSubClass = StaticJavaParser.parse(fileOfSubClass);
	int lineNumberOfMethodInSubClass = renameMethodSubClass.getLineOfMethodToBeRenamed(true);
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfSubClass, lineNumberOfMethodInSubClass, newMethodName);
}
 
Example 8
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in the sibling class of
 * the target class
 * 
 * @throws Exception
 */
@Test
public void testSiblingClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfSiblingClass);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfMethodToBeRenamed(true);
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert
	CompilationUnit cuRefactoredFileOfSiblingClass = StaticJavaParser.parse(fileOfSiblingClass);

	// assert that target's sibling has been refactored
	int lineNumberOfMethodInSiblingClass = renameMethodSiblingClass.getLineOfMethodToBeRenamed(true);
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfSiblingClass, lineNumberOfMethodInSiblingClass,
			newMethodName);

	// assert that caller method in target's sibling class has been refactored
	int lineNumberOfCallerMethodInSiblingClass = renameMethodSiblingClass.getLineNumberOfCallerInSiblingClass();
	assertThatNumberOfMethodCallsIsEqualToExpected(cuRefactoredFileOfSiblingClass,
			lineNumberOfCallerMethodInSiblingClass, newMethodName, 1);
}
 
Example 9
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test whether the refactoring was performed correctly in an interface
 * implemented by the target class
 * 
 * @throws Exception
 */
@Test
public void testInterfaceRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfInterface);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfInterfaceMethod();
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that method in interface has been refactored
	CompilationUnit cuRefactoredFileOfInterface = StaticJavaParser.parse(fileOfInterface);
	List<MethodDeclaration> methodDeclarations = cuRefactoredFileOfInterface.findAll(MethodDeclaration.class);
	assertThat(methodDeclarations).size().isEqualTo(1);
	assertThat(methodDeclarations.get(0).getNameAsString()).isEqualTo(newMethodName);
}
 
Example 10
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * The target class extends a super class and implements an interface. Test that
 * the super class was correctly refactored
 * 
 * @throws Exception
 */
@Test
public void testInterfaceMethodInSuperClassRefactored() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfInterface);
	filesToConsider.add(fileOfSuperClass);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfInterfaceMethod();
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that method in super class has been refactored
	CompilationUnit cuRefactoredFileOfSuperClass = StaticJavaParser.parse(fileOfSuperClass);
	int lineNumberOfMethodInSuperClass = renameMethodSuperClass.getLineOfInterfaceMethod();
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfSuperClass, lineNumberOfMethodInSuperClass,
			newMethodName);
}
 
Example 11
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test that the refactoring algorithm finds the correct method in case that
 * there is an inner class before the target method declaration
 * 
 * @throws Exception
 */
@Test
public void testRenamingOfMethodPlacedAfterInnerClass() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClass.getLineOfMethodPlacedInAndAfterInnerClass();
	String newMethodName = "newMethodName";

	// act
	performRenameMethod(filesToConsider, fileOfTestClass, lineNumberOfMethodToBeRenamed, newMethodName);

	// assert that method in outer class (the method for which the actual renaming
	// was intended) has been refactored
	CompilationUnit cuRefactoredFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfTestClass, lineNumberOfMethodToBeRenamed,
			newMethodName);
}
 
Example 12
Source Project: Refactoring-Bot   Source File: RefactoringHelperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testIsLocalMethodSignatureInClassOrInterface() throws FileNotFoundException {
	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	Optional<ClassOrInterfaceDeclaration> clazz = cu.getClassByName(TARGET_CLASS_NAME);
	assertThat(clazz).isPresent();

	// act
	boolean actual1 = RefactoringHelper.isLocalMethodSignatureInClassOrInterface(clazz.get(),
			LOCAL_METHOD_SIGNATURE);
	boolean actual2 = RefactoringHelper.isLocalMethodSignatureInClassOrInterface(clazz.get(),
			"not-present-in-class");

	// assert
	assertThat(actual1).isTrue();
	assertThat(actual2).isFalse();
}
 
Example 13
Source Project: Refactoring-Bot   Source File: RefactoringHelperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetMethodByLineNumberOfMethodName() throws FileNotFoundException {
	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	int lineNumber = TestDataClassRefactoringHelper.getLineOfMethod(true);

	// act
	MethodDeclaration method = RefactoringHelper.getMethodDeclarationByLineNumber(lineNumber, cu);

	// assert
	assertThat(method).isNotNull();
	assertThat(method.getDeclarationAsString()).isEqualTo("public static int getLineOfMethod(boolean parm)");

	// act
	boolean isMethodDeclarationAtLineNumber = RefactoringHelper.isMethodDeclarationAtLine(method, lineNumber);

	// assert
	assertThat(isMethodDeclarationAtLineNumber).isTrue();
}
 
Example 14
Source Project: Refactoring-Bot   Source File: RefactoringHelperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetClassOrInterfaceOfMethod() throws FileNotFoundException {
	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	int lineNumber = TestDataClassRefactoringHelper.getLineOfMethod(true);

	MethodDeclaration methodDeclaration = RefactoringHelper.getMethodDeclarationByLineNumber(lineNumber, cu);
	assertThat(methodDeclaration).isNotNull();

	// act
	ClassOrInterfaceDeclaration classOrInterface = RefactoringHelper.getClassOrInterfaceOfMethod(methodDeclaration);

	// assert
	assertThat(classOrInterface).isNotNull();
	assertThat(classOrInterface.getNameAsString()).isEqualTo(TARGET_CLASS_NAME);
}
 
Example 15
Source Project: Refactoring-Bot   Source File: RefactoringHelperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetQualifiedMethodSignatureAsString() throws FileNotFoundException, BotRefactoringException {
	configureStaticJavaParserForResolving();

	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	int lineNumber = TestDataClassRefactoringHelper.getLineOfMethod(true);
	MethodDeclaration targetMethod = RefactoringHelper.getMethodDeclarationByLineNumber(lineNumber, cu);
	assertThat(targetMethod).isNotNull();

	// act
	String qualifiedMethodSignature = RefactoringHelper.getQualifiedMethodSignatureAsString(targetMethod);

	// assert
	assertThat(qualifiedMethodSignature).isEqualTo(
			"de.refactoringbot.resources.refactoringhelper.TestDataClassRefactoringHelper.getLineOfMethod(boolean)");
}
 
Example 16
Source Project: quarkus   Source File: JavaDocParser.java    License: Apache License 2.0 6 votes vote down vote up
public String parseConfigDescription(String javadocComment) {
    if (javadocComment == null || javadocComment.trim().isEmpty()) {
        return Constants.EMPTY;
    }

    // the parser expects all the lines to start with "* "
    // we add it as it has been previously removed
    javadocComment = START_OF_LINE.matcher(javadocComment).replaceAll("* ");
    Javadoc javadoc = StaticJavaParser.parseJavadoc(javadocComment);

    if (isAsciidoc(javadoc)) {
        return handleEolInAsciidoc(javadoc);
    }

    return htmlJavadocToAsciidoc(javadoc.getDescription());
}
 
Example 17
Source Project: quarkus   Source File: JavaDocParser.java    License: Apache License 2.0 6 votes vote down vote up
public SectionHolder parseConfigSection(String javadocComment, int sectionLevel) {
    if (javadocComment == null || javadocComment.trim().isEmpty()) {
        return new SectionHolder(Constants.EMPTY, Constants.EMPTY);
    }

    // the parser expects all the lines to start with "* "
    // we add it as it has been previously removed
    javadocComment = START_OF_LINE.matcher(javadocComment).replaceAll("* ");
    Javadoc javadoc = StaticJavaParser.parseJavadoc(javadocComment);

    if (isAsciidoc(javadoc)) {
        final String details = handleEolInAsciidoc(javadoc);
        final int endOfTitleIndex = details.indexOf(Constants.DOT);
        final String title = details.substring(0, endOfTitleIndex).replaceAll("^([^\\w])+", Constants.EMPTY).trim();
        return new SectionHolder(title, details);
    }

    return generateConfigSection(javadoc, sectionLevel);
}
 
Example 18
Source Project: kogito-runtimes   Source File: RuleUnitPojoGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ClassOrInterfaceDeclaration classOrInterfaceDeclaration() {
    ClassOrInterfaceDeclaration c =
            new ClassOrInterfaceDeclaration()
                    .setPublic(true)
                    .addImplementedType(RuleUnitData.class.getCanonicalName())
                    .setName(ruleUnitDescription.getSimpleName());

    for (RuleUnitVariable v : ruleUnitDescription.getUnitVarDeclarations()) {
        ClassOrInterfaceType t = new ClassOrInterfaceType()
                .setName(v.getType().getCanonicalName());
        FieldDeclaration f = new FieldDeclaration();
        VariableDeclarator vd = new VariableDeclarator(t, v.getName());
        f.getVariables().add(vd);
        if (v.isDataSource()) {
            t.setTypeArguments( StaticJavaParser.parseType( v.getDataSourceParameterType().getCanonicalName() ) );
            if (ruleUnitHelper.isAssignableFrom(DataStore.class, v.getType())) {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createStore()");
            } else {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createSingleton()");
            }
        }
        c.addMember(f);
        f.createGetter();
        if (v.setter() != null) {
            f.createSetter();
        }
    }

    return c;
}
 
Example 19
public static AnnotatedClassPostProcessor scan(Stream<Path> files) {
    List<CompilationUnit> annotatedUnits = files
            .peek(System.out::println)
            .map(p -> {
                try {
                    return StaticJavaParser.parse(p);
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }).filter(cu -> cu.findFirst(AnnotationExpr.class, ann -> ann.getNameAsString().endsWith("When")).isPresent())
            .collect(Collectors.toList());

    return new AnnotatedClassPostProcessor(annotatedUnits);
}
 
Example 20
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
    //        FieldDeclaration dmnRuntimeField = new FieldDeclaration().addModifier(Modifier.Keyword.STATIC)
    //                                                                 .addVariable(new VariableDeclarator().setType(DMNRuntime.class.getCanonicalName())
    //                                                                                                      .setName("dmnRuntime")
    //                                                                                                      .setInitializer(new MethodCallExpr("org.kie.dmn.kogito.rest.quarkus.DMNKogitoQuarkus.createGenericDMNRuntime")));
    //        ClassOrInterfaceDeclaration cls = super.classDeclaration();
    //        cls.addModifier(Modifier.Keyword.STATIC);
    //        cls.addMember(dmnRuntimeField);
    //
    //        MethodDeclaration getDecisionMethod = new MethodDeclaration().setName("getDecision")
    //                                                                     .setType(Decision.class.getCanonicalName())
    //                                                                     .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "namespace"))
    //                                                                     .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "name"))
    //        ;
    //        cls.addMember(getDecisionMethod);
    CompilationUnit clazz = StaticJavaParser.parse(this.getClass().getResourceAsStream(TEMPLATE_JAVA));
    ClassOrInterfaceDeclaration typeDeclaration = (ClassOrInterfaceDeclaration) clazz.getTypes().get(0);
    ClassOrInterfaceType applicationClass = StaticJavaParser.parseClassOrInterfaceType(applicationCanonicalName);
    ClassOrInterfaceType inputStreamReaderClass = StaticJavaParser.parseClassOrInterfaceType(java.io.InputStreamReader.class.getCanonicalName());
    for (DMNResource resource : resources) {
        MethodCallExpr getResAsStream = getReadResourceMethod( applicationClass, resource );
        ObjectCreationExpr isr = new ObjectCreationExpr().setType(inputStreamReaderClass).addArgument(getResAsStream);
        Optional<FieldDeclaration> dmnRuntimeField = typeDeclaration.getFieldByName("dmnRuntime");
        Optional<Expression> initalizer = dmnRuntimeField.flatMap(x -> x.getVariable(0).getInitializer());
        if (initalizer.isPresent()) {
            initalizer.get().asMethodCallExpr().addArgument(isr);
        } else {
            throw new RuntimeException("The template " + TEMPLATE_JAVA + " has been modified.");
        }
    }
    if (useTracing) {
        VariableDeclarator execIdSupplierVariable = typeDeclaration.getFieldByName("execIdSupplier")
                .map(x -> x.getVariable(0))
                .orElseThrow(() -> new RuntimeException("Can't find \"execIdSupplier\" field in " + TEMPLATE_JAVA));
        execIdSupplierVariable.setInitializer(newObject(DmnExecutionIdSupplier.class));
    }
    return typeDeclaration;
}
 
Example 21
Source Project: openapi-generator   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void assertValidJavaSourceCode(String javaSourceCode, String filename) {
    try {
        CompilationUnit compilation = StaticJavaParser.parse(javaSourceCode);
        assertTrue(compilation.getTypes().size() > 0, "File: " + filename);
    }
    catch (ParseProblemException ex) {
        fail("Java parse problem: " + filename, ex);
    }
}
 
Example 22
Source Project: jig   Source File: ClassReader.java    License: 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 23
Source Project: Refactoring-Bot   Source File: FileService.java    License: 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 24
Source Project: Refactoring-Bot   Source File: RemoveMethodParameter.java    License: MIT License 5 votes vote down vote up
/**
 * Removes the parameter from all relevant method declarations and method calls
 * in the given java files
 * 
 * @param javaFilesRelevantForRefactoring
 * @param issueFilePath
 * @param targetMethod
 * @param parameterName
 * @throws FileNotFoundException
 */
private void removeParameterFromRelatedMethodDeclarationsAndMethodCalls(
		HashSet<String> javaFilesRelevantForRefactoring, MethodDeclaration targetMethod, String parameterName)
		throws FileNotFoundException {
	Integer parameterIndex = getMethodParameterIndex(targetMethod, parameterName);

	for (String currentFilePath : javaFilesRelevantForRefactoring) {
		FileInputStream is = new FileInputStream(currentFilePath);
		CompilationUnit cu = LexicalPreservingPrinter.setup(StaticJavaParser.parse(is));

		List<MethodDeclaration> methodDeclarationsInCurrentFile = cu.findAll(MethodDeclaration.class);
		List<MethodCallExpr> methodCallsInCurrentFile = cu.findAll(MethodCallExpr.class);

		// remove argument from all target method calls
		for (MethodCallExpr fileMethodCall : methodCallsInCurrentFile) {
			if (isTargetMethodCall(fileMethodCall)) {
				removeMethodCallArgument(fileMethodCall, parameterIndex);
			}
		}

		// remove parameter from all relevant method declarations
		for (MethodDeclaration fileMethod : methodDeclarationsInCurrentFile) {
			if (allRefactoringRelevantMethodDeclarations.contains(fileMethod)) {
				removeMethodParameter(fileMethod, parameterName);
				removeParameterFromJavadoc(fileMethod, parameterName);
			}
		}

		PrintWriter out = new PrintWriter(currentFilePath);
		out.println(LexicalPreservingPrinter.print(cu));
		out.close();
	}
}
 
Example 25
Source Project: Refactoring-Bot   Source File: RemoveMethodParameter.java    License: MIT License 5 votes vote down vote up
private void configureJavaParserForProject(BotIssue issue) {
	CombinedTypeSolver typeSolver = new CombinedTypeSolver();
	for (String javaRoot : issue.getJavaRoots()) {
		typeSolver.add(new JavaParserTypeSolver(javaRoot));
	}
	typeSolver.add(new ReflectionTypeSolver());
	JavaSymbolSolver javaSymbolSolver = new JavaSymbolSolver(typeSolver);
	StaticJavaParser.getConfiguration().setSymbolResolver(javaSymbolSolver);
}
 
Example 26
Source Project: Refactoring-Bot   Source File: RenameMethod.java    License: MIT License 5 votes vote down vote up
/**
 * Rename all relevant method declarations and method calls in the given java
 * files
 * 
 * @param javaFilesRelevantForRefactoring
 * @param newMethodName
 * @throws FileNotFoundException
 */
private void renameRelatedMethodDeclarationsAndMethodCalls(HashSet<String> javaFilesRelevantForRefactoring,
		String newMethodName) throws FileNotFoundException {
	for (String currentFilePath : javaFilesRelevantForRefactoring) {
		FileInputStream is = new FileInputStream(currentFilePath);
		CompilationUnit cu = LexicalPreservingPrinter.setup(StaticJavaParser.parse(is));

		List<MethodDeclaration> methodDeclarationsInCurrentFile = cu.findAll(MethodDeclaration.class);
		List<MethodCallExpr> methodCallsInCurrentFile = cu.findAll(MethodCallExpr.class);

		// rename all target method calls
		for (MethodCallExpr fileMethodCall : methodCallsInCurrentFile) {
			if (isTargetMethodCall(fileMethodCall)) {
				renameMethodCall(fileMethodCall, newMethodName);
			}
		}

		// rename all relevant method declarations
		for (MethodDeclaration fileMethod : methodDeclarationsInCurrentFile) {
			if (allRefactoringRelevantMethodDeclarations.contains(fileMethod)) {
				renameMethod(fileMethod, newMethodName);
			}
		}

		PrintWriter out = new PrintWriter(currentFilePath);
		out.println(LexicalPreservingPrinter.print(cu));
		out.close();
	}
}
 
Example 27
Source Project: Refactoring-Bot   Source File: RenameMethod.java    License: MIT License 5 votes vote down vote up
private void configureJavaParserForProject(BotIssue issue) {
	CombinedTypeSolver typeSolver = new CombinedTypeSolver();
	for (String javaRoot : issue.getJavaRoots()) {
		typeSolver.add(new JavaParserTypeSolver(javaRoot));
	}
	typeSolver.add(new ReflectionTypeSolver());
	JavaSymbolSolver javaSymbolSolver = new JavaSymbolSolver(typeSolver);
	StaticJavaParser.getConfiguration().setSymbolResolver(javaSymbolSolver);
}
 
Example 28
Source Project: Refactoring-Bot   Source File: ReorderModifier.java    License: MIT License 5 votes vote down vote up
/**
 * Reorder modifiers of a given field or method to comply with the JLS
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	String filepath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	FileInputStream in = new FileInputStream(filepath);
	CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in));

	FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(issue.getLine(), compilationUnit);
	MethodDeclaration method = RefactoringHelper.getMethodDeclarationByLineNumber(issue.getLine(),
			compilationUnit);
	boolean isModifierListUnchanged = false;
	NodeList<Modifier> modifiersInCorrectOrder;
	if (field != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(field.getModifiers());
		isModifierListUnchanged = field.getModifiers().equals(modifiersInCorrectOrder);
		field.setModifiers(new NodeList<Modifier>());
		field.setModifiers(modifiersInCorrectOrder);
	} else if (method != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(method.getModifiers());
		isModifierListUnchanged = method.getModifiers().equals(modifiersInCorrectOrder);
		method.setModifiers(new NodeList<Modifier>());
		method.setModifiers(modifiersInCorrectOrder);
	} else {
		throw new BotRefactoringException("Could not find method or field declaration at the given line!");
	}

	if (isModifierListUnchanged) {
		throw new BotRefactoringException("All modifiers are in correct order! Nothing to refactor.");
	}

	// Save changes to file
	PrintWriter out = new PrintWriter(filepath);
	out.println(LexicalPreservingPrinter.print(compilationUnit));
	out.close();

	// Return commit message
	return "Reordered modifiers to comply with the Java Language Specification";
}
 
Example 29
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 5 votes vote down vote up
/**
 * @param filePath
 * @return all <code>ClassOrInterfaceDeclaration</code> in the given file
 * @throws FileNotFoundException
 */
public static List<ClassOrInterfaceDeclaration> getAllClassesAndInterfacesFromFile(String filePath)
		throws FileNotFoundException {
	FileInputStream is = new FileInputStream(filePath);
	CompilationUnit cu = LexicalPreservingPrinter.setup(StaticJavaParser.parse(is));
	return cu.findAll(ClassOrInterfaceDeclaration.class);
}
 
Example 30
Source Project: Refactoring-Bot   Source File: ReorderModifiersTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testReorderMethodModifiers() throws Exception {
	// arrange
	int lineOfMethod = TestDataClassReorderModifiers.getLineOfMethodWithStaticAndFinalInWrongOrder();

	// act
	File tempFile = performReorderModifiers(lineOfMethod);

	// assert
	FileInputStream in = new FileInputStream(tempFile);
	CompilationUnit cu = StaticJavaParser.parse(in);
	MethodDeclaration methodDeclarationAfterRefactoring = RefactoringHelper
			.getMethodDeclarationByLineNumber(lineOfMethod, cu);
	assertAllModifiersInCorrectOrder(methodDeclarationAfterRefactoring.getModifiers());
}