Java Code Examples for com.github.javaparser.ast.stmt.BlockStmt

The following examples show how to use com.github.javaparser.ast.stmt.BlockStmt. 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
private void extractResultsFromIfStmt(IfStmt ifStmt, CodeAnalysisResult result) {
    Statement then = ifStmt.getThenStmt();
    Statement otherwise = ifStmt.getElseStmt().orElse(null);
    if (then instanceof BlockStmt) {

        List<Statement> thenBlockStmts = ((BlockStmt) then).getStatements();
        if (otherwise == null) {
            /*
             * This takes only the non-coverable one, meaning
             * that if } is on the same line of the last stmt it
             * is not considered here because it is should be already
             * considered
             */
            if (!thenBlockStmts.isEmpty()) {
                Statement lastInnerStatement = thenBlockStmts.get(thenBlockStmts.size() - 1);
                if (lastInnerStatement.getEnd().get().line < ifStmt.getEnd().get().line) {
                    result.closingBracket(Range.between(then.getBegin().get().line, ifStmt.getEnd().get().line));
                    result.nonCoverableCode(ifStmt.getEnd().get().line);
                }
            }
        } else {
            result.closingBracket(Range.between(then.getBegin().get().line, then.getEnd().get().line));
            result.nonCoverableCode(otherwise.getBegin().get().line);
        }
    }
}
 
Example 2
@Override
public MethodDeclaration withInitMethod(Expression... expression) {
    BlockStmt body = new BlockStmt();
    for (Expression exp : expression) {
        body.addStatement(exp);
    }
    MethodDeclaration method = new MethodDeclaration()
            .addModifier(Keyword.PUBLIC)
            .setName("init")
            .setType(void.class)
            .setBody(body);

    method.addAndGetParameter("io.quarkus.runtime.StartupEvent", "event").addAnnotation("javax.enterprise.event.Observes");

    return method;
}
 
Example 3
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 4
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 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
@Override
public void visit(final BlockStmt n, final Void arg) {
    printOrphanCommentsBeforeThisChildNode(n);
    printJavaComment(n.getComment(), arg);
    printer.println("{");
    if (n.getStatements() != null) {
        printer.indent();
        for (final Statement s : n.getStatements()) {
            s.accept(this, arg);
            printer.println();
        }
        printer.unindent();
    }
    printOrphanCommentsEnding(n);
    printer.print("}");
}
 
Example 7
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private BlockStmt wrapBodyAddingExceptionLogging(BlockStmt body, String nameURL) {
    TryStmt ts = new TryStmt();
    ts.setTryBlock(body);
    CatchClause cc = new CatchClause();
    String exceptionName = "e";
    cc.setParameter(new Parameter().setName(exceptionName).setType(Exception.class));
    BlockStmt cb = new BlockStmt();
    cb.addStatement(parseStatement(
            String.format(
                    "SystemMetricsCollector.registerException(\"%s\", %s.getStackTrace()[0].toString());",
                    nameURL,
                    exceptionName)
    ));
    cb.addStatement(new ThrowStmt(new NameExpr(exceptionName)));
    cc.setBody(cb);
    ts.setCatchClauses(new NodeList<>(cc));
    return new BlockStmt(new NodeList<>(ts));
}
 
Example 8
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 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: KieModuleModelMethod.java    License: Apache License 2.0 6 votes vote down vote up
public String toKieSessionConfMethod() {
    StringBuilder sb = new StringBuilder(
            "    private org.kie.api.runtime.KieSessionConfiguration getConfForSession(String sessionName) {\n" +
            "        org.drools.core.SessionConfigurationImpl conf = new org.drools.core.SessionConfigurationImpl();\n" +
            "        switch (sessionName) {\n"
    );

    for (Map.Entry<String, BlockStmt> entry : kSessionConfs.entrySet()) {
        sb.append( "            case \"" + entry.getKey() + "\":\n" );
        sb.append( entry.getValue() );
        sb.append( "                break;\n" );
    }

    sb.append(
            "        }\n" +
            "        return conf;\n" +
            "    }\n" );
    return sb.toString();
}
 
Example 11
@Override
public List<Statement> setupStatements() {
    return Collections.singletonList(
            new IfStmt(
                    new BinaryExpr(
                            new MethodCallExpr(new MethodCallExpr(null, "config"), "decision"),
                            new NullLiteralExpr(),
                            BinaryExpr.Operator.NOT_EQUALS
                    ),
                    new BlockStmt().addStatement(new ExpressionStmt(new MethodCallExpr(
                            new NameExpr("decisionModels"), "init", NodeList.nodeList(new ThisExpr())
                    ))),
                    null
            )
    );
}
 
Example 12
Source Project: enkan   Source File: FormTask.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration setterDeclaration(EntityField field) {
    MethodDeclaration decl = new MethodDeclaration(ModifierSet.PUBLIC,
            new VoidType(),
            "set" + CaseConverter.pascalCase(field.getName()),
            Collections.singletonList(new Parameter(
                    ASTHelper.createReferenceType(field.getType().getSimpleName(), 0),
                    new VariableDeclaratorId(field.getName()))));

    BlockStmt body = new BlockStmt();
    body.setStmts(
            Collections.singletonList(
                    new ExpressionStmt(
                            new AssignExpr(
                                    new FieldAccessExpr(new ThisExpr(), field.getName()),
                                    ASTHelper.createNameExpr(field.getName()),
                                    AssignExpr.Operator.assign
                            ))));
    decl.setBody(body);
    return decl;
}
 
