Java Code Examples for com.github.javaparser.ast.body.ClassOrInterfaceDeclaration

The following examples show how to use com.github.javaparser.ast.body.ClassOrInterfaceDeclaration. 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: state-machine   Author: davidmoten   File: ImmutableBeanGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static void writeEquals(PrintStream s, Map<String, String> imports, String indent,
        ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) {
    s.format("\n\n%[email protected]%s", indent, resolve(imports, Override.class));
    s.format("\n%spublic boolean equals(Object o) {", indent);
    s.format("\n%s%sif (o == null) {", indent, indent);
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else if (!(o instanceof %s)) {", indent, indent, c.getName());
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else {", indent, indent);
    if (vars.isEmpty()) {
        s.format("\n%s%s%sreturn true;", indent, indent, indent);
    } else {
        s.format("\n%s%s%s%s other = (%s) o;", indent, indent, indent, c.getName(), c.getName());
        s.format("\n%s%s%sreturn", indent, indent, indent);
        String expression = vars.stream() ///
                .map(x -> String.format("%s.deepEquals(this.%s, other.%s)", //
                        resolve(imports, Objects.class), x.getName(), x.getName())) //
                .collect(Collectors.joining(String.format("\n%s%s%s%s&& ", indent, indent, indent, indent)));
        s.format("\n%s%s%s%s%s;", indent, indent, indent, indent, expression);
    }
    s.format("\n%s%s}", indent, indent);
    s.format("\n%s}", indent);
}
 
Example #2
Source Project: flow   Author: vaadin   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 #3
Source Project: kogito-runtimes   Author: kiegroup   File: IncrementalRuleCodegen.java    License: Apache License 2.0 6 votes vote down vote up
private void generateSessionUnits( List<org.kie.kogito.codegen.GeneratedFile> generatedFiles ) {
    for (KieBaseModel kBaseModel : kieModuleModel.getKieBaseModels().values()) {
        for (String sessionName : kBaseModel.getKieSessionModels().keySet()) {
            CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) );
            ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get();
            annotator.withNamedSingletonComponent(template, "$SessionName$");
            template.setName( "SessionRuleUnit_" + sessionName );

            template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd));

            template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) );
            generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile(
                    org.kie.kogito.codegen.GeneratedFile.Type.RULE,
                    "org/drools/project/model/SessionRuleUnit_" + sessionName + ".java",
                    log( cu.toString() ) ));
        }
    }
}
 
Example #4
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String getReturnType(ClassOrInterfaceDeclaration clazz) {
    MethodDeclaration toResultMethod = clazz.getMethodsByName("toResult").get(0);
    String returnType;
    if (query.getBindings().size() == 1) {
        Map.Entry<String, Class<?>> binding = query.getBindings().entrySet().iterator().next();
        String name = binding.getKey();
        returnType = binding.getValue().getCanonicalName();

        Statement statement = toResultMethod
                .getBody()
                .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
                .getStatement(0);

        statement.findFirst(CastExpr.class).orElseThrow(() -> new NoSuchElementException("CastExpr not found in template.")).setType(returnType);
        statement.findFirst(StringLiteralExpr.class).orElseThrow(() -> new NoSuchElementException("StringLiteralExpr not found in template.")).setString(name);
    } else {
        returnType = "Result";
        generateResultClass(clazz, toResultMethod);
    }

    toResultMethod.setType(returnType);
    return returnType;
}
 
