Java Code Examples for com.github.javaparser.ast.body.ClassOrInterfaceDeclaration#setName()

The following examples show how to use com.github.javaparser.ast.body.ClassOrInterfaceDeclaration#setName() . 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: IncrementalRuleCodegen.java    From kogito-runtimes with 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 2
Source File: ClassOrInterfaceDeclarationMerger.java    From dolphin with 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 3
Source File: MessageProducerGenerator.java    From kogito-runtimes with 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 4
Source File: MessageDataEventGenerator.java    From kogito-runtimes with 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 5
Source File: QueryEndpointGenerator.java    From kogito-runtimes with 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 6
Source File: ProcessToExecModelGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public ProcessMetaData generate(WorkflowProcess process) {
    CompilationUnit parsedClazzFile = parse(this.getClass().getResourceAsStream(PROCESS_TEMPLATE_FILE));
    parsedClazzFile.setPackageDeclaration(process.getPackageName());
    Optional<ClassOrInterfaceDeclaration> processClazzOptional = parsedClazzFile.findFirst(ClassOrInterfaceDeclaration.class, sl -> true);

    String extractedProcessId = extractProcessId(process.getId());

    if (!processClazzOptional.isPresent()) {
        throw new NoSuchElementException("Cannot find class declaration in the template");
    }
    ClassOrInterfaceDeclaration processClazz = processClazzOptional.get();
    processClazz.setName(StringUtils.capitalize(extractedProcessId + PROCESS_CLASS_SUFFIX));
    String packageName = parsedClazzFile.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse(null);
    ProcessMetaData metadata = new ProcessMetaData(process.getId(),
            extractedProcessId,
            process.getName(),
            process.getVersion(),
            packageName,
            processClazz.getNameAsString());

    Optional<MethodDeclaration> processMethod = parsedClazzFile.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("process"));

    processVisitor.visitProcess(process, processMethod.get(), metadata);

    metadata.setGeneratedClassModel(parsedClazzFile);
    return metadata;
}
 
Example 7
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with 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 (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();
        }
    }

    if (!node.getMethodsByName("failFastOffer").isEmpty()) {
        MethodDeclaration deprecatedMethodRedirect = node.addMethod("weakOffer", Keyword.PUBLIC);
        patchMethodAsDeprecatedRedirector(deprecatedMethodRedirect, "failFastOffer", PrimitiveType.intType(),
                new Parameter(classType("E"), "e"));
    }

    node.setJavadocComment(formatMultilineJavadoc(0,
            "NOTE: This class was automatically generated by "
                    + JavaParsingAtomicArrayQueueGenerator.class.getName(),
            "which can found in the jctools-build module. The original source file is " + sourceFileName + ".")
            + node.getJavadocComment().orElse(new JavadocComment("")).getContent());
}
 