Example 13
Source Project: kogito-runtimes   Source File: TriggerMetaData.java    License: Apache License 2.0 6 votes vote down vote up
public static LambdaExpr buildLambdaExpr(Node node, ProcessMetaData metadata) {
    Map<String, Object> nodeMetaData = node.getMetaData();
    TriggerMetaData triggerMetaData = new TriggerMetaData(
            (String) nodeMetaData.get(TRIGGER_REF),
            (String) nodeMetaData.get(TRIGGER_TYPE),
            (String) nodeMetaData.get(MESSAGE_TYPE),
            (String) nodeMetaData.get(MAPPING_VARIABLE),
            String.valueOf(node.getId()))
            .validate();
    metadata.getTriggers().add(triggerMetaData);

    // and add trigger action
    BlockStmt actionBody = new BlockStmt();
    CastExpr variable = new CastExpr(
            new ClassOrInterfaceType(null, triggerMetaData.getDataType()),
            new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable")
                    .addArgument(new StringLiteralExpr(triggerMetaData.getModelRef())));
    MethodCallExpr producerMethodCall = new MethodCallExpr(new NameExpr("producer_" + node.getId()), "produce").addArgument(new MethodCallExpr(new NameExpr("kcontext"), "getProcessInstance")).addArgument(variable);
    actionBody.addStatement(producerMethodCall);
    return new LambdaExpr(
            new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
            actionBody
    );
}
 
Example 14
@Override
public void visitNode(String factoryField, T node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, factoryClass(), getNodeId(node), factoryMethod(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, getDefaultName()));
    visitMetaData(node.getMetaData(), body, getNodeId(node));
    VariableScope variableScopeNode = (VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE);

    if (variableScope != null) {
        visitVariableScope(getNodeId(node), variableScopeNode, body, new HashSet<>());
    }

    visitCustomFields(node, variableScope).forEach(body::addStatement);

    // composite context node might not have variable scope
    // in that case inherit it from parent
    VariableScope scope = variableScope;
    if (node.getDefaultContext(VariableScope.VARIABLE_SCOPE) != null && !((VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE)).getVariables().isEmpty()) {
        scope = (VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE);
    }
    body.addStatement(getFactoryMethod(getNodeId(node), CompositeContextNodeFactory.METHOD_AUTO_COMPLETE, new BooleanLiteralExpr(node.isAutoComplete())));
    visitNodes(getNodeId(node), node.getNodes(), body, scope, metadata);
    visitConnections(getNodeId(node), node.getNodes(), body);
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example 15
Source Project: kogito-runtimes   Source File: TimerNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(String factoryField, TimerNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, TimerNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
    .addStatement(getNameMethod(node,"Timer"));

    Timer timer = node.getTimer();
    body.addStatement(getFactoryMethod(getNodeId(node), METHOD_TYPE, new IntegerLiteralExpr(timer.getTimeType())));

    if (timer.getTimeType() == Timer.TIME_CYCLE) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_DELAY, new StringLiteralExpr(timer.getDelay())));
        if (timer.getPeriod() != null && !timer.getPeriod().isEmpty()) {
            body.addStatement(getFactoryMethod(getNodeId(node), METHOD_PERIOD, new StringLiteralExpr(timer.getPeriod())));
        }
    } else if (timer.getTimeType() == Timer.TIME_DURATION) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_DELAY, new StringLiteralExpr(timer.getDelay())));
    } else if (timer.getTimeType() == Timer.TIME_DATE) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_DATE, new StringLiteralExpr(timer.getDate())));
    }

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example 16
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleDecision(RuleSetNode.RuleType.Decision ruleType) {

        StringLiteralExpr namespace = new StringLiteralExpr(ruleType.getNamespace());
        StringLiteralExpr model = new StringLiteralExpr(ruleType.getModel());
        Expression decision = ruleType.getDecision() == null ?
                new NullLiteralExpr() : new StringLiteralExpr(ruleType.getDecision());

        MethodCallExpr decisionModels =
                new MethodCallExpr(new NameExpr("app"), "decisionModels");
        MethodCallExpr decisionModel =
                new MethodCallExpr(decisionModels, "getDecisionModel")
                        .addArgument(namespace)
                        .addArgument(model);

        BlockStmt actionBody = new BlockStmt();
        LambdaExpr lambda = new LambdaExpr(new Parameter(new UnknownType(), "()"), actionBody);
        actionBody.addStatement(new ReturnStmt(decisionModel));

        return new MethodCallExpr(METHOD_DECISION)
                .addArgument(namespace)
                .addArgument(model)
                .addArgument(decision)
                .addArgument(lambda);
    }
 
