com.github.javaparser.ast.CompilationUnit Java Examples

The following examples show how to use com.github.javaparser.ast.CompilationUnit. 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: 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 #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 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 #3
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 #4
Source File: JavaEnumBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicEnum() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(eq(PACKAGE), eq(NAME), capture(compilationUnitCapture));

  javaEnumBuilder.setJavaDoc("");

  replayAll();

  javaEnumBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n"
          + "\n"
          + "import com.fasterxml.jackson.annotation.JsonProperty;\n"
          + "\n"
          + "public enum EnumName {\n"
          + "}\n",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #5
Source File: SourceProjectImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCompilationUnit() {
  CompilationUnit compilationUnit1 = new CompilationUnit();

  expect(path.resolve("com/github/kklisura"))
      .andReturn(Paths.get("source-project/main/com/github/kklisura"));

  expect(sourceRoot.getRoot()).andReturn(path);

  expect(sourceRoot.add(compilationUnit1)).andReturn(sourceRoot);

  replayAll();

  sourceProject.addCompilationUnit("com.github.kklisura", "name", compilationUnit1);

  verifyAll();

  assertTrue(
      compilationUnit1
          .getStorage()
          .get()
          .getPath()
          .endsWith("source-project/main/com/github/kklisura/name.java"));
}
 
Example #6
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpVerbs() throws IOException, ParseException {
    File file = new File("src/test/java/controller/SimpleController.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    ControllerModel model = new ControllerModel();
    visitor.visit(declaration, model);

    final Collection<ControllerRouteModel> routes = (Collection<ControllerRouteModel>) model.getRoutes().get("/simple");
    assertThat(routes).isNotNull();
    assertThat(routes).hasSize(6);

    for (ControllerRouteModel route : routes) {
        assertThat(route.getHttpMethod().name()).isEqualToIgnoringCase(route.getMethodName());
        assertThat(route.getParams()).isEmpty();
        assertThat(route.getPath()).isEqualToIgnoringCase("/simple");
    }
}
 
Example #7
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 #8
Source File: SourceProjectImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCompilationUnitAddingDuplicateCompilationUnit() {
  CompilationUnit compilationUnit1 = new CompilationUnit();

  expect(path.resolve("com/github/kklisura"))
      .andReturn(Paths.get("source-project/main/com/github/kklisura"))
      .times(2);

  expect(sourceRoot.getRoot()).andReturn(path).times(2);

  expect(sourceRoot.add(compilationUnit1)).andReturn(sourceRoot).times(2);

  replayAll();

  sourceProject.addCompilationUnit("com.github.kklisura", "name", compilationUnit1);
  sourceProject.addCompilationUnit("com.github.kklisura", "name", compilationUnit1);

  verifyAll();

  assertTrue(
      compilationUnit1
          .getStorage()
          .get()
          .getPath()
          .endsWith("source-project/main/com/github/kklisura/name.java"));
}
 
Example #9
Source File: StaticScanner.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
public void addStepsFromFileContents(String file, String contents) {
    StringReader reader = new StringReader(contents);
    ParseResult<CompilationUnit> result = new JavaParser().parse(reader);
    boolean shouldScan = result.getResult().map(this::shouldScan).orElse(false);
    if (!shouldScan) {
        return;
    }
    RegistryMethodVisitor methodVisitor = new RegistryMethodVisitor(stepRegistry, file);
    methodVisitor.visit(result.getResult().get(), null);
}
 
Example #10
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public CompilationUnit injectableClass() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream(RESOURCE)).setPackageDeclaration(packageName);                        
    ClassOrInterfaceDeclaration cls = compilationUnit
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    
    cls.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("processes")).forEach(fd -> {
        annotator.withInjection(fd);
        fd.getVariable(0).setType(new ClassOrInterfaceType(null, new SimpleName(annotator.multiInstanceInjectionType()), 
                                                           NodeList.nodeList(new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName())))))));
    });
    
    annotator.withApplicationComponent(cls);
    
    return compilationUnit;
}
 
