com.github.javaparser.StaticJavaParser Java Examples

The following examples show how to use com.github.javaparser.StaticJavaParser. 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: RefactoringHelperTest.java    From Refactoring-Bot with 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 #2
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 #3
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #4
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #5
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #6
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #7
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 #8
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #9
Source File: RenameMethodTest.java    From Refactoring-Bot with 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 #10
Source File: AddOverrideAnnotation.java    From Refactoring-Bot with 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 #11
Source File: RefactoringHelperTest.java    From Refactoring-Bot with 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 #12
Source File: RefactoringHelperTest.java    From Refactoring-Bot with 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 #13
Source File: RefactoringHelperTest.java    From Refactoring-Bot with 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 #14
Source File: PackageInfoReader.java    From jig with 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 #15
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 #16
Source File: JavaDocParser.java    From quarkus with 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 File: JavaDocParser.java    From quarkus with 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 File: RefactoringHelperTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
@Test
public void testGetFieldDeclarationByLineNumber() throws FileNotFoundException {
	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	int lineNumber = TestDataClassRefactoringHelper.lineNumberOfFieldDeclaration;
	String expectedFieldAsString = "public static int lineNumberOfFieldDeclaration = " + lineNumber + ";";

	// act
	FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(lineNumber, cu);

	// assert
	assertThat(field).isNotNull();
	assertThat(field.toString()).isEqualTo(expectedFieldAsString);
}
 
Example #19
Source File: RuleUnitPojoGenerator.java    From kogito-runtimes with 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 #20
Source File: RenameMethodTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * Two classes sharing the same interface should only lead to a refactoring in
 * both classes, if the common interface declares the target method signature.
 * This is not given in this test case
 * 
 * @throws Exception
 */
@Test
public void testTwoClassesWithSameMethodSigAndEmptyInterface() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClassImplementingEmptyInterface);
	filesToConsider.add(fileOfEmptyInterface);
	int lineNumberOfMethodToBeRenamed = renameMethodTestClassWithEmptyInterfaceImpl.getLineOfMethodToBeRenamed();
	String newMethodName = "newMethodName";

	CompilationUnit cuOriginalFileOfTestClassImplementingEmptyInterface = StaticJavaParser
			.parse(fileOfTestClassImplementingEmptyInterface);
	MethodDeclaration originalMethodInInnerClass = RefactoringHelper.getMethodDeclarationByLineNumber(
			renameMethodTestClassWithEmptyInterfaceImpl.getLineOfMethodToBeRenamed(),
			cuOriginalFileOfTestClassImplementingEmptyInterface);

	assertThat(originalMethodInInnerClass).isNotNull();

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

	// assert
	CompilationUnit cuRefactoredFileOfTestClassImplementingEmptyInterface = StaticJavaParser
			.parse(fileOfTestClassImplementingEmptyInterface);

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

	// assert that inner class method remained unchanged
	int lineNumberOfInnerClassMethod = renameMethodInnerClassWithEmptyInterfaceImpl.getLineOfMethodToBeRenamed();
	assertThatMethodNameIsEqualToExpected(cuRefactoredFileOfTestClassImplementingEmptyInterface,
			lineNumberOfInnerClassMethod, originalMethodInInnerClass.getNameAsString());
}
 
Example #21
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 #22
Source File: RefactoringHelperTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
@Test
public void testFindRelatedClassesAndInterfaces() throws BotRefactoringException, IOException {
	configureStaticJavaParserForResolving();

	// arrange
	FileInputStream in = new FileInputStream(getTestResourcesFile());
	CompilationUnit cu = StaticJavaParser.parse(in);
	Optional<ClassOrInterfaceDeclaration> targetClass = cu.getClassByName(TARGET_CLASS_NAME);
	assertThat(targetClass).isPresent();

	int lineNumber = TestDataClassRefactoringHelper.getLineOfMethod(true);
	MethodDeclaration targetMethod = RefactoringHelper.getMethodDeclarationByLineNumber(lineNumber, cu);
	assertThat(targetMethod).isNotNull();

	List<String> allJavaFiles = new ArrayList<>();
	allJavaFiles.add(getTestResourcesFile().getCanonicalPath());

	// act
	Set<String> relatedClassesAndInterfaces = RefactoringHelper.findRelatedClassesAndInterfaces(allJavaFiles,
			targetClass.get(), targetMethod);

	// assert
	// this method is already being tested indirectly in some of the refactoring
	// tests (e.g. for removing a method parameter) with a larger set of classes.
	// That's why we keep it simple here.
	assertThat(relatedClassesAndInterfaces).hasSize(2);
}
 