Example 17
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleFlowGroup(RuleSetNode.RuleType ruleType) {
    // build supplier for rule runtime
    BlockStmt actionBody = new BlockStmt();
    LambdaExpr lambda = new LambdaExpr(new Parameter(new UnknownType(), "()"), actionBody);

    MethodCallExpr ruleRuntimeBuilder = new MethodCallExpr(
            new MethodCallExpr(new NameExpr("app"), "ruleUnits"), "ruleRuntimeBuilder");
    MethodCallExpr ruleRuntimeSupplier = new MethodCallExpr(
            ruleRuntimeBuilder, "newKieSession",
            NodeList.nodeList(new StringLiteralExpr("defaultStatelessKieSession"), new NameExpr("app.config().rule()")));
    actionBody.addStatement(new ReturnStmt(ruleRuntimeSupplier));

    return new MethodCallExpr("ruleFlowGroup")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(lambda);

}
 
Example 18
Source Project: kogito-runtimes   Source File: ProcessVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void visitHeader(WorkflowProcess process, BlockStmt body) {
    Map<String, Object> metaData = getMetaData(process.getMetaData());
    Set<String> imports = ((org.jbpm.process.core.Process) process).getImports();
    Map<String, String> globals = ((org.jbpm.process.core.Process) process).getGlobals();
    if ((imports != null && !imports.isEmpty()) || (globals != null && globals.size() > 0) || !metaData.isEmpty()) {
        if (imports != null) {
            for (String s : imports) {
                body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_IMPORTS, new StringLiteralExpr(s)));
            }
        }
        if (globals != null) {
            for (Map.Entry<String, String> global : globals.entrySet()) {
                body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_GLOBAL, new StringLiteralExpr(global.getKey()), new StringLiteralExpr(global.getValue())));
            }
        }
    }
}
 
Example 19
Source Project: kogito-runtimes   Source File: ForEachNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(String factoryField, ForEachNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, ForEachNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "ForEach"));
    visitMetaData(node.getMetaData(), body, getNodeId(node));

    body.addStatement(getFactoryMethod(getNodeId(node), METHOD_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getCollectionExpression()))))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE, new StringLiteralExpr(node.getVariableName()),
                    new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
                            new StringLiteralExpr(node.getVariableType().getStringType())
                    ))));

    if (node.getOutputCollectionExpression() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getOutputCollectionExpression()))))
                .addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_VARIABLE, new StringLiteralExpr(node.getOutputVariableName()),
                        new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
                                new StringLiteralExpr(node.getOutputVariableType().getStringType())
                        ))));
    }
    // visit nodes
    visitNodes(getNodeId(node), node.getNodes(), body, ((VariableScope) node.getCompositeNode().getDefaultContext(VariableScope.VARIABLE_SCOPE)), metadata);
    body.addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_INCOMING_CONNECTIONS, new LongLiteralExpr(node.getLinkedIncomingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_OUTGOING_CONNECTIONS, new LongLiteralExpr(node.getLinkedOutgoingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
            .addStatement(getDoneMethod(getNodeId(node)));

}
 
Example 20
Source Project: dolphin   Source File: JavaparserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup(){
  CompilationUnit cu = new CompilationUnit();
  // set the package
  cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr("java.parser.test")));

  // create the type declaration
  ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "GeneratedClass");
  ASTHelper.addTypeDeclaration(cu, type);

  // create a method
  MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
  method.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
  ASTHelper.addMember(type, method);

  // add a parameter to the method
  Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 0), "args");
  param.setVarArgs(true);
  ASTHelper.addParameter(method, param);

  // add a body to the method
  BlockStmt block = new BlockStmt();
  method.setBody(block);

  // add a statement do the method body
  NameExpr clazz = new NameExpr("System");
  FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
  MethodCallExpr call = new MethodCallExpr(field, "println");
  ASTHelper.addArgument(call, new StringLiteralExpr("Hello World!"));
  ASTHelper.addStmt(block, call);

  unit = cu;
}
 
Example 21
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 22
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 23
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 24
Source Project: kogito-runtimes   Source File: RuleUnitMetaModel.java    License: Apache License 2.0 5 votes vote down vote up
public Statement extractIntoCollection(String sourceUnitVar, String targetProcessVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(sourceUnitVar);
    String localVarName = localVarName(v);
    blockStmt.addStatement(assignVar(v))
            .addStatement(new ExpressionStmt(
                    new MethodCallExpr(new NameExpr(localVarName), "subscribe")
                            .addArgument(new MethodCallExpr(
                                    new NameExpr(DataObserver.class.getCanonicalName()), "of")
                                                 .addArgument(parseExpression(targetProcessVar + "::add")))));
    return blockStmt;
}
 
Example 25
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 26
Source Project: kogito-runtimes   Source File: MessageProducerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

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

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
    } 
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 27
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 28
Source Project: kogito-runtimes   Source File: FaultNodeVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, FaultNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, FaultNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "Error"));
    if (node.getFaultVariable() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_FAULT_VARIABLE, new StringLiteralExpr(node.getFaultVariable())));
    }
    if (node.getFaultName() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_FAULT_NAME, new StringLiteralExpr(node.getFaultName())));
    }

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));

}
 
Example 29
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 30
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);
}