Java Code Examples for com.github.javaparser.ast.CompilationUnit

The following examples show how to use com.github.javaparser.ast.CompilationUnit. 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: mapper-generator-javafx   Source File: MyShellCallback.java    License: 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 2
@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 3
Source Project: kogito-runtimes   Source File: ApplicationGenerator.java    License: 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 4
Source Project: wisdom   Source File: ControllerSourceVisitorTest.java    License: 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 5
@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 6
Source Project: gauge-java   Source File: StaticScanner.java    License: 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 7
Source Project: wisdom   Source File: ControllerSourceVisitorTest.java    License: 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 8
Source Project: kogito-runtimes   Source File: MarshallerGeneratorTest.java    License: 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 9
Source Project: flow   Source File: OpenApiObjectGenerator.java    License: 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 10
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 11
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 12
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 13
@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 14
@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 15
@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 16
@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 17
@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 18
@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 19
Source Project: Briefness   Source File: FinalRClassBuilder.java    License: 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 20
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 21
Source Project: wisdom   Source File: ClassSourceVisitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAnAnnotation() throws IOException, ParseException {
    File file = new File("src/test/java/sample/MyAnnotation.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    final Boolean isController = visitor.visit(declaration, null);
    assertThat(isController).isFalse();
}
 
Example 22
Source Project: molicode   Source File: JavaParserTest.java    License: 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 23
Source Project: wisdom   Source File: ClassSourceVisitorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClassAnnotatedWithController() throws IOException, ParseException {
    File file = new File("src/test/java/sample/MyAnnotatedController.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    final Boolean isController = visitor.visit(declaration, null);
    assertThat(isController).isTrue();
}
 
Example 24
Source Project: SnowGraph   Source File: ParseUtil.java    License: 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 25
Source Project: kogito-runtimes   Source File: ApplicationGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void generateSectionClass(ApplicationSection section, List<GeneratedFile> generatedFiles) {
    CompilationUnit cp = section.injectableClass();

    if (cp != null) {
        String packageName = cp.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
        String clazzName = packageName + "." + cp
                .findFirst(ClassOrInterfaceDeclaration.class)
                .map(c -> c.getName().toString())
                .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
        generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS,
                                             clazzName.replace('.', '/') + ".java",
                             log( cp.toString() ).getBytes(StandardCharsets.UTF_8)));
    }
}
 
Example 26
Source Project: kogito-runtimes   Source File: MessageProducerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType())));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
    });
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class).filter(fd -> fd.getVariable(0).getNameAsString().equals("emitter")).get();
        annotator.withInjection(emitterField);
        annotator.withOutgoingMessage(emitterField, trigger.getName());
        emitterField.getVariable(0).setType(annotator.emitterType("String"));
        
        MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methos in MessageProducerTemplate"));
        BlockStmt body = new BlockStmt();
        MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send");
        annotator.withMessageProducer(sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall").addArgument(new NameExpr("pi")).addArgument(new NameExpr(EVENT_DATA_VAR)));
        body.addStatement(sendMethodCall);
        produceMethod.setBody(body);

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
    } 
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 27
/**
 * Analyze the test file for test methods that have multiple assert statements with the same explanation message
 */
@Override
public void runAnalysis(CompilationUnit testFileCompilationUnit, CompilationUnit productionFileCompilationUnit, String testFileName, String productionFileName) throws FileNotFoundException {
    DuplicateAssert.ClassVisitor classVisitor;
    classVisitor = new DuplicateAssert.ClassVisitor();
    classVisitor.visit(testFileCompilationUnit, null);
}
 
Example 28
Source Project: kogito-runtimes   Source File: PersistenceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected void fileSystemBasedPersistence(List<GeneratedFile> generatedFiles) {
	ClassOrInterfaceDeclaration persistenceProviderClazz = new ClassOrInterfaceDeclaration()
            .setName("KogitoProcessInstancesFactoryImpl")
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addExtendedType("org.kie.kogito.persistence.KogitoProcessInstancesFactory");
    
    CompilationUnit compilationUnit = new CompilationUnit("org.kie.kogito.persistence");            
    compilationUnit.getTypes().add(persistenceProviderClazz);                 
    
    if (useInjection()) {
        annotator.withApplicationComponent(persistenceProviderClazz);            
        
        FieldDeclaration pathField = new FieldDeclaration().addVariable(new VariableDeclarator()
                                                                                 .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getCanonicalName()))))
                                                                                 .setName(PATH_NAME));
        annotator.withConfigInjection(pathField, KOGITO_PERSISTENCE_FS_PATH_PROP);
        // allow to inject path for the file system storage
        BlockStmt pathMethodBody = new BlockStmt();                
        pathMethodBody.addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(PATH_NAME), "orElse").addArgument(new StringLiteralExpr("/tmp"))));
        
        MethodDeclaration pathMethod = new MethodDeclaration()
                .addModifier(Keyword.PUBLIC)
                .setName(PATH_NAME)
                .setType(String.class)                                
                .setBody(pathMethodBody);
        
        persistenceProviderClazz.addMember(pathField);
        persistenceProviderClazz.addMember(pathMethod);
    }
    
    String packageName = compilationUnit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse("");
    String clazzName = packageName + "." + persistenceProviderClazz.findFirst(ClassOrInterfaceDeclaration.class).map(c -> c.getName().toString()).get();
 
    generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS,
                                         clazzName.replace('.', '/') + ".java",
                                         compilationUnit.toString().getBytes(StandardCharsets.UTF_8))); 
    
    persistenceProviderClazz.getMembers().sort(new BodyDeclarationComparator());
}
 
Example 29
Source Project: kogito-runtimes   Source File: MessageDataEventGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in MessageDataEventTemplate"));
    template.setName(resourceClazzName);  
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(ConstructorDeclaration.class).stream().forEach(cd -> cd.setName(resourceClazzName));

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 30
Source Project: Refactoring-Bot   Source File: RenameMethodTest.java    License: 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);
}