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

The following examples show how to use com.github.javaparser.ast.stmt.BlockStmt. 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: ClassCodeAnalyser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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
Source File: TimerNodeVisitor.java    From kogito-runtimes with 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 #3
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 #4
Source File: RuleSetNodeVisitor.java    From kogito-runtimes with 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 #5
Source File: QueryEndpointGenerator.java    From kogito-runtimes with 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 #6
Source File: RuleSetNodeVisitor.java    From kogito-runtimes with 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 #7
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: ProcessVisitor.java    From kogito-runtimes with 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 #10
Source File: RuleConfigGenerator.java    From kogito-runtimes with 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 #11
Source File: ProcessGenerator.java    From kogito-runtimes with 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 #12
Source File: KieModuleModelMethod.java    From kogito-runtimes with 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 #13
Source File: DecisionContainerGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: ForEachNodeVisitor.java    From kogito-runtimes with 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 #15
Source File: ProcessInstanceGenerator.java    From kogito-runtimes with 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 #16
Source File: TriggerMetaData.java    From kogito-runtimes with 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 #17
Source File: CompositeContextNodeVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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 #18
Source File: FormTask.java    From enkan with 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 #19
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@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 #20
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final IfStmt n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("if (");
    n.getCondition().accept(this, arg);
    final boolean thenBlock = n.getThenStmt() instanceof BlockStmt;
    if (thenBlock) // block statement should start on the same line
        printer.print(") ");
    else {
        printer.println(")");
        printer.indent();
    }
    n.getThenStmt().accept(this, arg);
    if (!thenBlock)
        printer.unindent();
    if (n.getElseStmt().isPresent()) {
        if (thenBlock)
            printer.print(" ");
        else
            printer.println();
        final boolean elseIf = n.getElseStmt().orElse(null) instanceof IfStmt;
        final boolean elseBlock = n.getElseStmt().orElse(null) instanceof BlockStmt;
        if (elseIf || elseBlock) // put chained if and start of block statement on a same level
            printer.print("else ");
        else {
            printer.println("else");
            printer.indent();
        }
        if (n.getElseStmt().isPresent())
            n.getElseStmt().get().accept(this, arg);
        if (!(elseIf || elseBlock))
            printer.unindent();
    }
}
 
Example #21
Source File: EventNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, EventNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, EventNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "Event"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_EVENT_TYPE, new StringLiteralExpr(node.getType())));

    Variable variable = null;
    if (node.getVariableName() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE_NAME, new StringLiteralExpr(node.getVariableName())));
        variable = variableScope.findVariable(node.getVariableName());
    }

    if (EVENT_TYPE_SIGNAL.equals(node.getMetaData(EVENT_TYPE))) {
        metadata.getSignals().put(node.getType(), variable != null ? variable.getType().getStringType() : null);
    } else if (EVENT_TYPE_MESSAGE.equals(node.getMetaData(EVENT_TYPE))) {
        Map<String, Object> nodeMetaData = node.getMetaData();
        try {
            TriggerMetaData triggerMetaData = new TriggerMetaData((String) nodeMetaData.get(TRIGGER_REF),
                    (String) nodeMetaData.get(TRIGGER_TYPE),
                    (String) nodeMetaData.get(MESSAGE_TYPE),
                    node.getVariableName(),
                    String.valueOf(node.getId())).validate();
            metadata.getTriggers().add(triggerMetaData);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(
                    MessageFormat.format(
                            "Invalid parameters for event node \"{0}\": {1}",
                            node.getName(),
                            e.getMessage()), e);
        }
    }
    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example #22
