com.github.javaparser.ast.expr.StringLiteralExpr Java Examples

The following examples show how to use com.github.javaparser.ast.expr.StringLiteralExpr. 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: StateNodeVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<MethodCallExpr> visitCustomFields(StateNode node, VariableScope variableScope) {
    if (node.getConstraints() == null) {
        return Stream.empty();
    }
    return node.getConstraints()
            .entrySet()
            .stream()
            .map((e -> getFactoryMethod(getNodeId(node), METHOD_CONSTRAINT,
                    getOrNullExpr(e.getKey().getConnectionId()),
                    new LongLiteralExpr(e.getKey().getNodeId()),
                    new StringLiteralExpr(e.getKey().getToType()),
                    new StringLiteralExpr(e.getValue().getDialect()),
                    new StringLiteralExpr(StringEscapeUtils.escapeJava(e.getValue().getConstraint())),
                    new IntegerLiteralExpr(e.getValue().getPriority()))));
}
 
Example #2
Source File: WorkItemNodeVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private Expression getParameterExpr(String type, String value) {
    ParamType pType = ParamType.fromString(type);
    if (pType == null) {
        return new StringLiteralExpr(value);
    }
    switch (pType) {
        case BOOLEAN:
            return new BooleanLiteralExpr(Boolean.parseBoolean(value));
        case FLOAT:
            return new MethodCallExpr()
                    .setScope(new NameExpr(Float.class.getName()))
                    .setName("parseFloat")
                    .addArgument(new StringLiteralExpr(value));
        case INTEGER:
            return new IntegerLiteralExpr(Integer.parseInt(value));
        default:
            return new StringLiteralExpr(value);
    }
}
 
Example #3
Source File: AnnotatedMember.java    From jeddict with Apache License 2.0 6 votes vote down vote up
static Optional<String> getStringAttribute(AnnotationExpr annotationExpr, String attributeName) {
    Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName);
    if (expressionOpt.isPresent()) {
        Expression expression = expressionOpt.get();
        if (expression.isStringLiteralExpr()) {
            return expression.toStringLiteralExpr()
                    .map(StringLiteralExpr::getValue);
        } else if (expression.isNameExpr()) {
            return expression.toNameExpr()
                    .map(NameExpr::getNameAsString);
        } else if (expression.isIntegerLiteralExpr()) {
            return expression.toIntegerLiteralExpr()
                    .map(IntegerLiteralExpr::asInt)
                    .map(String::valueOf);
        } else if (expression.isFieldAccessExpr() || expression.isBinaryExpr()) {
            return expressionOpt
                    .map(Expression::toString);
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return Optional.empty();
}
 
Example #4
Source File: AnnotatedMember.java    From jeddict with Apache License 2.0 6 votes vote down vote up
static List<String> getStringAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isStringLiteralExpr()) {
            values.add(expression.asStringLiteralExpr().getValue());
        } else if (expression.isArrayInitializerExpr()) {
            List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes();
            for (Node node : nodes) {
                if (node instanceof StringLiteralExpr) {
                    values.add(((StringLiteralExpr) node).getValue());
                } else {
                    values.add(node.toString());
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example #5
Source File: WorkItemNodeVisitor.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) {
    Work work = node.getWork();
    String workName = node.getWork().getName();

    if (workName.equals("Service Task")) {
        ServiceTaskDescriptor d = new ServiceTaskDescriptor(node, contextClassLoader);
        String mangledName = d.mangledName();
        CompilationUnit generatedHandler = d.generateHandlerClassForService();
        metadata.getGeneratedHandlers().put(mangledName, generatedHandler);
        workName = mangledName;
    }

    body.addStatement(getAssignedFactoryMethod(factoryField, WorkItemNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, work.getName()))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_WORK_NAME, new StringLiteralExpr(workName)));

    addWorkItemParameters(work, body, getNodeId(node));
    addNodeMappings(node, body, getNodeId(node));

    body.addStatement(getDoneMethod(getNodeId(node)));

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

    metadata.getWorkItems().add(workName);
}
 