Example 8
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with 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 9
Source File: MessageConsumerGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageConsumerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());
    clazz.addImport(modelfqcn);

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, dataClazzName));
    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("consume")).forEach(md -> { 
        interpolateArguments(md, "String");
        md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$Trigger$", trigger.getName())));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataType$", trigger.getDataType())));
    });
    template.findAll(MethodCallExpr.class).forEach(this::interpolateStrings);
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        template.findAll(FieldDeclaration.class,
                         fd -> isProcessField(fd)).forEach(fd -> annotator.withNamedInjection(fd, processId));
        template.findAll(FieldDeclaration.class,
                         fd -> isApplicationField(fd)).forEach(fd -> annotator.withInjection(fd));

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
        template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> annotator.withIncomingMessage(md, trigger.getName()));
    } else {
        template.findAll(FieldDeclaration.class,
                         fd -> isProcessField(fd)).forEach(fd -> initializeProcessField(fd, template));
        
        template.findAll(FieldDeclaration.class,
                         fd -> isApplicationField(fd)).forEach(fd -> initializeApplicationField(fd, template));
    }
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 10
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java"));
    clazz.setPackageDeclaration(this.packageName);

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

    template.setName(resourceClazzName);

    template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);
    template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods);

    interpolateInputType(template);

    if (useInjection()) {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
    } else {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(this::initializeApplicationField);
    }

    MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0);
    for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) {
        if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) {
            continue;
        }

        MethodDeclaration clonedMethod = dmnMethod.clone();
        String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName());
        clonedMethod.setName(name);
        MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!"));
        evaluateCall.setName(new SimpleName("evaluateDecisionService"));
        evaluateCall.addArgument(new StringLiteralExpr(ds.getName()));
        clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName())));
        ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!"));
        if (ds.getOutputDecision().size() == 1) {
            MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class,
                                                                      mce -> mce.getNameAsString().equals("extractContextIfSucceded"))
                                                           .orElseThrow(() -> new RuntimeException("Template was modified!"));
            rewrittenReturnExpr.setName("extractSingletonDSIfSucceded");
        }

        if (useMonitoring) {
            addMonitoringToMethod(clonedMethod, ds.getName());
        }

        template.addMember(clonedMethod);
    }

    if (useMonitoring) {
        addMonitoringImports(clazz);
        ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString()))
                .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed."));
        addExceptionMetricsLogging(exceptionClazz, nameURL);
        addMonitoringToMethod(dmnMethod, nameURL);
    }

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 11
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private CompilationUnit compilationUnitOutput() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream("/class-templates/TaskOutputTemplate.java"));
    compilationUnit.setPackageDeclaration(packageName);
    Optional<ClassOrInterfaceDeclaration> processMethod = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class, sl1 -> true);

    if (!processMethod.isPresent()) {
        throw new RuntimeException("Cannot find class declaration in the template");
    }
    ClassOrInterfaceDeclaration modelClass = processMethod.get();
    compilationUnit.addOrphanComment(new LineComment("Task output model for user task '" + humanTaskNode.getName() + "' in process '" + processId + "'"));
    addUserTaskAnnotation(modelClass);
    modelClass.setName(outputModelClassSimpleName);

    // setup of the toMap method body
    BlockStmt toMapBody = new BlockStmt();
    ClassOrInterfaceType toMap = new ClassOrInterfaceType(null, new SimpleName(Map.class.getSimpleName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getSimpleName()), new ClassOrInterfaceType(
                                                                                                                                                                                                                    null,
                                                                                                                                                                                                                    Object.class.getSimpleName())));
    VariableDeclarationExpr paramsField = new VariableDeclarationExpr(toMap, "params");
    toMapBody.addStatement(new AssignExpr(paramsField, new ObjectCreationExpr(null, new ClassOrInterfaceType(null, HashMap.class.getSimpleName()), NodeList.nodeList()), AssignExpr.Operator.ASSIGN));

    for (Entry<String, String> entry : humanTaskNode.getOutMappings().entrySet()) {
        if (entry.getValue() == null || INTERNAL_FIELDS.contains(entry.getKey())) {
            continue;
        }

        Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue()))
                .orElse(processVariableScope.findVariable(entry.getValue()));

        if (variable == null) {
            // check if given mapping is an expression
            Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(entry.getValue());
            if (matcher.find()) {
                Map<String, String> dataOutputs = (Map<String, String>) humanTaskNode.getMetaData("DataOutputs");
                variable = new Variable();
                variable.setName(entry.getKey());
                variable.setType(new ObjectDataType(dataOutputs.get(entry.getKey())));
            } else {
                throw new IllegalStateException("Task " + humanTaskNode.getName() +" (output) " + entry.getKey() + " reference not existing variable " + entry.getValue());
            }
        }

        FieldDeclaration fd = new FieldDeclaration().addVariable(
                                                                 new VariableDeclarator()
                                                                                         .setType(variable.getType().getStringType())
                                                                                         .setName(entry.getKey()))
                                                    .addModifier(Modifier.Keyword.PRIVATE);
        modelClass.addMember(fd);
        addUserTaskParamAnnotation(fd, UserTaskParam.ParamType.OUTPUT);

        fd.createGetter();
        fd.createSetter();

        // toMap method body
        MethodCallExpr putVariable = new MethodCallExpr(new NameExpr("params"), "put");
        putVariable.addArgument(new StringLiteralExpr(entry.getKey()));
        putVariable.addArgument(new FieldAccessExpr(new ThisExpr(), entry.getKey()));
        toMapBody.addStatement(putVariable);
    }

    Optional<MethodDeclaration> toMapMethod = modelClass.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("toMap"));

    toMapBody.addStatement(new ReturnStmt(new NameExpr("params")));
    toMapMethod.ifPresent(methodDeclaration -> methodDeclaration.setBody(toMapBody));
    return compilationUnit;
}