Source File: StartNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void handleSignal(StartNode startNode, Map<String, Object> nodeMetaData, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    if (EVENT_TYPE_SIGNAL.equalsIgnoreCase((String) startNode.getMetaData(TRIGGER_TYPE))) {
        Variable variable = null;
        Map<String, String> variableMapping = startNode.getOutMappings();
        if (variableMapping != null && !variableMapping.isEmpty()) {
            Entry<String, String> varInfo = variableMapping.entrySet().iterator().next();

            body.addStatement(getFactoryMethod(getNodeId(startNode), METHOD_TRIGGER,
                    new StringLiteralExpr((String) nodeMetaData.get(MESSAGE_TYPE)),
                    getOrNullExpr(varInfo.getKey()),
                    getOrNullExpr(varInfo.getValue())));
            variable = variableScope.findVariable(varInfo.getKey());

            if (variable == null) {
                // check parent node container
                VariableScope vscope = (VariableScope) startNode.resolveContext(VariableScope.VARIABLE_SCOPE, varInfo.getKey());
                variable = vscope.findVariable(varInfo.getKey());
            }
        } else {
            body.addStatement(getFactoryMethod(getNodeId(startNode), METHOD_TRIGGER,
                    new StringLiteralExpr((String) nodeMetaData.get(MESSAGE_TYPE)),
                    new StringLiteralExpr(getOrDefault((String) nodeMetaData.get(TRIGGER_MAPPING), ""))));
        }
        metadata.getSignals().put((String) nodeMetaData.get(MESSAGE_TYPE), variable != null ? variable.getType().getStringType() : null);
    } else {
        String triggerMapping = (String) nodeMetaData.get(TRIGGER_MAPPING);
        body.addStatement(getFactoryMethod(getNodeId(startNode), METHOD_TRIGGER,
                new StringLiteralExpr((String) nodeMetaData.get(TRIGGER_REF)),
                new StringLiteralExpr(getOrDefault((String) nodeMetaData.get(TRIGGER_MAPPING), "")),
                new StringLiteralExpr(getOrDefault(startNode.getOutMapping(triggerMapping), ""))));
    }
}
 
Example #23
Source File: StartNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, StartNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, StartNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "Start"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_INTERRUPTING, new BooleanLiteralExpr(node.isInterrupting())));

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
    if (node.getTimer() != null) {
        Timer timer = node.getTimer();
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_TIMER, getOrNullExpr(timer.getDelay()),
                getOrNullExpr(timer.getPeriod()),
                getOrNullExpr(timer.getDate()),
                new IntegerLiteralExpr(node.getTimer().getTimeType())));

    } else if (node.getTriggers() != null && !node.getTriggers().isEmpty()) {
        Map<String, Object> nodeMetaData = node.getMetaData();
        metadata.getTriggers().add(new TriggerMetaData((String) nodeMetaData.get(TRIGGER_REF),
                (String) nodeMetaData.get(TRIGGER_TYPE),
                (String) nodeMetaData.get(MESSAGE_TYPE),
                (String) nodeMetaData.get(TRIGGER_MAPPING),
                String.valueOf(node.getId())).validate());

        handleSignal(node, nodeMetaData, body, variableScope, metadata);
    } else {
        // since there is start node without trigger then make sure it is startable
        metadata.setStartable(true);
    }

}
 
Example #24
Source File: BoundaryEventNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, BoundaryEventNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, BoundaryEventNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "BoundaryEvent"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_EVENT_TYPE, new StringLiteralExpr(node.getType())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_ATTACHED_TO, new StringLiteralExpr(node.getAttachedToNodeId())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_SCOPE, getOrNullExpr(node.getScope())));

    Variable variable = null;
    if (node.getVariableName() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE_NAME, new StringLiteralExpr(node.getVariableName())));
        variable = variableScope.findVariable(node.getVariableName());
    }

    if (EVENT_TYPE_SIGNAL.equals(node.getMetaData(EVENT_TYPE))) {
        metadata.getSignals().put(node.getType(), variable != null ? variable.getType().getStringType() : null);
    } else if (EVENT_TYPE_MESSAGE.equals(node.getMetaData(EVENT_TYPE))) {
        Map<String, Object> nodeMetaData = node.getMetaData();
        metadata.getTriggers().add(new TriggerMetaData((String) nodeMetaData.get(TRIGGER_REF),
                (String) nodeMetaData.get(TRIGGER_TYPE),
                (String) nodeMetaData.get(MESSAGE_TYPE),
                node.getVariableName(),
                String.valueOf(node.getId())).validate());
    }

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example #25
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public BlockStmt copyInto(String sourceVarName, String destVarName, ModelMetaData dest, Map<String, String> mapping) {
    BlockStmt blockStmt = new BlockStmt();

    for (Map.Entry<String, String> e : mapping.entrySet()) {
        String destField = variableScope.getTypes().get(e.getKey()).getSanitizedName();
        String sourceField = e.getValue();
        blockStmt.addStatement(
                dest.callSetter(destVarName, destField, dest.callGetter(sourceVarName, sourceField)));
    }

    return blockStmt;
}
 
