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

The following examples show how to use com.github.javaparser.ast.expr.StringLiteralExpr. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kogito-runtimes   Source File: ConfigGenerator.java    License: 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 2
Source Project: kogito-runtimes   Source File: IncrementalRuleCodegen.java    License: 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 3
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: 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 4
Source Project: kogito-runtimes   Source File: StateNodeVisitor.java    License: 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 5
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 6
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 7
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 8
Source Project: kogito-runtimes   Source File: RuleSetNodeVisitor.java    License: 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 9
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 10
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 11
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 12
Source Project: kogito-runtimes   Source File: WorkItemNodeVisitor.java    License: 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 13
Source Project: kogito-runtimes   Source File: WorkItemNodeVisitor.java    License: 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 14
Source Project: jeddict   Source File: AnnotatedMember.java    License: 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 15
Source Project: jeddict   Source File: AnnotatedMember.java    License: 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 16
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey))
            )
    ));
    return node;
}
 
Example 17
@Override
public <T extends NodeWithAnnotations<?>> T withConfigInjection(T node, String configKey, String defaultValue) {
    node.addAnnotation(new NormalAnnotationExpr(
            new Name("org.eclipse.microprofile.config.inject.ConfigProperty"),
            NodeList.nodeList(
                    new MemberValuePair("name", new StringLiteralExpr(configKey)),
                    new MemberValuePair("defaultValue", new StringLiteralExpr(defaultValue))
            )
    ));
    return node;
}
 
Example 18
/**
 * Annotates given node with set of roles to enforce security
 *
 * @param node  node to be annotated
 * @param roles roles that are allowed
 */
default <T extends NodeWithAnnotations<?>> T withSecurityRoles(T node, String[] roles) {
    if (roles != null && roles.length > 0) {
        List<Expression> rolesExpr = new ArrayList<>();

        for (String role : roles) {
            rolesExpr.add(new StringLiteralExpr(role.trim()));
        }

        node.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.annotation.security.RolesAllowed"), new ArrayInitializerExpr(NodeList.nodeList(rolesExpr))));
    }
    return node;
}
 
Example 19
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 20
public void addProcessToApplication(ProcessGenerator r) {
    ObjectCreationExpr newProcess = new ObjectCreationExpr()
            .setType(r.targetCanonicalName())
            .addArgument("application");
    IfStmt byProcessId = new IfStmt(new MethodCallExpr(new StringLiteralExpr(r.processId()), "equals", NodeList.nodeList(new NameExpr("processId"))),
                                    new ReturnStmt(new MethodCallExpr(
                                            newProcess,
                                            "configure")),
                                    null);

    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(byProcessId);
}
 
Example 21
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
    byProcessIdMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new NullLiteralExpr()));

    NodeList<Expression> processIds = NodeList.nodeList(processes.stream().map(p -> new StringLiteralExpr(p.processId())).collect(Collectors.toList()));
    processesMethodDeclaration
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(Arrays.class.getCanonicalName()), "asList", processIds)));

    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    applicationDeclarations.add( applicationFieldDeclaration );

    ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration("Processes")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter( "Application", "application" )
            .setBody( new BlockStmt().addStatement( "this.application = application;" ) );
    applicationDeclarations.add( constructorDeclaration );

    ClassOrInterfaceDeclaration cls = super.classDeclaration().setMembers(applicationDeclarations);
    cls.getMembers().sort(new BodyDeclarationComparator());
    
    return cls;
}
 
Example 22
Source Project: kogito-runtimes   Source File: AbstractResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void interpolateStrings(StringLiteralExpr vv) {
    String s = vv.getValue();
    String documentation =
            process.getMetaData()
                    .getOrDefault("Documentation", processName).toString();
    String interpolated =
            s.replace("$name$", processName)
                    .replace("$id$", processId)
                    .replace("$documentation$", documentation);
    vv.setString(interpolated);
}
 
Example 23
Source Project: kogito-runtimes   Source File: AbstractResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void interpolateUserTaskStrings(StringLiteralExpr vv, UserTaskModelMetaData userTask) {
    String s = vv.getValue();

    String interpolated =
            s.replace("$taskname$", userTask.getName().replaceAll("\\s", "_"));
    vv.setString(interpolated);
}
 
