Java Code Examples for com.github.javaparser.ast.CompilationUnit#findAll()

The following examples show how to use com.github.javaparser.ast.CompilationUnit#findAll() . 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: RemoveMethodParameterTest.java    From Refactoring-Bot with 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 2
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 3
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 4
Source File: RemoveMethodParameter.java    From Refactoring-Bot with 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 5
Source File: RenameMethod.java    From Refactoring-Bot with 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 6
Source File: RefactoringHelper.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * Finds a method declaration in a compilation unit that starts at the specified
 * line number
 * 
 * @param lineNumber
 * @param cu
 * @return MethodDeclaration or null if none found
 */
public static MethodDeclaration getMethodDeclarationByLineNumber(int lineNumber, CompilationUnit cu) {
	MethodDeclaration result = null;
	List<MethodDeclaration> methods = cu.findAll(MethodDeclaration.class);
	for (MethodDeclaration method : methods) {
		if (isMethodDeclarationAtLine(method, lineNumber)) {
			result = method;
		}
	}
	return result;
}
 
Example 7
Source File: RefactoringHelper.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * Finds a field declaration in a compilation unit that starts at the specified
 * line number
 * 
 * @param lineNumber
 * @param cu
 * @return FieldDeclaration or null if none found
 */
public static FieldDeclaration getFieldDeclarationByLineNumber(int lineNumber, CompilationUnit cu) {
	FieldDeclaration result = null;
	List<FieldDeclaration> fields = cu.findAll(FieldDeclaration.class);
	for (FieldDeclaration field : fields) {
		if (isFieldDeclarationAtLine(field, lineNumber)) {
			result = field;
		}
	}
	return result;
}
 
Example 8
Source File: RefactoringHelper.java    From Refactoring-Bot with 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 9
Source File: RenameMethodTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * Test that a refactoring of an inner class (implementing the same interface as
 * the outer class) results in a correct refactoring of both, the inner and the
 * outer class. Also test whether the implemented interface and super class of
 * the outer class was successfully refactored
 * 
 * @throws Exception
 */
@Test
public void testInnerClassWithInterfaceRefactoring() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfInterface);
	filesToConsider.add(fileOfSuperClass);
	int lineNumberOfMethodToBeRenamed = renameMethodInnerClassWithInterfaceImpl.getLineOfInterfaceMethod();
	String newMethodName = "newMethodName";

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

	// assert
	CompilationUnit cuRefactoredFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);

	// assert that method in inner class has been refactored
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfTestClass, lineNumberOfMethodToBeRenamed,
			newMethodName);

	// assert that method in outer class has been refactored
	int lineNumberOfMethodInOuterClass = renameMethodTestClass.getLineOfInterfaceMethod();
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfTestClass, lineNumberOfMethodInOuterClass,
			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);

	// assert that super class of outer class has been refactored
	CompilationUnit cuRefactoredFileOfSuperClass = StaticJavaParser.parse(fileOfSuperClass);
	int lineNumberOfMethodInSuperClass = renameMethodSuperClass.getLineOfInterfaceMethod();
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfSuperClass, lineNumberOfMethodInSuperClass,
			newMethodName);
}
 
Example 10
Source File: ParseUtil.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
public static List<String> parseFileContent(String code) {
	try {
		CompilationUnit cu = JavaParser.parse(code);
		List<MethodDeclaration> methods = cu.findAll(MethodDeclaration.class);
		count += methods.size();
		return methods.stream()
			.map(MethodDeclaration::toString)
			.collect(Collectors.toList());
	} catch (ParseProblemException e) {
	    logger.warn("Could not parse code: ");
	    logger.warn(code);
		return new ArrayList<>();
	}
}
 
Example 11
Source File: RemoveMethodParameterTest.java    From Refactoring-Bot with MIT License 4 votes vote down vote up
/**
 * Test that a refactoring of an inner class (implementing the same interface as
 * the outer class) results in a correct refactoring of both, the inner and the
 * outer class. Also test whether the implemented interface and super class of
 * the outer class was successfully refactored
 * 
 * @throws Exception
 */