Example #6
Source File: ConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateAddonsMethod() {
    MethodCallExpr asListOfAddons = new MethodCallExpr(new NameExpr("java.util.Arrays"), "asList");
    try {
        Enumeration<URL> urls = classLoader.getResources("META-INF/kogito.addon");
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String addon = StringUtils.readFileAsString(new InputStreamReader(url.openStream()));
            asListOfAddons.addArgument(new StringLiteralExpr(addon));
        }
    } catch (IOException e) {
        LOGGER.warn("Unexpected exception during loading of kogito.addon files", e);
    }

    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            newObject(Addons.class, asListOfAddons)
    ));

    return method(Keyword.PUBLIC, Addons.class, "addons", body);
}
 
Example #7
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 #8
Source File: IncrementalRuleCodegen.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void generateSessionUnits( List<org.kie.kogito.codegen.GeneratedFile> generatedFiles ) {
    for (KieBaseModel kBaseModel : kieModuleModel.getKieBaseModels().values()) {
        for (String sessionName : kBaseModel.getKieSessionModels().keySet()) {
            CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) );
            ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get();
            annotator.withNamedSingletonComponent(template, "$SessionName$");
            template.setName( "SessionRuleUnit_" + sessionName );

            template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd));

            template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) );
            generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile(
                    org.kie.kogito.codegen.GeneratedFile.Type.RULE,
                    "org/drools/project/model/SessionRuleUnit_" + sessionName + ".java",
                    log( cu.toString() ) ));
        }
    }
}
 
Example #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: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private String getReturnType(ClassOrInterfaceDeclaration clazz) {
    MethodDeclaration toResultMethod = clazz.getMethodsByName("toResult").get(0);
    String returnType;
    if (query.getBindings().size() == 1) {
        Map.Entry<String, Class<?>> binding = query.getBindings().entrySet().iterator().next();
        String name = binding.getKey();
        returnType = binding.getValue().getCanonicalName();

        Statement statement = toResultMethod
                .getBody()
                .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
                .getStatement(0);

        statement.findFirst(CastExpr.class).orElseThrow(() -> new NoSuchElementException("CastExpr not found in template.")).setType(returnType);
        statement.findFirst(StringLiteralExpr.class).orElseThrow(() -> new NoSuchElementException("StringLiteralExpr not found in template.")).setString(name);
    } else {
        returnType = "Result";
        generateResultClass(clazz, toResultMethod);
    }

    toResultMethod.setType(returnType);
    return returnType;
}
 
Example #11
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 #12
Source File: RuleSetNodeVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleUnit(VariableScope variableScope, ProcessMetaData metadata, RuleSetNode ruleSetNode, String nodeName, RuleSetNode.RuleType ruleType) {
    String unitName = ruleType.getName();
    ProcessContextMetaModel processContext = new ProcessContextMetaModel(variableScope, contextClassLoader);
    RuleUnitDescription description;

    try {
        Class<?> unitClass = loadUnitClass(nodeName, unitName, metadata.getPackageName());
        description = new ReflectiveRuleUnitDescription(null, (Class<? extends RuleUnitData>) unitClass);
    } catch (ClassNotFoundException e) {
        logger.warn("Rule task \"{}\": cannot load class {}. " +
                "The unit data object will be generated.", nodeName, unitName);

        GeneratedRuleUnitDescription d = generateRuleUnitDescription(unitName, processContext);
        RuleUnitComponentFactoryImpl impl = (RuleUnitComponentFactoryImpl) RuleUnitComponentFactory.get();
        impl.registerRuleUnitDescription(d);
        description = d;
    }

    RuleUnitHandler handler = new RuleUnitHandler(description, processContext, ruleSetNode, assignableChecker);
    Expression ruleUnitFactory = handler.invoke();

    return new MethodCallExpr("ruleUnit")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(ruleUnitFactory);

}
 
