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

The following examples show how to use com.github.javaparser.ast.Modifier. 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: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration unbind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(model.fromMap("variables", "vmap"));

    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("unbind")
            .setType(new VoidType())
            .addParameter(modelName, "variables")
            .addParameter(new ClassOrInterfaceType()
                                  .setName("java.util.Map")
                                  .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                                    new ClassOrInterfaceType().setName("Object")),
                          "vmap")
            .setBody(body);
}
 
Example 2
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 3
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            new NameExpr(BUSINESS_KEY),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 4
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance")
            .addArgument(new NameExpr(BUSINESS_KEY))
            .addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 5
public ProcessesContainerGenerator(String packageName) {
    super("Processes", "processes", Processes.class);
    this.packageName = packageName;
    this.processes = new ArrayList<>();
    this.factoryMethods = new ArrayList<>();
    this.applicationDeclarations = new NodeList<>();

    byProcessIdMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processById")
            .setType(new ClassOrInterfaceType(null, org.kie.kogito.process.Process.class.getCanonicalName())
                             .setTypeArguments(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName()))))
            .setBody(new BlockStmt())
            .addParameter("String", "processId");

    processesMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processIds")
            .setType(new ClassOrInterfaceType(null, Collection.class.getCanonicalName())
                             .setTypeArguments(new ClassOrInterfaceType(null, "String")))
            .setBody(new BlockStmt());

    applicationDeclarations.add(byProcessIdMethodDeclaration);
    applicationDeclarations.add(processesMethodDeclaration);
}
 
Example 6
Source Project: kogito-runtimes   Source File: ProcessConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedProcessEventListenerConfig.class,
            callMerge(
                    VAR_PROCESS_EVENT_LISTENER_CONFIGS,
                    ProcessEventListenerConfig.class, "listeners",
                    VAR_PROCESS_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, ProcessEventListenerConfig.class)).setName(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, ProcessEventListener.class)).setName(VAR_PROCESS_EVENT_LISTENERS)
            ),
            body);
}
 
Example 7
Source Project: kogito-runtimes   Source File: RuleUnitInstanceGenerator.java    License: 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 8
Source Project: kogito-runtimes   Source File: RuleConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration relcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleEventListenerConfig.class), VAR_RULE_EVENT_LISTENER_CONFIGS)));
            members.add(relcFieldDeclaration);

            FieldDeclaration aelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), AgendaEventListener.class), VAR_AGENDA_EVENT_LISTENERS)));
            members.add(aelFieldDeclaration);

            FieldDeclaration rrelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleRuntimeEventListener.class), VAR_RULE_RUNTIME_EVENT_LISTENERS)));
            members.add(rrelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultRelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, RuleEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_RULE_EVENT_LISTENER_CONFIG, newObject(DefaultRuleEventListenerConfig.class)));
            members.add(defaultRelcFieldDeclaration);
        }

        return members;
    }
 
Example 9
Source Project: kogito-runtimes   Source File: RuleConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedRuleEventListenerConfig.class,
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "agendaListeners",
                    VAR_AGENDA_EVENT_LISTENERS
            ),
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "ruleRuntimeListeners",
                    VAR_RULE_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, RuleEventListenerConfig.class, METHOD_MERGE_RULE_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, RuleEventListenerConfig.class)).setName(VAR_RULE_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, AgendaEventListener.class)).setName(VAR_AGENDA_EVENT_LISTENERS),
                    new Parameter().setType(genericType(Collection.class, RuleRuntimeEventListener.class)).setName(VAR_RULE_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example 10
Source Project: kogito-runtimes   Source File: DecisionConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration delcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DecisionEventListenerConfig.class), VAR_DECISION_EVENT_LISTENER_CONFIG)));
            members.add(delcFieldDeclaration);

            FieldDeclaration drelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DMNRuntimeEventListener.class), VAR_DMN_RUNTIME_EVENT_LISTENERS)));
            members.add(drelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultDelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, DecisionEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_DECISION_EVENT_LISTENER_CONFIG, newObject(DefaultDecisionEventListenerConfig.class)));
            members.add(defaultDelcFieldDeclaration);
        }

        return members;
    }
 
