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

The following examples show how to use com.github.javaparser.ast.body.ClassOrInterfaceDeclaration#addMember() . 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: RuleUnitInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String canonicalName = ruleUnitDescription.getRuleUnitName();
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractRuleUnitInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, canonicalName)))
            .addConstructor(Modifier.Keyword.PUBLIC)
            .addParameter(RuleUnitGenerator.ruleUnitType(canonicalName), "unit")
            .addParameter(canonicalName, "value")
            .addParameter(KieSession.class.getCanonicalName(), "session")
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr("unit"),
                    new NameExpr("value"),
                    new NameExpr("session")
            )));
    classDecl.addMember(bindMethod());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example 2
Source File: PersistenceGenerator.java    From kogito-runtimes with 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 3
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
    ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
    clazz.addMember(resultClass);

    ConstructorDeclaration constructor = resultClass.addConstructor(Modifier.Keyword.PUBLIC);
    BlockStmt constructorBody = constructor.createBody();

    ObjectCreationExpr resultCreation = new ObjectCreationExpr();
    resultCreation.setType("Result");
    BlockStmt resultMethodBody = toResultMethod.createBody();
    resultMethodBody.addStatement(new ReturnStmt(resultCreation));

    query.getBindings().forEach((name, type) -> {
        resultClass.addField(type, name, Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL);

        MethodDeclaration getterMethod = resultClass.addMethod("get" + ucFirst(name), Modifier.Keyword.PUBLIC);
        getterMethod.setType(type);
        BlockStmt body = getterMethod.createBody();
        body.addStatement(new ReturnStmt(new NameExpr(name)));

        constructor.addAndGetParameter(type, name);
        constructorBody.addStatement(new AssignExpr(new NameExpr("this." + name), new NameExpr(name), AssignExpr.Operator.ASSIGN));

        MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
        callExpr.addArgument(new StringLiteralExpr(name));
        resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
    });
}
 
Example 4
Source File: RuleUnitDTOSourceClass.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(packageName);

    ClassOrInterfaceDeclaration dtoClass = cu.addClass(targetCanonicalName, Modifier.Keyword.PUBLIC);
    dtoClass.addImplementedType(String.format("java.util.function.Supplier<%s>", ruleUnit.getSimpleName()));

    MethodDeclaration supplier = dtoClass.addMethod("get", Modifier.Keyword.PUBLIC);
    supplier.addAnnotation(Override.class);
    supplier.setType(ruleUnit.getSimpleName());
    BlockStmt supplierBlock = supplier.createBody();
    supplierBlock.addStatement(String.format("%s unit = new %s();", ruleUnit.getSimpleName(), ruleUnit.getSimpleName()));

    for (RuleUnitVariable unitVarDeclaration : ruleUnit.getUnitVarDeclarations()) {
        FieldProcessor fieldProcessor = new FieldProcessor(unitVarDeclaration, ruleUnitHelper );
        FieldDeclaration field = fieldProcessor.createField();
        supplierBlock.addStatement(fieldProcessor.fieldInitializer());
        dtoClass.addMember(field);
        field.createGetter();
        field.createSetter();
    }

    supplierBlock.addStatement("return unit;");

    return cu.toString();
}
 
Example 5
Source File: RuleUnitPojoGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private ClassOrInterfaceDeclaration classOrInterfaceDeclaration() {
    ClassOrInterfaceDeclaration c =
            new ClassOrInterfaceDeclaration()
                    .setPublic(true)
                    .addImplementedType(RuleUnitData.class.getCanonicalName())
                    .setName(ruleUnitDescription.getSimpleName());

    for (RuleUnitVariable v : ruleUnitDescription.getUnitVarDeclarations()) {
        ClassOrInterfaceType t = new ClassOrInterfaceType()
                .setName(v.getType().getCanonicalName());
        FieldDeclaration f = new FieldDeclaration();
        VariableDeclarator vd = new VariableDeclarator(t, v.getName());
        f.getVariables().add(vd);
        if (v.isDataSource()) {
            t.setTypeArguments( StaticJavaParser.parseType( v.getDataSourceParameterType().getCanonicalName() ) );
            if (ruleUnitHelper.isAssignableFrom(DataStore.class, v.getType())) {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createStore()");
            } else {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createSingleton()");
            }
        }
        c.addMember(f);
        f.createGetter();
        if (v.setter() != null) {
            f.createSetter();
        }
    }

    return c;
}
 
Example 6
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 7
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;
}
 
Example 8
Source File: ServiceTaskDescriptor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String unqualifiedName = StaticJavaParser.parseName(mangledName).removeQualifier().asString();
    ClassOrInterfaceDeclaration cls = new ClassOrInterfaceDeclaration()
            .setName(unqualifiedName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addImplementedType(WorkItemHandler.class.getCanonicalName());
    ClassOrInterfaceType serviceType = new ClassOrInterfaceType(null, interfaceName);
    FieldDeclaration serviceField = new FieldDeclaration()
            .addVariable(new VariableDeclarator(serviceType, "service"));
    cls.addMember(serviceField);

    // executeWorkItem method
    BlockStmt executeWorkItemBody = new BlockStmt();
    MethodDeclaration executeWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("executeWorkItem")
            .setBody(executeWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    MethodCallExpr callService = new MethodCallExpr(new NameExpr("service"), operationName);

    for (Map.Entry<String, String> paramEntry : parameters.entrySet()) {
        MethodCallExpr getParamMethod = new MethodCallExpr(new NameExpr("workItem"), "getParameter").addArgument(new StringLiteralExpr(paramEntry.getKey()));
        callService.addArgument(new CastExpr(new ClassOrInterfaceType(null, paramEntry.getValue()), getParamMethod));
    }
    MethodCallExpr completeWorkItem = completeWorkItem(executeWorkItemBody, callService);

    executeWorkItemBody.addStatement(completeWorkItem);

    // abortWorkItem method
    BlockStmt abortWorkItemBody = new BlockStmt();
    MethodDeclaration abortWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("abortWorkItem")
            .setBody(abortWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    // getName method
    MethodDeclaration getName = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(String.class)
            .setName("getName")
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(mangledName))));
    cls.addMember(executeWorkItem)
            .addMember(abortWorkItem)
            .addMember(getName);

    return cls;
}