Example #13
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 #14
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 #15
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 #16
Source File: ProcessContextMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public MethodCallExpr setVariable(String procVar) {
    Variable v = variableScope.findVariable(procVar);
    if (v == null) {
        throw new IllegalArgumentException("No such variable " + procVar);
    }
    MethodCallExpr setter = new MethodCallExpr().setScope(new NameExpr(kcontext))
            .setName("setVariable")
            .addArgument(new StringLiteralExpr(procVar));
    return setter;
}
 
Example #17
Source File: SplitNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, Split node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, SplitFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "Split"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_TYPE, new IntegerLiteralExpr(node.getType())));

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

    if (node.getType() == Split.TYPE_OR || node.getType() == Split.TYPE_XOR) {
        for (Entry<ConnectionRef, Constraint> entry : node.getConstraints().entrySet()) {
            if (entry.getValue() != null) {
                BlockStmt actionBody = new BlockStmt();
                LambdaExpr lambda = new LambdaExpr(
                        new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
                        actionBody
                );

                for (Variable v : variableScope.getVariables()) {
                    actionBody.addStatement(makeAssignment(v));
                }
                BlockStmt constraintBody = new BlockStmt();
                constraintBody.addStatement(entry.getValue().getConstraint());

                actionBody.addStatement(constraintBody);

                body.addStatement(getFactoryMethod(getNodeId(node), METHOD_CONSTRAINT,
                        new LongLiteralExpr(entry.getKey().getNodeId()),
                        new StringLiteralExpr(getOrDefault(entry.getKey().getConnectionId(), "")),
                        new StringLiteralExpr(entry.getKey().getToType()),
                        new StringLiteralExpr(entry.getValue().getDialect()),
                        lambda,
                        new IntegerLiteralExpr(entry.getValue().getPriority())));
            }
        }
    }
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example #18
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 #19
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 #20
Source File: ProcessContextMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Expression getVariable(String procVar) {
    String interpolatedVar = extractVariableFromExpression(procVar);
    Variable v = variableScope.findVariable(interpolatedVar);
    if (v == null) {
        throw new IllegalArgumentException("No such variable " + procVar);
    }
    MethodCallExpr getter = new MethodCallExpr().setScope(new NameExpr(kcontext))
            .setName("getVariable")
            .addArgument(new StringLiteralExpr(interpolatedVar));
    CastExpr castExpr = new CastExpr()
            .setExpression(new EnclosedExpr(getter))
            .setType(v.getType().getStringType());
    return castExpr;
}
 
Example #21
Source File: WorkItemNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void addWorkItemParameters(Work work, BlockStmt body, String variableName) {
    for (Entry<String, Object> entry : work.getParameters().entrySet()) {
        if (entry.getValue() == null) {
            continue; // interfaceImplementationRef ?
        }
        String paramType = null;
        if(work.getParameterDefinition(entry.getKey()) != null) {
            paramType = work.getParameterDefinition(entry.getKey()).getType().getStringType();
        }
        body.addStatement(getFactoryMethod(variableName, METHOD_WORK_PARAMETER, new StringLiteralExpr(entry.getKey()), getParameterExpr(paramType, entry.getValue().toString())));
    }
}
 
Example #22
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
private String createMemberParamValue(AnnotationExpr a) {
    Expression memberValue = a.asSingleMemberAnnotationExpr().getMemberValue();
    if (memberValue.getClass().isAssignableFrom(StringLiteralExpr.class))
        return memberValue.asStringLiteralExpr().asString();

    if (memberValue.getClass().isAssignableFrom(NameExpr.class))
        return memberValue.asNameExpr().getNameAsString();

    throw new IllegalArgumentException(String.format("Javadoc param type (%s) not supported.", memberValue.toString()));
}
 
