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

The following examples show how to use com.github.javaparser.ast.stmt.ReturnStmt. 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: 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 #2
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 #3
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 #4
Source File: DecisionConfigGenerator.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(CachedDecisionEventListenerConfig.class,
            callMerge(
                    VAR_DECISION_EVENT_LISTENER_CONFIG,
                    DecisionEventListenerConfig.class, "listeners",
                    VAR_DMN_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, DecisionEventListenerConfig.class, METHOD_MERGE_DECISION_EVENT_LISTENER_CONFIG,
            nodeList(
                    new Parameter().setType(genericType(Collection.class, DecisionEventListenerConfig.class)).setName(VAR_DECISION_EVENT_LISTENER_CONFIG),
                    new Parameter().setType(genericType(Collection.class, DMNRuntimeEventListener.class)).setName(VAR_DMN_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example #5
Source File: ProcessConfigGenerator.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(CachedProcessEventListenerConfig.class,
            callMerge(
                    VAR_PROCESS_EVENT_LISTENER_CONFIGS,
                    ProcessEventListenerConfig.class, "listeners",
                    VAR_PROCESS_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, ProcessEventListenerConfig.class)).setName(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, ProcessEventListener.class)).setName(VAR_PROCESS_EVENT_LISTENERS)
            ),
            body);
}
 
Example #6
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

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

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #7
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 #8
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 #9
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

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

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #10
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addMonitoringToMethod(MethodDeclaration method, String nameURL) {
    BlockStmt body = method.getBody().orElseThrow(() -> new NoSuchElementException("This method should be invoked only with concrete classes and not with abstract methods or interfaces."));
    NodeList<Statement> statements = body.getStatements();
    ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("Return statement not found: can't add monitoring to endpoint. Template was modified."));
    statements.addFirst(parseStatement("double startTime = System.nanoTime();"));
    statements.addBefore(parseStatement("double endTime = System.nanoTime();"), returnStmt);
    statements.addBefore(parseStatement("SystemMetricsCollector.registerElapsedTimeSampleMetrics(\"" + nameURL + "\", endTime - startTime);"), returnStmt);
    statements.addBefore(parseStatement(String.format("DMNResultMetricsBuilder.generateMetrics(result, \"%s\");", nameURL)), returnStmt);
}
 
Example #11
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 #12
Source File: AbstractApplicationSection.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public MethodDeclaration factoryMethod() {
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType( sectionClassName )
            .setName(methodName)
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new NameExpr(methodName))));
}
 
Example #13
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 ReturnStmt n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("return");
    if (n.getExpression().isPresent()) {
        printer.print(" ");
        n.getExpression().get().accept(this, arg);
    }
    printer.print(";");
}
 
Example #14
Source File: DecisionConfigGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_DECISION_EVENT_LISTENER_CONFIG, nodeList(
                    annotator.getMultiInstance(VAR_DECISION_EVENT_LISTENER_CONFIG),
                    annotator.getMultiInstance(VAR_DMN_RUNTIME_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, DecisionEventListenerConfig.class, METHOD_EXTRACT_DECISION_EVENT_LISTENER_CONFIG, body);
}
 
Example #15
Source File: FormTask.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration getterDeclaration(EntityField field) {
    MethodDeclaration decl = new MethodDeclaration(ModifierSet.PUBLIC,
            ASTHelper.createReferenceType(field.getType().getSimpleName(), 0),
            "get" + CaseConverter.pascalCase(field.getName()));
    BlockStmt body = new BlockStmt();
    body.setStmts(
            Collections.singletonList(
                    new ReturnStmt(
                            new FieldAccessExpr(new ThisExpr(), field.getName()))));
    decl.setBody(body);
    return decl;
}
 
Example #16
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addExceptionMetricsLogging(ClassOrInterfaceDeclaration template, String nameURL) {
    MethodDeclaration method = template.findFirst(MethodDeclaration.class, x -> "toResponse".equals(x.getNameAsString()))
            .orElseThrow(() -> new NoSuchElementException("Method toResponse not found, template has changed."));

    BlockStmt body = method.getBody().orElseThrow(() -> new NoSuchElementException("This method should be invoked only with concrete classes and not with abstract methods or interfaces."));
    ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("Check for null dmn result not found, can't add monitoring to endpoint."));
    NodeList<Statement> statements = body.getStatements();
    String methodArgumentName = method.getParameters().get(0).getNameAsString();
    statements.addBefore(parseStatement(String.format("SystemMetricsCollector.registerException(\"%s\", %s.getStackTrace()[0].toString());", nameURL, methodArgumentName)), returnStmt);
}
 
