Java源码示例:com.github.javaparser.ast.stmt.ReturnStmt

示例1
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);
}
 
示例2
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;
}
 
示例3
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;
}
 
示例4
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;
}
 
示例5
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);
}
 
示例6
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);
}
 
示例7
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);
}
 
示例8
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);
    }
 
示例9
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);

}
 
示例10
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;
}
 
示例11
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);

}
 
示例12
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());
}
 
示例13
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;
}
 
示例14
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);
}
 
示例15
@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;
}
 
示例16
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);
}
 
示例17
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));
    }
}
 
示例18
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));
    });
}
 
示例19
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));
}
 
示例20
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);
}
 
示例21
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);
}
 
示例22
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);
}
 
示例23
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);
}
 
示例24
public MethodDeclaration factoryMethod() {
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType( sectionClassName )
            .setName(methodName)
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new NameExpr(methodName))));
}
 
示例25
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
    );
}
 
示例26
@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(";");
}
 
示例27
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;
}
 
示例28
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
  }
}
 
示例29
@Override
public ClassOrInterfaceDeclaration classDeclaration() {

    NodeList<BodyDeclaration<?>> declarations = new NodeList<>();

    // declare field `application`
    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(applicationFieldDeclaration);

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

    // declare field `ruleRuntimeBuilder`
    FieldDeclaration kieRuntimeFieldDeclaration = new FieldDeclaration();
    kieRuntimeFieldDeclaration
            .addVariable(new VariableDeclarator( new ClassOrInterfaceType(null, KieRuntimeBuilder.class.getCanonicalName()), "ruleRuntimeBuilder")
            .setInitializer(new ObjectCreationExpr().setType(ProjectSourceClass.PROJECT_RUNTIME_CLASS)))
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(kieRuntimeFieldDeclaration);

    // declare method ruleRuntimeBuilder()
    MethodDeclaration methodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("ruleRuntimeBuilder")
            .setType(KieRuntimeBuilder.class.getCanonicalName())
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new FieldAccessExpr(new ThisExpr(), "ruleRuntimeBuilder"))));
    declarations.add(methodDeclaration);

    declarations.addAll(factoryMethods);
    declarations.add(genericFactoryById());

    ClassOrInterfaceDeclaration cls = super.classDeclaration()
            .setMembers(declarations);

    cls.getMembers().sort(new BodyDeclarationComparator());

    return cls;
}
 
示例30
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();
}