Example #5
Source Project: kogito-runtimes   Author: kiegroup   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 #6
Source Project: kogito-runtimes   Author: kiegroup   File: MarshallerGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithListMarshallers() throws Exception {

    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithList.class));
    assertThat(proto).isNotNull();
    assertThat(proto.getMessages()).hasSize(1);

    System.out.println(proto.getMessages());

    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("PersonWithListMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #7
Source Project: kogito-runtimes   Author: kiegroup   File: MarshallerGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithAdressMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithAddress.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(2);
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(2);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("AddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
    marshallerClass = classes.get(1).getClassByName("PersonWithAddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #8
Source Project: kogito-runtimes   Author: kiegroup   File: MarshallerGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPersonWithAdressesMarshallers() throws Exception {
    
    Proto proto = generator.generate("org.kie.kogito.test", Collections.singleton(PersonWithAddresses.class));
    assertThat(proto).isNotNull();        
    assertThat(proto.getMessages()).hasSize(2);

    System.out.println(proto.getMessages());
    
    MarshallerGenerator marshallerGenerator = new MarshallerGenerator(this.getClass().getClassLoader());
    
    List<CompilationUnit> classes = marshallerGenerator.generate(proto.toString());
    assertThat(classes).isNotNull();       
    assertThat(classes).hasSize(2);
    
    Optional<ClassOrInterfaceDeclaration> marshallerClass = classes.get(0).getClassByName("AddressMessageMarshaller");
    assertThat(marshallerClass).isPresent();
    marshallerClass = classes.get(1).getClassByName("PersonWithAddressesMessageMarshaller");
    assertThat(marshallerClass).isPresent();
}
 
Example #9
Source Project: kogito-runtimes   Author: kiegroup   File: DecisionCodegenTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generateAllFiles() throws Exception {

    GeneratorContext context = stronglyTypedContext();

    DecisionCodegen codeGenerator = DecisionCodegen.ofPath(Paths.get("src/test/resources/decision/models/vacationDays").toAbsolutePath());
    codeGenerator.setContext(context);

    List<GeneratedFile> generatedFiles = codeGenerator.generate();
    assertEquals(5, generatedFiles.size());

    assertIterableEquals(Arrays.asList(
            "decision/InputSet.java",
            "decision/TEmployee.java",
            "decision/TAddress.java",
            "decision/TPayroll.java",
            "decision/VacationsResource.java"
                         ),
                         fileNames(generatedFiles)
    );

    ClassOrInterfaceDeclaration classDeclaration = codeGenerator.moduleGenerator().classDeclaration();
    assertNotNull(classDeclaration);
}
 
Example #10
Source Project: apigcc   Author: apigcc   File: RequestMappingHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 判断是否为Rest接口
 * @param n
 * @return
 */
public static boolean isRest(MethodDeclaration n){
    if(n.isAnnotationPresent(ANNOTATION_RESPONSE_BODY)){
        return true;
    }
    Optional<Node> parentOptional = n.getParentNode();
    if(parentOptional.isPresent()){
        Node parentNode = parentOptional.get();
        if(parentNode instanceof ClassOrInterfaceDeclaration){
            if (((ClassOrInterfaceDeclaration) parentNode).isAnnotationPresent(SpringParser.ANNOTATION_REST_CONTROLLER)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #11
Source Project: scott   Author: dodie   File: MethodBoundaryExtractor.java    License: MIT License 6 votes vote down vote up
private boolean isInTheCorrectClass(MethodDeclaration methodDeclaration) {
	Node n = methodDeclaration;
	
	String containingClassName = "";
	while (n != null) {
		if (n instanceof ClassOrInterfaceDeclaration) {
			ClassOrInterfaceDeclaration c = (ClassOrInterfaceDeclaration) n;
			containingClassName = c.getName() + "$" + containingClassName;
		}
		Optional<Node> no = n.getParentNode();
		if (no.isEmpty()) {
			n = null;
		} else {
			n = no.get();
		}
	}
	
	containingClassName = containingClassName.substring(0, containingClassName.length() - 1);
	return containingClassName.equals(className);
}
 
Example #12
Source Project: selenium   Author: SeleniumHQ   File: CdpClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(String.format("return %s;", getMapper()));

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example #13
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: RemoveMethodParameter.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String parameterName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, parameterName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, parameterName,
			targetMethod, qualifiedNamesOfRelatedClassesAndInterfaces);
	removeParameterFromRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, targetMethod,
			parameterName);

	String targetMethodSignature = RefactoringHelper.getLocalMethodSignatureAsString(targetMethod);
	return "Removed parameter '" + parameterName + "' from method '" + targetMethodSignature + "'";
}
 
Example #14
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: RemoveMethodParameter.java    License: MIT License 6 votes vote down vote up
/**
 * Tries to find the target method in the given class or interface. Checks if
 * the found method itself could be refactored, without yet checking other code
 * locations
 * 
 * @param issue
 * @param filePath
 * @param parameterToBeRemoved
 * @return
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
private MethodDeclaration findAndValidateTargetMethod(BotIssue issue, String filePath, String parameterToBeRemoved)
		throws BotRefactoringException, FileNotFoundException {
	List<ClassOrInterfaceDeclaration> classesAndInterfaces = RefactoringHelper
			.getAllClassesAndInterfacesFromFile(filePath);

	MethodDeclaration targetMethod = null;
	for (ClassOrInterfaceDeclaration classOrInterface : classesAndInterfaces) {
		for (MethodDeclaration currentMethod : classOrInterface.getMethods()) {
			if (RefactoringHelper.isMethodDeclarationAtLine(currentMethod, issue.getLine())) {
				targetMethod = currentMethod;
				break;
			}
		}
		if (targetMethod != null) {
			break;
		}
	}

	if (targetMethod == null) {
		throw new BotRefactoringException("Could not find a method declaration at the given line!");
	}
	validateMethodHasParameter(targetMethod, parameterToBeRemoved);
	validateParameterUnused(targetMethod, parameterToBeRemoved);
	return targetMethod;
}
 
Example #15
Source Project: Briefness   Author: hacknife   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 #16
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: RenameMethod.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	configureJavaParserForProject(issue);

	String newMethodName = issue.getRefactorString();
	String issueFilePath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	MethodDeclaration targetMethod = findAndValidateTargetMethod(issue, issueFilePath, newMethodName);
	ClassOrInterfaceDeclaration targetClass = RefactoringHelper.getClassOrInterfaceOfMethod(targetMethod);
	Set<String> qualifiedNamesOfRelatedClassesAndInterfaces = RefactoringHelper
			.findRelatedClassesAndInterfaces(issue.getAllJavaFiles(), targetClass, targetMethod);

	HashSet<String> javaFilesRelevantForRefactoring = findRelevantJavaFiles(issue, newMethodName, targetMethod,
			qualifiedNamesOfRelatedClassesAndInterfaces);
	renameRelatedMethodDeclarationsAndMethodCalls(javaFilesRelevantForRefactoring, newMethodName);

	String oldMethodName = targetMethod.getNameAsString();
	return "Renamed method '" + oldMethodName + "' to '" + newMethodName + "'";
}
 
Example #17
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
    SimpleGroovyClassDoc parent = visit(n);
    if (n.isInterface()) {
        currentClassDoc.setTokenType(SimpleGroovyDoc.INTERFACE_DEF);
    } else {
        currentClassDoc.setTokenType(SimpleGroovyDoc.CLASS_DEF);
    }
    n.getExtendedTypes().forEach(et -> {
        if (n.isInterface()) {
            currentClassDoc.addInterfaceName(fullName(et));
        } else {
            currentClassDoc.setSuperClassName(fullName(et));
        }
    });
    currentClassDoc.setNameWithTypeArgs(currentClassDoc.name() + genericTypesAsString(n.getTypeParameters()));
    n.getImplementedTypes().forEach(classOrInterfaceType ->
            currentClassDoc.addInterfaceName(fullName(classOrInterfaceType)));
    super.visit(n, arg);
    if (parent != null) {
        currentClassDoc = parent;
    }
}
 
Example #18
Source Project: dolphin   Author: beihaifeiwu   File: ClassOrInterfaceDeclarationMerger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration doMerge(ClassOrInterfaceDeclaration first, ClassOrInterfaceDeclaration second) {

  ClassOrInterfaceDeclaration declaration = new ClassOrInterfaceDeclaration();

  declaration.setInterface(first.isInterface());
  declaration.setName(first.getName());

  declaration.setModifiers(mergeModifiers(first.getModifiers(), second.getModifiers()));
  declaration.setJavaDoc(mergeSingle(first.getJavaDoc(), second.getJavaDoc()));
  declaration.setTypeParameters(mergeCollections(first.getTypeParameters(), second.getTypeParameters()));

  declaration.setImplements(mergeCollections(first.getImplements(), second.getImplements()));
  declaration.setExtends(mergeCollections(first.getExtends(), second.getExtends()));

  declaration.setAnnotations(mergeCollections(first.getAnnotations(), second.getAnnotations()));
  declaration.setMembers(mergeCollections(first.getMembers(), second.getMembers()));

  return declaration;
}
 
Example #19
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: RefactoringHelper.java    License: MIT License 6 votes vote down vote up
/**
 * @param allJavaFiles
 * @param targetClass
 * @param targetMethod
 * @return list of qualified class or interface names which are reachable via
 *         the inheritance hierarchy of the given class (ancestors, descendants,
 *         siblings, ...) and contain the given target method
 * @throws BotRefactoringException
 * @throws FileNotFoundException
 */
public static Set<String> findRelatedClassesAndInterfaces(List<String> allJavaFiles,
		ClassOrInterfaceDeclaration targetClass, MethodDeclaration targetMethod)
		throws BotRefactoringException, FileNotFoundException {
	Set<ResolvedReferenceTypeDeclaration> relatedClassesAndInterfaces = new HashSet<>();
	relatedClassesAndInterfaces.add(targetClass.resolve());

	addQualifiedNamesToRelatedClassesAndInterfacesRecursively(relatedClassesAndInterfaces, allJavaFiles,
			targetClass, targetMethod);

	Set<String> result = new HashSet<>();
	for (ResolvedReferenceTypeDeclaration declaration : relatedClassesAndInterfaces) {
		result.add(declaration.getQualifiedName());
	}

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

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

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

	// assert
	assertThat(classOrInterface).isNotNull();
	assertThat(classOrInterface.getNameAsString()).isEqualTo(TARGET_CLASS_NAME);
}
 
Example #21
Source Project: JApiDocs   Author: YeDaxia   File: SpringControllerParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeHandleController(ControllerNode controllerNode, ClassOrInterfaceDeclaration clazz) {
    clazz.getAnnotationByName("RequestMapping").ifPresent(a -> {
        if (a instanceof SingleMemberAnnotationExpr) {
            String baseUrl = ((SingleMemberAnnotationExpr) a).getMemberValue().toString();
            controllerNode.setBaseUrl(Utils.removeQuotations(baseUrl));
            return;
        }
        if (a instanceof NormalAnnotationExpr) {
            ((NormalAnnotationExpr) a).getPairs().stream()
                    .filter(v -> isUrlPathKey(v.getNameAsString()))
                    .findFirst()
                    .ifPresent(p -> {
                        controllerNode.setBaseUrl(Utils.removeQuotations(p.getValue().toString()));
                    });
        }
    });
}
 
Example #22
Source Project: butterfly   Author: paypal   File: Extends.java    License: MIT License 6 votes vote down vote up
@Override
protected String getTypeName(CompilationUnit compilationUnit, int index) {
    ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
    NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
    ClassOrInterfaceType extendedType = extendedTypes.get(index);
    String typeSimpleName = extendedType.getName().getIdentifier();
    Optional<ClassOrInterfaceType> scope = extendedType.getScope();
    String typeName;
    if (scope.isPresent()) {
        String typePackageName = scope.get().toString();
        typeName = String.format("%s.%s", typePackageName, typeSimpleName);
    } else {
        typeName = typeSimpleName;
    }
    return typeName;
}
 
Example #23
Source Project: kogito-runtimes   Author: kiegroup   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 #24
Source Project: JCTools   Author: JCTools   File: JavaParsingAtomicLinkedQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration node, Void arg) {
    super.visit(node, arg);

    replaceParentClassesForAtomics(node);

    node.setName(translateQueueName(node.getNameAsString()));
    if (MPSC_LINKED_ATOMIC_QUEUE_NAME.equals(node.getNameAsString())) {
        /*
         * Special case for MPSC
         */
        node.removeModifier(Keyword.ABSTRACT);
    }

    if (isCommentPresent(node, GEN_DIRECTIVE_CLASS_CONTAINS_ORDERED_FIELD_ACCESSORS)) {
        node.setComment(null);
        removeStaticFieldsAndInitialisers(node);
        patchAtomicFieldUpdaterAccessorMethods(node);
    }

    for (MethodDeclaration method : node.getMethods()) {
        if (isCommentPresent(method, GEN_DIRECTIVE_METHOD_IGNORE)) {
            method.remove();
        }
    }

    node.setJavadocComment(formatMultilineJavadoc(0,
            "NOTE: This class was automatically generated by "
                    + JavaParsingAtomicLinkedQueueGenerator.class.getName(),
            "which can found in the jctools-build module. The original source file is " + sourceFileName + ".")
            + node.getJavadocComment().orElse(new JavadocComment("")).getContent());
}
 
Example #25
Source Project: kogito-runtimes   Author: kiegroup   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 #26
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new NullLiteralExpr()));

    NodeList<Expression> processIds = NodeList.nodeList(processes.stream().map(p -> new StringLiteralExpr(p.processId())).collect(Collectors.toList()));
    processesMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(Arrays.class.getCanonicalName()), "asList", processIds)));

    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    applicationDeclarations.add( applicationFieldDeclaration );

    ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration("Processes")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter( "Application", "application" )
            .setBody( new BlockStmt().addStatement( "this.application = application;" ) );
    applicationDeclarations.add( constructorDeclaration );

    ClassOrInterfaceDeclaration cls = super.classDeclaration().setMembers(applicationDeclarations);
    cls.getMembers().sort(new BodyDeclarationComparator());
    
    return cls;
}
 