Example #17
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void addCastExpr(Statement stmt, Type castType) {
  ReturnStmt rstmt = (ReturnStmt) stmt;
  Optional<Expression> o_expr = rstmt.getExpression(); 
  Expression expr = o_expr.isPresent() ? o_expr.get() : null;
  CastExpr ce = new CastExpr(castType, expr);
  rstmt.setExpression(ce);  // removes the parent link from expr
  if (expr != null) {
    expr.setParentNode(ce); // restore it
  }
}
 
Example #18
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration createInstanceGenericMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

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

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #19
Source File: CodegenUtils.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static MethodDeclaration extractOptionalInjection(String type, String fieldName, String defaultMethod, DependencyInjectionAnnotator annotator) {
    BlockStmt body = new BlockStmt();
    MethodDeclaration extractMethod = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setName("extract_" + fieldName)
            .setType(type)
            .setBody(body);
    Expression condition = annotator.optionalInstanceExists(fieldName);
    IfStmt valueExists = new IfStmt(condition, new ReturnStmt(annotator.getOptionalInstance(fieldName)), new ReturnStmt(new NameExpr(defaultMethod)));
    body.addStatement(valueExists);
    return extractMethod;
}
 
Example #20
Source File: ProcessInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration bind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(new ReturnStmt(model.toMap("variables")));
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("bind")
            .addParameter(modelName, "variables")
            .setType(new ClassOrInterfaceType()
                             .setName("java.util.Map")
                             .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                               new ClassOrInterfaceType().setName("Object")))
            .setBody(body);

}
 
Example #21
Source File: PersistenceGenerator.java    From kogito-runtimes with 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 #22
Source File: RuleConfigGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_RULE_EVENT_LISTENER_CONFIG, NodeList.nodeList(
                    annotator.getMultiInstance(VAR_RULE_EVENT_LISTENER_CONFIGS),
                    annotator.getMultiInstance(VAR_AGENDA_EVENT_LISTENERS),
                    annotator.getMultiInstance(VAR_RULE_RUNTIME_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, RuleEventListenerConfig.class, METHOD_EXTRACT_RULE_EVENT_LISTENER_CONFIG, body);
}
 
Example #23
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: ProcessConfigGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateExtractEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG, NodeList.nodeList(
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    annotator.getMultiInstance(VAR_PROCESS_EVENT_LISTENERS)
            ))
    ));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG, body);
}
 
Example #26
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void addMonitoringToResource(CompilationUnit cu, MethodDeclaration[] methods, String nameURL) {
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));

    for (MethodDeclaration md : methods) {
        BlockStmt body = md.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"));
        NodeList<Statement> statements = body.getStatements();
        ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a return statement!"));
        statements.addFirst(parseStatement("double startTime = System.nanoTime();"));
        statements.addBefore(parseStatement("double endTime = System.nanoTime();"), returnStmt);
        statements.addBefore(parseStatement("SystemMetricsCollector.registerElapsedTimeSampleMetrics(\"" + nameURL + "\", endTime - startTime);"), returnStmt);
        md.setBody(wrapBodyAddingExceptionLogging(body, nameURL));
    }
}
 
Example #27
Source File: QueryEndpointGenerator.java    From kogito-runtimes with 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 #28
Source File: RuleUnitContainerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java"));
    clazz.setPackageDeclaration(this.packageName);

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

    template.setName(resourceClazzName);

    template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);
    template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods);

    interpolateInputType(template);

    if (useInjection()) {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
    } else {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(this::initializeApplicationField);
    }

    MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0);
    for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) {
        if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) {
            continue;
        }

        MethodDeclaration clonedMethod = dmnMethod.clone();
        String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName());
        clonedMethod.setName(name);
        MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!"));
        evaluateCall.setName(new SimpleName("evaluateDecisionService"));
        evaluateCall.addArgument(new StringLiteralExpr(ds.getName()));
        clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName())));
        ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!"));
        if (ds.getOutputDecision().size() == 1) {
            MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class,
                                                                      mce -> mce.getNameAsString().equals("extractContextIfSucceded"))
                                                           .orElseThrow(() -> new RuntimeException("Template was modified!"));
            rewrittenReturnExpr.setName("extractSingletonDSIfSucceded");
        }

        if (useMonitoring) {
            addMonitoringToMethod(clonedMethod, ds.getName());
        }

        template.addMember(clonedMethod);
    }

    if (useMonitoring) {
        addMonitoringImports(clazz);
        ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString()))
                .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed."));
        addExceptionMetricsLogging(exceptionClazz, nameURL);
        addMonitoringToMethod(dmnMethod, nameURL);
    }

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example #30
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(ReturnStmt n, Void arg) {
    out.println("ReturnStmt: " + (extended ? n : n.getExpression()));
    super.visit(n, arg);
}