Example #23
Source File: RefactoringHelperTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
private void configureStaticJavaParserForResolving() {
	CombinedTypeSolver typeSolver = new CombinedTypeSolver();
	String javaRoot = TestUtils.getAbsolutePathOfTestsFolder();
	typeSolver.add(new JavaParserTypeSolver(javaRoot));
	typeSolver.add(new ReflectionTypeSolver());
	JavaSymbolSolver javaSymbolSolver = new JavaSymbolSolver(typeSolver);
	StaticJavaParser.getConfiguration().setSymbolResolver(javaSymbolSolver);
}
 
Example #24
Source File: ExtendsTest.java    From butterfly with MIT License 5 votes vote down vote up
@Test
public void negateTest() throws ParseException {
    String resourceName = "/test-app/src/main/java/com/testapp/JavaLangSubclass.java";
    InputStream resourceAsStream = this.getClass().getResourceAsStream(resourceName);
    CompilationUnit compilationUnit = StaticJavaParser.parse(resourceAsStream);
    Extends extendsObj = new Extends(Throwable.class).setNegate(true);
    Assert.assertFalse(extendsObj.evaluate(compilationUnit));
}
 
Example #25
Source File: RemoveMethodParameterTest.java    From Refactoring-Bot with MIT License 5 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 testRefactoringOfMethodPlacedAfterInnerClass() throws Exception {
	// arrange
	List<File> filesToConsider = new ArrayList<File>();
	filesToConsider.add(fileOfTestClass);
	int lineNumberOfMethodWithParameterToBeRemoved = removeParameterTestClass
			.getLineOfMethodPlacedInAndAfterInnerClass(0, 0, 0);
	String parameterName = "b";

	CompilationUnit cuOriginalFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	MethodDeclaration originalMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			lineNumberOfMethodWithParameterToBeRemoved, cuOriginalFileOfTestClass);
	assertThat(originalMethod).isNotNull();

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

	// assert that method in outer class (the method for which the actual renaming
	// was intended) has been refactored
	CompilationUnit cuRefactoredFileOfTestClass = StaticJavaParser.parse(fileOfTestClass);
	MethodDeclaration refactoredMethod = RefactoringHelper.getMethodDeclarationByLineNumber(
			lineNumberOfMethodWithParameterToBeRemoved, cuRefactoredFileOfTestClass);
	assertThat(refactoredMethod).isNotNull();
	assertThat(refactoredMethod.getParameterByName(parameterName).isPresent()).isFalse();
}
 
Example #26
Source File: GroovyDocParser.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Map<String, GroovyClassDoc> parseJava(String packagePath, String file, String src) throws RuntimeException {
    GroovydocJavaVisitor visitor = new GroovydocJavaVisitor(packagePath, links);
    try {
        visitor.visit(StaticJavaParser.parse(src), null);
    } catch(Throwable t) {
        System.err.println("Attempting to ignore error parsing Java source file: " + packagePath + "/" + file);
        System.err.println("Consider reporting the error to the Groovy project: https://issues.apache.org/jira/browse/GROOVY");
        System.err.println("... or directly to the JavaParser project: https://github.com/javaparser/javaparser/issues");
        System.err.println("Error: " + t.getMessage());
    }
    return visitor.getGroovyClassDocs();
}
 
Example #27
Source File: ReorderModifiersTest.java    From Refactoring-Bot with 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());
}
 
Example #28
Source File: TestUtils.java    From openapi-generator with 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 #29
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 #30
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);
}