Example #27
Source Project: deadcode4j   Author: Scout24   File: TypeErasureAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, A arg) {
    this.definedTypeParameters.addLast(getTypeParameterNames(n.getTypeParameters()));
    try {
        super.visit(n, arg);
    } finally {
        this.definedTypeParameters.removeLast();
    }
}
 
Example #28
Source Project: state-machine   Author: davidmoten   File: ImmutableBeanGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static List<FieldDeclaration> getFields(ClassOrInterfaceDeclaration c) {
    List<FieldDeclaration> fields = c.getChildNodes() //
            .stream() //
            .filter(x -> x instanceof FieldDeclaration) //
            .map(x -> (FieldDeclaration) x) //
            .collect(Collectors.toList());
    return fields;
}
 
Example #29
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/RestQueryTemplate.java"));
    cu.setPackageDeclaration(query.getNamespace());

    ClassOrInterfaceDeclaration clazz = cu
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    clazz.setName(targetCanonicalName);

    cu.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);

    FieldDeclaration ruleUnitDeclaration = clazz
            .getFieldByName("ruleUnit")
            .orElseThrow(() -> new NoSuchElementException("ClassOrInterfaceDeclaration doesn't contain a field named ruleUnit!"));
    setUnitGeneric(ruleUnitDeclaration.getElementType());
    if (annotator != null) {
        annotator.withInjection(ruleUnitDeclaration);
    }

    String returnType = getReturnType(clazz);
    generateConstructors(clazz);
    generateQueryMethods(cu, clazz, returnType);
    clazz.getMembers().sort(new BodyDeclarationComparator());
    return cu.toString();
}
 
Example #30
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateConstructors(ClassOrInterfaceDeclaration clazz) {
    for (ConstructorDeclaration c : clazz.getConstructors()) {
        c.setName(targetCanonicalName);
        if (!c.getParameters().isEmpty()) {
            setUnitGeneric(c.getParameter(0).getType());
        }
    }
}