Example #23
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 #24
Source File: LambdaSubProcessNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private BlockStmt unbind(VariableScope variableScope, SubProcessNode subProcessNode) {
    BlockStmt stmts = new BlockStmt();

    for (Map.Entry<String, String> e : subProcessNode.getOutMappings().entrySet()) {

        // check if given mapping is an expression
        Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(e.getValue());
        if (matcher.find()) {

            String expression = matcher.group(1);
            String topLevelVariable = expression.split("\\.")[0];
            Map<String, String> dataOutputs = (Map<String, String>) subProcessNode.getMetaData("BPMN.OutputTypes");
            Variable variable = new Variable();
            variable.setName(topLevelVariable);
            variable.setType(new ObjectDataType(dataOutputs.get(e.getKey())));

            stmts.addStatement(makeAssignment(variableScope.findVariable(topLevelVariable)));
            stmts.addStatement(makeAssignmentFromModel(variable, e.getKey()));

            stmts.addStatement(dotNotationToSetExpression(expression, e.getKey()));

            stmts.addStatement(new MethodCallExpr()
                    .setScope(new NameExpr(KCONTEXT_VAR))
                    .setName("setVariable")
                    .addArgument(new StringLiteralExpr(topLevelVariable))
                    .addArgument(topLevelVariable));
        } else {

            stmts.addStatement(makeAssignmentFromModel(variableScope.findVariable(e.getValue()), e.getKey()));
            stmts.addStatement(new MethodCallExpr()
                    .setScope(new NameExpr(KCONTEXT_VAR))
                    .setName("setVariable")
                    .addArgument(new StringLiteralExpr(e.getValue()))
                    .addArgument(e.getKey()));
        }

    }

    return stmts;
}
 
Example #25
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addUserTaskAnnotation(ClassOrInterfaceDeclaration modelClass) {
    String taskName = (String) humanTaskNode.getWork().getParameter(TASK_NAME);
    if (taskName == null)
        taskName = humanTaskNode.getName();
    modelClass.addAndGetAnnotation(UserTask.class).addPair("taskName", new StringLiteralExpr(taskName)).addPair("processName", new StringLiteralExpr(StringUtils.capitalize(ProcessToExecModelGenerator
                                                                                                                                                                                                       .extractProcessId(processId))));
}
 
Example #26
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())));
        }
    }
}
 
Example #27
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void visitConnection(String factoryField, Connection connection, BlockStmt body) {
    // if the connection is a hidden one (compensations), don't dump
    Object hidden = ((ConnectionImpl) connection).getMetaData(HIDDEN);
    if (hidden != null && ((Boolean) hidden)) {
        return;
    }

    body.addStatement(getFactoryMethod(factoryField, "connection", new LongLiteralExpr(connection.getFrom().getId()),
            new LongLiteralExpr(connection.getTo().getId()),
            new StringLiteralExpr(getOrDefault((String) connection.getMetaData().get("UniqueId"), ""))));
}
 
Example #28
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Statement makeAssignment(String targetLocalVariable, Variable processVariable) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(processVariable.getType().getStringType());
    // `type` `name` = (`type`) `kcontext.getVariable
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, targetLocalVariable),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr(KCONTEXT_VAR),
                            "getVariable")
                            .addArgument(new StringLiteralExpr(targetLocalVariable))),
            AssignExpr.Operator.ASSIGN);
    return new ExpressionStmt(assignExpr);
}
 
Example #29
Source File: A_Nodes.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Test
public void calculatesTypeNames() throws IOException, ParseException {
    CompilationUnit compilationUnit = JavaParser.parse(
            FileLoader.getFile("de/is24/javaparser/TypeNameTestClass.java"));

    compilationUnit.accept(new VoidVisitorAdapter<Void>() {
        @Override
        public void visit(StringLiteralExpr n, Void arg) {
            assertThat("Name of anonymous class is invalid!", Nodes.getTypeName(n), is(n.getValue()));
        }
    }, null);
}
 
Example #30
Source File: ProcessVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void visitVariableScope(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(FACTORY_FIELD_NAME, METHOD_VARIABLE, new StringLiteralExpr(variable.getName()), variableValue, new StringLiteralExpr(Variable.VARIABLE_TAGS), tags != null ? new StringLiteralExpr(tags) : new NullLiteralExpr()));
        }
    }
}