Example #11
Source File: MarshallerGeneratorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(Person.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(1);
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(1);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("PersonMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #12
Source File: JavaInterfaceBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetJavadoc() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture));

  interfaceBuilder.setJavaDoc("Java doc.");

  replayAll();

  interfaceBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n"
          + "\n"
          + "/**\n"
          + " * Java doc.\n"
          + " */\n"
          + "public interface InterfaceTest {\n"
          + "}\n",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #13
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
private void parseClass(ClassOrInterfaceDeclaration classDeclaration,
        CompilationUnit compilationUnit) {
    Optional<AnnotationExpr> endpointAnnotation = classDeclaration
            .getAnnotationByClass(Endpoint.class);
    compilationUnit.getStorage().ifPresent(storage -> {
        String className = classDeclaration.getFullyQualifiedName()
                .orElse(classDeclaration.getNameAsString());
        qualifiedNameToPath.put(className, storage.getPath().toString());
    });
    if (!endpointAnnotation.isPresent()) {
        nonEndpointMap.put(classDeclaration.resolve().getQualifiedName(),
                classDeclaration);
    } else {
        Optional<Javadoc> javadoc = classDeclaration.getJavadoc();
        if (javadoc.isPresent()) {
            endpointsJavadoc.put(classDeclaration,
                    javadoc.get().getDescription().toText());
        } else {
            endpointsJavadoc.put(classDeclaration, "");
        }
        pathItems.putAll(createPathItems(
                getEndpointName(classDeclaration, endpointAnnotation.get()),
                classDeclaration));
    }
}
 
Example #14
Source File: JavaClassBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetJavadoc() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture));

  javaClassBuilder.setJavaDoc("Java doc.");

  replayAll();

  javaClassBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n"
          + "\n"
          + "/**\n"
          + " * Java doc.\n"
          + " */\n"
          + "public class ClassName {\n"
          + "}\n",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #15
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotNullContraints() throws IOException, ParseException{
    File file = new File("src/test/java/controller/ControllerWithConstraints.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    ControllerModel model = new ControllerModel();
    visitor.visit(declaration, model);

    ControllerRouteModel route = getModelByPath(model,"/superman");
    assertThat(route).isNotNull();
    assertThat(route.getParams()).hasSize(1);
    RouteParamModel param = (RouteParamModel) Iterables.get(route.getParams(), 0);

    //Annotated with NotNull constraints
    assertThat(param.getName()).isEqualTo("clark");
    assertThat(param.isMandatory()).isTrue();

    route = getModelByPath(model,"/batman");
    assertThat(route).isNotNull();
    assertThat(route.getParams()).hasSize(1);
    param = (RouteParamModel) Iterables.get(route.getParams(), 0);

    //Annotated with NotNull constraints that contains a message
    assertThat(param.getName()).isEqualTo("bruce");
    assertThat(param.isMandatory()).isTrue();
}
 
Example #16
Source File: JavaClassBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddingImports() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(PACKAGE_NAME), eq(CLASS_NAME), capture(compilationUnitCapture));

  replayAll();

  javaClassBuilder.addImport("java.util", "List");
  javaClassBuilder.addImport("java.util", "List");
  javaClassBuilder.addImport("java.util", "List");

  javaClassBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n\n"
          + "import java.util.List;\n"
          + "\n"
          + "public class ClassName {\n"
          + "}\n"
          + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #17
Source File: ApplicationGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private List<GeneratedFile> generateApplicationSections() {
    ArrayList<GeneratedFile> generatedFiles = new ArrayList<>();

    for (Generator generator : generators) {
        ApplicationSection section = generator.section();
        if (section == null) {
            continue;
        }
        CompilationUnit sectionUnit = new CompilationUnit();
        sectionUnit.setPackageDeclaration( this.packageName );
        sectionUnit.addType( section.classDeclaration() );
        generatedFiles.add(
                new GeneratedFile(GeneratedFile.Type.APPLICATION_SECTION,
                                  getFilePath(section.sectionClassName()),
                                  sectionUnit.toString()));
    }
    return generatedFiles;
}
 