Example 11
Source Project: kogito-runtimes   Source File: DecisionConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedDecisionEventListenerConfig.class,
            callMerge(
                    VAR_DECISION_EVENT_LISTENER_CONFIG,
                    DecisionEventListenerConfig.class, "listeners",
                    VAR_DMN_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, DecisionEventListenerConfig.class, METHOD_MERGE_DECISION_EVENT_LISTENER_CONFIG,
            nodeList(
                    new Parameter().setType(genericType(Collection.class, DecisionEventListenerConfig.class)).setName(VAR_DECISION_EVENT_LISTENER_CONFIG),
                    new Parameter().setType(genericType(Collection.class, DMNRuntimeEventListener.class)).setName(VAR_DMN_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example 12
Source Project: TestSmellDetector   Source File: LazyTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {
    // ensure that this method is only executed for the test file
    if (Objects.equals(fileType, TEST_FILE)) {
        if (Util.isValidTestMethod(n)) {
            currentMethod = n;
            testMethod = new TestMethod(currentMethod.getNameAsString());
            testMethod.setHasSmell(false); //default value is false (i.e. no smell)
            super.visit(n, arg);

            //reset values for next method
            currentMethod = null;
            productionVariables = new ArrayList<>();
        }
    } else { //collect a list of all public/protected members of the production class
        for (Modifier modifier : n.getModifiers()) {
            if (modifier.name().toLowerCase().equals("public") || modifier.name().toLowerCase().equals("protected")) {
                productionMethods.add(n);
            }
        }

    }
}
 
Example 13
/**
 * The purpose of this method is to 'visit' all test methods in the test file.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {

    //JUnit 4
    //check if test method has Ignore annotation
    if (n.getAnnotationByName("Test").isPresent()) {
        if (n.getAnnotationByName("Ignore").isPresent()) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }

    //JUnit 3
    //check if test method is not public
    if (n.getNameAsString().toLowerCase().startsWith("test")) {
        if (!n.getModifiers().contains(Modifier.PUBLIC)) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }
}
 
Example 14
private void getParameterNames(MethodDeclaration methodDeclaration, boolean isInterface) {
  NodeList<Modifier> modifiers = methodDeclaration.getModifiers();
  if (isInterface || modifiers.contains(Modifier.publicModifier())) {
    String methodName = methodDeclaration.getName().getIdentifier();
    List<Parameter> parameters = methodDeclaration.getParameters();
    names.className = this.className;
    List<List<ParameterName>> parameterNames =
        names.names.computeIfAbsent(methodName, k -> new ArrayList<>(4));

    final List<ParameterName> temp = new ArrayList<>(8);
    for (final Parameter parameter : parameters) {
      ParameterName parameterName = new ParameterName();
      String type = parameter.getType().toString();
      String name = parameter.getName().getIdentifier();
      if (name.contains("[]")) {
        type = type + "[]";
        name = COMPILE.matcher(name).replaceAll(Matcher.quoteReplacement(""));
      }
      parameterName.type = type;
      parameterName.name = name;
      temp.add(parameterName);
    }
    parameterNames.add(temp);
  }
}
 
Example 15
Source Project: groovy   Source File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private SimpleGroovyClassDoc visit(TypeDeclaration<?> n) {
    SimpleGroovyClassDoc parent = null;
    List<String> imports = getImports();
    String name = n.getNameAsString();
    if (n.isNestedType()) {
        parent = currentClassDoc;
        name = parent.name() + "$" + name;
    }
    currentClassDoc = new SimpleGroovyClassDoc(imports, aliases, name.replace('$', '.'), links);
    NodeList<Modifier> mods = n.getModifiers();
    if (parent != null) {
        parent.addNested(currentClassDoc);
        if (parent.isInterface()) {
            // an inner interface/class within an interface is public
            mods.add(Modifier.publicModifier());
        }
    }
    setModifiers(mods, currentClassDoc);
    processAnnotations(currentClassDoc, n);
    currentClassDoc.setFullPathName(withSlashes(packagePath + FS + name));
    classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc);
    n.getJavadocComment().ifPresent(javadocComment ->
            currentClassDoc.setRawCommentText(javadocComment.getContent()));
    return parent;
}
 
Example 16
Source Project: groovy   Source File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void setModifiers(NodeList<Modifier> modifiers, SimpleGroovyAbstractableElementDoc elementDoc) {
    if (modifiers.contains(Modifier.publicModifier())) {
        elementDoc.setPublic(true);
    }
    if (modifiers.contains(Modifier.staticModifier())) {
        elementDoc.setStatic(true);
    }
    if (modifiers.contains(Modifier.abstractModifier())) {
        elementDoc.setAbstract(true);
    }
    if (modifiers.contains(Modifier.finalModifier())) {
        elementDoc.setFinal(true);
    }
    if (modifiers.contains(Modifier.protectedModifier())) {
        elementDoc.setProtected(true);
    }
    if (modifiers.contains(Modifier.privateModifier())) {
        elementDoc.setPrivate(true);
    }
}
 
Example 17
Source Project: groovy   Source File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void setConstructorOrMethodCommon(CallableDeclaration<? extends CallableDeclaration<?>> n, SimpleGroovyExecutableMemberDoc methOrCons) {
    n.getJavadocComment().ifPresent(javadocComment ->
            methOrCons.setRawCommentText(javadocComment.getContent()));
    NodeList<Modifier> mods = n.getModifiers();
    if (currentClassDoc.isInterface()) {
        mods.add(Modifier.publicModifier());
    }
    setModifiers(mods, methOrCons);
    processAnnotations(methOrCons, n);
    for (Parameter param : n.getParameters()) {
        SimpleGroovyParameter p = new SimpleGroovyParameter(param.getNameAsString());
        processAnnotations(p, param);
        p.setType(makeType(param.getType()));
        methOrCons.add(p);
    }
}
 
Example 18
Source Project: kogito-runtimes   Source File: CodegenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodDeclaration method(Modifier.Keyword modifier, Class<?> type, String name, NodeList<Parameter> parameters, BlockStmt body) {
    return new MethodDeclaration()
            .setModifiers(modifier)
            .setType(type == null ? "void" : type.getCanonicalName())
            .setName(name)
            .setParameters(parameters)
            .setBody(body);
}
 
Example 19
Source Project: kogito-runtimes   Source File: CodegenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodDeclaration extractOptionalInjection(String type, String fieldName, String defaultMethod, DependencyInjectionAnnotator annotator) {
    BlockStmt body = new BlockStmt();
    MethodDeclaration extractMethod = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setName("extract_" + fieldName)
            .setType(type)
            .setBody(body);
    Expression condition = annotator.optionalInstanceExists(fieldName);
    IfStmt valueExists = new IfStmt(condition, new ReturnStmt(annotator.getOptionalInstance(fieldName)), new ReturnStmt(new NameExpr(defaultMethod)));
    body.addStatement(valueExists);
    return extractMethod;
}
 
Example 20
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractProcessInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, model.getModelClassSimpleName())))
            .addMember(constructorDecl())
            .addMember(constructorWithBusinessKeyDecl())
            .addMember(bind())
            .addMember(unbind());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example 21
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration bind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(new ReturnStmt(model.toMap("variables")));
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("bind")
            .addParameter(modelName, "variables")
            .setType(new ClassOrInterfaceType()
                             .setName("java.util.Map")
                             .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                               new ClassOrInterfaceType().setName("Object")))
            .setBody(body);

}
 
Example 22
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example 23
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorWithBusinessKeyDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(String.class.getCanonicalName(), "businessKey")
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr("businessKey"),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example 24
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 25
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration createInstanceGenericMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance").addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 26
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration legacyProcess(ProcessMetaData processMetaData) {
    return processMetaData.getGeneratedClassModel()
            .findFirst(MethodDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a method declaration!"))
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(Process.class.getCanonicalName())
            .setName("legacyProcess");
}
 
Example 27
@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 28
Source Project: kogito-runtimes   Source File: ProcessConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG, NodeList.nodeList(
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG, body);
}
 
Example 29
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: 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 30
private MethodDeclaration genericFactoryById() {
    ClassOrInterfaceType returnType = new ClassOrInterfaceType(null, RuleUnit.class.getCanonicalName())
            .setTypeArguments(new WildcardType());

    SwitchStmt switchStmt = new SwitchStmt();
    switchStmt.setSelector(new NameExpr("fqcn"));

    for (RuleUnitGenerator ruleUnit : ruleUnits) {
        SwitchEntry switchEntry = new SwitchEntry();
        switchEntry.getLabels().add(new StringLiteralExpr(ruleUnit.getRuleUnitDescription().getCanonicalName()));
        ObjectCreationExpr ruleUnitConstructor = new ObjectCreationExpr()
                .setType(ruleUnit.targetCanonicalName())
                .addArgument("application");
        switchEntry.getStatements().add(new ReturnStmt(ruleUnitConstructor));
        switchStmt.getEntries().add(switchEntry);
    }

    SwitchEntry defaultEntry = new SwitchEntry();
    defaultEntry.getStatements().add(new ThrowStmt(new ObjectCreationExpr().setType(UnsupportedOperationException.class.getCanonicalName())));
    switchStmt.getEntries().add(defaultEntry);

    return new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setType(returnType)
            .setName("create")
            .addParameter(String.class, "fqcn")
            .setBody(new BlockStmt().addStatement(switchStmt));
}