@Test
public void testInnerClassWithInterfaceRefactoring() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	filesToConsider.add(fileOfInterface);
	filesToConsider.add(fileOfSuperClass);
	int lineNumberOfMethodWithParameterToBeRemoved = removeParameterInnerClassWithInterfaceImpl
			.getLineOfMethodWithUnusedParameter(0, 0, 0);
	String parameterName = "b";

	CompilationUnit cuOriginalFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	CompilationUnit cuOriginalFileOfSuperClass = StaticJavaParser.parse(fileOfSuperClass);
	MethodDeclaration originalInnerClassMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			removeParameterInnerClassWithInterfaceImpl.getLineOfMethodWithUnusedParameter(0, 0, 0),
			cuOriginalFileOfTestClass);
	MethodDeclaration originalOuterClassMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			removeParameterTestClass.getLineOfMethodWithUnusedParameter(0, 0, 0), cuOriginalFileOfTestClass);
	MethodDeclaration originalMethodInSuperClass = RefactoringHelper.getMethodDeclarationByLineNumber(
			removeParameterSuperClass.getLineOfMethodWithUnusedParameter(0, 0, 0), cuOriginalFileOfSuperClass);

	SoftAssertions softAssertions = new SoftAssertions();
	softAssertions.assertThat(originalInnerClassMethod).isNotNull();
	softAssertions.assertThat(originalOuterClassMethod).isNotNull();
	softAssertions.assertThat(originalMethodInSuperClass).isNotNull();
	softAssertions.assertAll();

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

	// assert
	CompilationUnit cuRefactoredFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);

	// assert that method in inner class has been refactored
	MethodDeclaration refactoredInnerClassMethod = getMethodByName(TARGET_INNER_CLASS_WITH_INTERFACE_NAME,
			originalInnerClassMethod.getNameAsString(), cuRefactoredFileOfTestClass);
	assertThat(refactoredInnerClassMethod).isNotNull();
	assertThat(refactoredInnerClassMethod.getParameterByName(parameterName).isPresent()).isFalse();

	// assert that method in outer class has been refactored
	MethodDeclaration refactoredOuterClassMethod = getMethodByName(TARGET_CLASS_NAME,
			originalOuterClassMethod.getNameAsString(), cuRefactoredFileOfTestClass);
	assertThat(refactoredOuterClassMethod).isNotNull();
	assertThat(refactoredOuterClassMethod.getParameterByName(parameterName).isPresent()).isFalse();

	// 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();

	// assert that super class of outer class has been refactored
	CompilationUnit cuRefactoredFileOfSuperClass = StaticJavaParser.parse(fileOfSuperClass);
	String methodInSuperClassName = originalMethodInSuperClass.getNameAsString();
	MethodDeclaration methodInSuperClass = getMethodByName(SUPER_CLASS_NAME, methodInSuperClassName,
			cuRefactoredFileOfSuperClass);
	assertThat(methodInSuperClass).isNotNull();
	assertThat(methodInSuperClass.getParameterByName(parameterName).isPresent()).isFalse();
}
 
Example 12
Source File: RemoveMethodParameterTest.java    From Refactoring-Bot with MIT License 3 votes vote down vote up
/**
 * TEST HELPER METHOD ONLY. Does not work for classes with with more than one
 * method declaration with the same name.
 * 
 * Finds a method in a compilation unit inside the given class or interface and
 * with the given name.
 * 
 * Hint: this method is needed to find a method in a refacored compilation unit
 * for which we do not know the line number of the method (removing javadoc
 * comments changes the lines)
 * 
 * @param classOrInterfaceName
 * @param methodName
 * @param cu
 * @return MethodDeclaration or null if none found
 */
private MethodDeclaration getMethodByName(String classOrInterfaceName, String methodName, CompilationUnit cu) {
	for (ClassOrInterfaceDeclaration clazz : cu.findAll(ClassOrInterfaceDeclaration.class)) {
		if (clazz.getNameAsString().equals(classOrInterfaceName)) {
			List<MethodDeclaration> methods = clazz.findAll(MethodDeclaration.class);
			for (MethodDeclaration method : methods) {
				if (method.getNameAsString().equals(methodName)) {
					return method;
				}
			}
		}
	}

	return null;
}