Example #18
Source File: FinalRClassBuilder.java    From Briefness with Apache License 2.0 6 votes vote down vote up
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception {
  CompilationUnit compilationUnit = JavaParser.parse(rFile);
  TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

  TypeSpec.Builder result = TypeSpec.classBuilder(className)
      .addModifiers(PUBLIC, FINAL);

  for (Node node : resourceClass.getChildNodes()) {
    if (node instanceof ClassOrInterfaceDeclaration) {
      addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes);
    }
  }

  JavaFile finalR = JavaFile.builder(packageName, result.build())
      .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
      .build();

  finalR.writeTo(outputDir);
}
 
Example #19
Source File: DirClassTypeResolverTest.java    From turin-programming-language with Apache License 2.0 6 votes vote down vote up
@Test
public void formalParametersOfLoadedFunctionHaveCorrectType() throws IOException {
    SymbolResolver symbolResolver = new ComposedSymbolResolver(ImmutableList.of());
    DirClassesTypeResolver dirClassesTypeResolver = new DirClassesTypeResolver(tmpDir);
    List<? extends FormalParameter> paramsTypeFatalError = dirClassesTypeResolver.resolveAbsoluteFunctionName("me.tomassetti.javaformatter.fatalError").get().getParameters();
    List<? extends FormalParameter> paramsTypeFormat = dirClassesTypeResolver.resolveAbsoluteFunctionName("me.tomassetti.javaformatter.format").get().getParameters();
    List<? extends FormalParameter> paramsTypeParse = dirClassesTypeResolver.resolveAbsoluteFunctionName("me.tomassetti.javaformatter.parse").get().getParameters();

    assertEquals(1, paramsTypeFatalError.size());
    assertEquals(1, paramsTypeFormat.size());
    assertEquals(1, paramsTypeParse.size());

    assertEquals(true, paramsTypeFatalError.get(0).getType().isReferenceTypeUsage());
    assertEquals(String.class.getCanonicalName(), paramsTypeFatalError.get(0).getType().asReferenceTypeUsage().getQualifiedName());
    assertEquals(true, paramsTypeFormat.get(0).getType().isReferenceTypeUsage());
    assertEquals(CompilationUnit.class.getCanonicalName(), paramsTypeFormat.get(0).getType().asReferenceTypeUsage().getQualifiedName());
    assertEquals(true, paramsTypeParse.get(0).getType().isReferenceTypeUsage());
    assertEquals(String.class.getCanonicalName(), paramsTypeParse.get(0).getType().asReferenceTypeUsage().getQualifiedName());
}
 
Example #20
Source File: MyShellCallback.java    From mapper-generator-javafx with Apache License 2.0 6 votes vote down vote up
private String getNewJavaFile(String newFileSource, String existingFileFullPath) throws FileNotFoundException {
    JavaParser javaParser = new JavaParser();
    ParseResult<CompilationUnit> newCompilationUnitParse = javaParser.parse(newFileSource);
    CompilationUnit newCompilationUnit;
    if (newCompilationUnitParse.isSuccessful() && newCompilationUnitParse.getResult().isPresent()) {
        newCompilationUnit = newCompilationUnitParse.getResult().get();
    } else {
        log.error("解析 newFileSource 失败, {}", newCompilationUnitParse.getProblem(0).toString());
        return newFileSource;
    }

    ParseResult<CompilationUnit> existingCompilationUnitParse = javaParser.parse(new File(existingFileFullPath));
    CompilationUnit existingCompilationUnit;
    if (existingCompilationUnitParse.isSuccessful() && existingCompilationUnitParse.getResult().isPresent()) {
        existingCompilationUnit = existingCompilationUnitParse.getResult().get();
    } else {
        log.error("解析 existingFileFullPath 失败, {}", existingCompilationUnitParse.getProblem(0).toString());
        return newFileSource;
    }
    return mergerFile(newCompilationUnit, existingCompilationUnit);
}
 