Example #26
Source File: JavaparserTest.java    From dolphin with 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 #27
Source File: RuleUnitHandler.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private BlockStmt unbind(ProcessContextMetaModel variableScope, RuleSetNode node, RuleUnitDescription unitDescription) {
    RuleUnitMetaModel unit =
            new RuleUnitMetaModel(unitDescription, "unit", assignableChecker );

    BlockStmt actionBody = new BlockStmt();

    Map<String, String> mappings = getOutputMappings(variableScope, node);
    for (Map.Entry<String, String> e : mappings.entrySet()) {
        String unitVar = e.getKey();
        String procVar = e.getValue();
        boolean procVarIsCollection = variableScope.isCollectionType(procVar);
        boolean unitVarIsDataSource = unitDescription.hasDataSource(unitVar);
        if (procVarIsCollection && unitVarIsDataSource) {
            actionBody.addStatement(variableScope.assignVariable(procVar));
            actionBody.addStatement(
                    requireNonNull(procVar,
                                   String.format(
                                           "Null collection variable used as an output variable: %s. " +
                                                   "Initialize this variable to get the contents or the data source, " +
                                                   "or use a non-collection data type to extract one value.", procVar)));
            actionBody.addStatement(unit.extractIntoCollection(unitVar, procVar));
        } else if (procVarIsCollection /* && !unitVarIsDataSource */) {
            actionBody.addStatement(variableScope.assignVariable(procVar));
            actionBody.addStatement(unit.extractIntoScalar(unitVar, procVar));
        } else if (/* !procVarIsCollection && */ unitVarIsDataSource) {
            actionBody.addStatement(variableScope.assignVariable(procVar));
            actionBody.addStatement(unit.extractIntoScalar(unitVar, procVar));
        } else /* !procVarIsCollection && !unitVarIsDataSource */ {
            MethodCallExpr setterCall = variableScope.setVariable(procVar);
            actionBody.addStatement(
                    setterCall.addArgument(unit.get(unitVar)));
        }
    }

    return actionBody;
}
 
Example #28
Source File: AbstractCompositeNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected <U extends Node> void visitNodes(String factoryField, U[] nodes, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    for (U node : nodes) {
        AbstractNodeVisitor<U> visitor = (AbstractNodeVisitor<U>) nodesVisitors.get(node.getClass());
        if (visitor == null) {
            continue;
        }
        visitor.visitNode(factoryField, node, body, variableScope, metadata);
    }
}
 
Example #29
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected static LambdaExpr createLambdaExpr(String consequence, VariableScope scope) {
    BlockStmt conditionBody = new BlockStmt();
    List<Variable> variables = scope.getVariables();
    variables.stream()
            .map(ActionNodeVisitor::makeAssignment)
            .forEach(conditionBody::addStatement);

    conditionBody.addStatement(new ReturnStmt(new EnclosedExpr(new NameExpr(consequence))));

    return new LambdaExpr(
            new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
            conditionBody
    );
}
 
Example #30
Source File: CompositeContextNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void visitVariableScope(String contextNode, VariableScope variableScope, BlockStmt body, Set<String> visitedVariables) {
    if (variableScope != null && !variableScope.getVariables().isEmpty()) {
        for (Variable variable : variableScope.getVariables()) {
            if (!visitedVariables.add(variable.getName())) {
                continue;
            }
            String tags = (String) variable.getMetaData(Variable.VARIABLE_TAGS);
            ClassOrInterfaceType variableType = new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName());
            ObjectCreationExpr variableValue = new ObjectCreationExpr(null, variableType, new NodeList<>(new StringLiteralExpr(variable.getType().getStringType())));
            body.addStatement(getFactoryMethod(contextNode, METHOD_VARIABLE,
                    new StringLiteralExpr(variable.getName()), variableValue,
                    new StringLiteralExpr(Variable.VARIABLE_TAGS), (tags != null ? new StringLiteralExpr(tags) : new NullLiteralExpr())));
        }
    }
}