Example 24
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/RestQueryTemplate.java"));
    cu.setPackageDeclaration(query.getNamespace());

    ClassOrInterfaceDeclaration clazz = cu
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    clazz.setName(targetCanonicalName);

    cu.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);

    FieldDeclaration ruleUnitDeclaration = clazz
            .getFieldByName("ruleUnit")
            .orElseThrow(() -> new NoSuchElementException("ClassOrInterfaceDeclaration doesn't contain a field named ruleUnit!"));
    setUnitGeneric(ruleUnitDeclaration.getElementType());
    if (annotator != null) {
        annotator.withInjection(ruleUnitDeclaration);
    }

    String returnType = getReturnType(clazz);
    generateConstructors(clazz);
    generateQueryMethods(cu, clazz, returnType);
    clazz.getMembers().sort(new BodyDeclarationComparator());
    return cu.toString();
}
 
Example 25
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
    ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
    clazz.addMember(resultClass);

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

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

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

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

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

        MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
        callExpr.addArgument(new StringLiteralExpr(name));
        resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
    });
}
 
Example 26
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void interpolateStrings(StringLiteralExpr vv) {
    String interpolated = vv.getValue()
            .replace("$name$", name)
            .replace("$endpointName$", endpointName)
            .replace("$queryName$", query.getName())
            .replace("$prometheusName$", endpointName);
    vv.setString(interpolated);
}
 
Example 27
private MethodDeclaration genericFactoryById() {
    ClassOrInterfaceType returnType = new ClassOrInterfaceType(null, RuleUnit.class.getCanonicalName())
            .setTypeArguments(new WildcardType());

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

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

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

    return new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setType(returnType)
            .setName("create")
            .addParameter(String.class, "fqcn")
            .setBody(new BlockStmt().addStatement(switchStmt));
}
 
Example 28
Source Project: kogito-runtimes   Source File: KieModuleModelMethod.java    License: Apache License 2.0 5 votes vote down vote up
private void setClockType() {
    NameExpr type = new NameExpr(kieSessionModel.getClockType().getClass().getCanonicalName());
    MethodCallExpr clockTypeEnum = new MethodCallExpr(type, "get", nodeList(new StringLiteralExpr(kieSessionModel.getClockType().getClockType())));
    stmt.addStatement(new MethodCallExpr(nameExpr, "setClockType", nodeList(clockTypeEnum)));

    confBlock.addStatement(new MethodCallExpr(confExpr, "setOption", nodeList(clockTypeEnum.clone())));
}
 
Example 29
private MethodCallExpr getReadResourceMethod( ClassOrInterfaceType applicationClass, DMNResource resource ) {
    String source = resource.getDmnModel().getResource().getSourcePath();
    Path sourcePath = Paths.get(source);
    if (resource.getPath().toString().endsWith( ".jar" )) {
        return new MethodCallExpr( new NameExpr( IoUtils.class.getCanonicalName() ), "readFileInJar" )
                .addArgument(new StringLiteralExpr(resource.getPath().toString()))
                .addArgument(new StringLiteralExpr(source));
    }
    Path relativizedPath = resource.getPath().relativize(sourcePath);
    String resourcePath = "/" + relativizedPath.toString().replace( File.separatorChar, '/');
    return new MethodCallExpr(new FieldAccessExpr(applicationClass.getNameAsExpression(), "class"), "getResourceAsStream")
            .addArgument(new StringLiteralExpr(resourcePath));
}
 
Example 30
Source Project: kogito-runtimes   Source File: DMNRestResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void interpolateStrings(StringLiteralExpr vv) {
    String s = vv.getValue();
    String documentation = "";
    String interpolated = s.replace("$name$", decisionName)
                           .replace("$nameURL$", nameURL)
                           .replace("$id$", decisionId)
                           .replace("$modelName$", dmnModel.getName())
                           .replace("$modelNamespace$", dmnModel.getNamespace())
                           .replace("$documentation$", documentation);
    vv.setString(interpolated);
}