Example #21
Source File: JavaInterfaceBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddingImportsOnSamePackage() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture));

  replayAll();

  interfaceBuilder.addImport(BASE_PACKAGE_NAME, "Test");
  interfaceBuilder.addImport("java.util", "List");
  interfaceBuilder.addImport("java.util", "List");
  interfaceBuilder.addImport("java.util", "List");

  interfaceBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n\n"
          + "import java.util.List;\n"
          + "\n"
          + "public interface InterfaceTest {\n"
          + "}\n"
          + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #22
Source File: SeeTagConverter.java    From xDoc with MIT License 5 votes vote down vote up
@Override
public DocTag converter(String comment) {
    DocTag docTag = super.converter(comment);

    String path = JavaSourceFileManager.getInstance().getPath((String) docTag.getValues());
    if (StringUtils.isBlank(path)) {
        return null;
    }

    Class<?> returnClassz;
    CompilationUnit cu;
    try (FileInputStream in = new FileInputStream(path)) {
        Optional<CompilationUnit> optional = javaParser.parse(in).getResult();
        if (!optional.isPresent()) {
            return null;
        }
        cu = optional.get();
        if (cu.getTypes().size() <= 0) {
            return null;
        }
        returnClassz = Class.forName(cu.getPackageDeclaration().get().getNameAsString() + "." + cu.getTypes().get(0).getNameAsString());

    } catch (Exception e) {
        log.warn("读取java原文件失败:{}", path, e.getMessage());
        return null;
    }

    String text = cu.getComment().isPresent() ? CommentUtils.parseCommentText(cu.getComment().get().getContent()) : "";

    Map<String, String> commentMap = JavaFileUtils.analysisFieldComments(returnClassz);
    List<FieldInfo> fields = JavaFileUtils.analysisFields(returnClassz, commentMap);

    ObjectInfo objectInfo = new ObjectInfo();
    objectInfo.setType(returnClassz);
    objectInfo.setFieldInfos(fields);
    objectInfo.setComment(text);
    return new SeeTagImpl(docTag.getTagName(), objectInfo);
}
 
Example #23
Source File: JavaInterfaceBuilderImplTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicInterfaceWithAnnotation() throws IOException {
  Capture<CompilationUnit> compilationUnitCapture = Capture.newInstance();

  sourceProject.addCompilationUnit(
      eq(BASE_PACKAGE_NAME), eq(NAME), capture(compilationUnitCapture));

  interfaceBuilder.addAnnotation("Annotation");
  interfaceBuilder.addAnnotation("Annotation");
  interfaceBuilder.addAnnotation("Deprecated");
  interfaceBuilder.addAnnotation("Deprecated");

  replayAll();

  interfaceBuilder.build(sourceProject);

  assertEquals(
      "package com.github.kklisura;\n"
          + "\n"
          + "import com.github.kklisura.annotations.Annotation;\n"
          + "\n"
          + "@Annotation\n"
          + "@Deprecated\n"
          + "public interface InterfaceTest {\n"
          + "}\n"
          + "",
      compilationUnitCapture.getValue().toString());

  verifyAll();
}
 
Example #24
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassImplementingController() throws IOException, ParseException {
    File file = new File("src/test/java/sample/MyController.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    final Boolean isController = visitor.visit(declaration, null);
    assertThat(isController).isTrue();
}
 
Example #25
Source File: MysteryGuest.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Analyze the test file for test methods that use external resources
 */
@Override
public void runAnalysis(CompilationUnit testFileCompilationUnit, CompilationUnit productionFileCompilationUnit, String testFileName, String productionFileName) throws FileNotFoundException {
    MysteryGuest.ClassVisitor classVisitor;
    classVisitor = new MysteryGuest.ClassVisitor();
    classVisitor.visit(testFileCompilationUnit, null);
}
 
Example #26
Source File: Sources.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public CompilationUnit apply(String resource) {
    InputStream is = null;
    try {
        is = getClass().getClassLoader().getResourceAsStream(resource);
        return JavaParser.parse(is);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to load resource: [" + resource + "] from classpath.");
    } finally {
        IOUtils.closeQuietly(is);
    }
}
 
Example #27
Source File: ReorderModifiersTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
@Test
public void testReorderFieldModifiers() throws Exception {
	// arrange
	int lineNumber = TestDataClassReorderModifiers.lineNumberOfFieldWithStaticAndFinalInWrongOrder;

	// act
	File tempFile = performReorderModifiers(lineNumber);

	// assert
	FileInputStream in = new FileInputStream(tempFile);
	CompilationUnit cu = StaticJavaParser.parse(in);
	FieldDeclaration fieldDeclarationAfterRefactoring = RefactoringHelper
			.getFieldDeclarationByLineNumber(lineNumber, cu);
	assertAllModifiersInCorrectOrder(fieldDeclarationAfterRefactoring.getModifiers());
}
 
Example #28
Source File: JavaParserTest.java    From molicode with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    CompilationUnit compilationUnit = new CompilationUnit();
    ClassOrInterfaceDeclaration myClass = compilationUnit
            .addClass("MyClass")
            .setPublic(true);
    myClass.addField(int.class, "A_CONSTANT", PUBLIC, STATIC);
    myClass.addField(String.class, "name", PRIVATE);
    Comment comment= new JavadocComment();
    comment.setContent("你大爷!");
    myClass.addMethod("helloWorld", PUBLIC).setParameters(NodeList.nodeList()).setComment(comment);
    String code = myClass.toString();
    System.out.println(code);
}
 
Example #29
Source File: RelationCalculator.java    From jql with MIT License 5 votes vote down vote up
public void calculateRelations(Collection<File> files) {
    System.out.println();
    int totalFiles = files.size();
    int fileIndex = 1;
    for (File file : files) {
        try {
            CompilationUnit cu = parse(file);
            NodeList<TypeDeclaration<?>> types = cu.getTypes();
            for (TypeDeclaration<?> type : types) {
                boolean isInterface = type instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) type).isInterface();
                boolean isAnnotation = type instanceof AnnotationDeclaration;
                boolean isEnumeration = type instanceof EnumDeclaration;
                boolean isClass = !isAnnotation && !isEnumeration && !isInterface;
                if (isInterface) {
                    // check if this interface extends another interface and persist relation in EXTENDS table
                    ClassOrInterfaceDeclaration interfaceDeclaration = (ClassOrInterfaceDeclaration) type;
                    extendsRelationCalculator.calculate(interfaceDeclaration, cu);
                }
                if (isClass) {
                    ClassOrInterfaceDeclaration classDeclaration = (ClassOrInterfaceDeclaration) type;
                    // check if this class implements an interface and persist relation in IMPLEMENTS table
                    implementsRelationCalculator.calculate(classDeclaration, cu);
                    // check if this class extends another class and persist relation in EXTENDS table
                    extendsRelationCalculator.calculate(classDeclaration, cu);
                }
                if (isClass || isInterface) {
                    annotatedWithCalculator.calculate((ClassOrInterfaceDeclaration) type, cu);
                }
            }
        } catch (ParseProblemException | IOException e) {
            System.err.println("Error while parsing " + file.getAbsolutePath());
        }
        System.out.print("\rCalculating relations: " + getPercent(fileIndex, totalFiles) + "% " + ("(" + fileIndex + "/" + totalFiles + ")"));
        fileIndex++;
    }
    System.out.println();
}
 
Example #30
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnInterfaceClass() throws IOException, ParseException {
    File file = new File("src/test/java/sample/MyInterface.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    final Boolean isController = visitor.visit(declaration, null);
    assertThat(isController).isFalse();
}