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

The following examples show how to use com.github.javaparser.ast.expr.NameExpr. 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: TestSmellDetector   Author: TestSmells   File: LazyTest.java    License: GNU General Public License v3.0 7 votes vote down vote up
/**
 * The purpose of this method is to identify the production class methods that are called from the test method
 * When the parser encounters a method call:
 * 1) the method is contained in the productionMethods list
 * or
 * 2) the code will check the 'scope' of the called method
 * A match is made if the scope is either:
 * equal to the name of the production class (as in the case of a static method) or
 * if the scope is a variable that has been declared to be of type of the production class (i.e. contained in the 'productionVariables' list).
 */
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        if (productionMethods.stream().anyMatch(i -> i.getNameAsString().equals(n.getNameAsString()) &&
                i.getParameters().size() == n.getArguments().size())) {
            calledProductionMethods.add(new MethodUsage(currentMethod.getNameAsString(), n.getNameAsString()));
        } else {
            if (n.getScope().isPresent()) {
                if (n.getScope().get() instanceof NameExpr) {
                    //checks if the scope of the method being called is either of production class (e.g. static method)
                    //or
                    ///if the scope matches a variable which, in turn, is of type of the production class
                    if (((NameExpr) n.getScope().get()).getNameAsString().equals(productionClassName) ||
                            productionVariables.contains(((NameExpr) n.getScope().get()).getNameAsString())) {
                        calledProductionMethods.add(new MethodUsage(currentMethod.getNameAsString(), n.getNameAsString()));
                    }
                }
            }
        }
    }
}
 
Example #2
Source Project: jeddict   Author: jeddict   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 #3
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessGenerator.java    License: 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 #4
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessGenerator.java    License: 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 #5
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public ObjectCreationExpr newInstance() {
    if (annotator != null) {
        return new ObjectCreationExpr()
                .setType(StaticProcessConfig.class.getCanonicalName())
                .addArgument(new MethodCallExpr(METHOD_EXTRACT_WORK_ITEM_HANDLER_CONFIG))
                .addArgument(new MethodCallExpr(METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG))
                .addArgument(new MethodCallExpr(METHOD_EXTRACT_UNIT_OF_WORK_MANAGER))
                .addArgument(new MethodCallExpr(METHOD_EXTRACT_JOBS_SERVICE));
    } else {
        return new ObjectCreationExpr()
                .setType(StaticProcessConfig.class.getCanonicalName())
                .addArgument(new NameExpr(VAR_DEFAULT_WORK_ITEM_HANDLER_CONFIG))
                .addArgument(new NameExpr(VAR_DEFAULT_PROCESS_EVENT_LISTENER_CONFIG))
                .addArgument(new NameExpr(VAR_DEFAULT_UNIT_OF_WORK_MANAGER))
                .addArgument(new NameExpr(VAR_DEFAULT_JOBS_SEVICE));
    }
}
 
Example #6
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private BlockStmt wrapBodyAddingExceptionLogging(BlockStmt body, String nameURL) {
    TryStmt ts = new TryStmt();
    ts.setTryBlock(body);
    CatchClause cc = new CatchClause();
    String exceptionName = "e";
    cc.setParameter(new Parameter().setName(exceptionName).setType(Exception.class));
    BlockStmt cb = new BlockStmt();
    cb.addStatement(parseStatement(
            String.format(
                    "SystemMetricsCollector.registerException(\"%s\", %s.getStackTrace()[0].toString());",
                    nameURL,
                    exceptionName)
    ));
    cb.addStatement(new ThrowStmt(new NameExpr(exceptionName)));
    cc.setBody(cb);
    ts.setCatchClauses(new NodeList<>(cc));
    return new BlockStmt(new NodeList<>(ts));
}
 
Example #7
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitInstanceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String canonicalName = ruleUnitDescription.getRuleUnitName();
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractRuleUnitInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, canonicalName)))
            .addConstructor(Modifier.Keyword.PUBLIC)
            .addParameter(RuleUnitGenerator.ruleUnitType(canonicalName), "unit")
            .addParameter(canonicalName, "value")
            .addParameter(KieSession.class.getCanonicalName(), "session")
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr("unit"),
                    new NameExpr("value"),
                    new NameExpr("session")
            )));
    classDecl.addMember(bindMethod());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example #8
Source Project: kogito-runtimes   Author: kiegroup   File: DecisionContainerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Statement> setupStatements() {
    return Collections.singletonList(
            new IfStmt(
                    new BinaryExpr(
                            new MethodCallExpr(new MethodCallExpr(null, "config"), "decision"),
                            new NullLiteralExpr(),
                            BinaryExpr.Operator.NOT_EQUALS
                    ),
                    new BlockStmt().addStatement(new ExpressionStmt(new MethodCallExpr(
                            new NameExpr("decisionModels"), "init", NodeList.nodeList(new ThisExpr())
                    ))),
                    null
            )
    );
}
 
Example #9
Source Project: kogito-runtimes   Author: kiegroup   File: LambdaSubProcessNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
protected Expression dotNotationToSetExpression(String dotNotation, String value) {
    String[] elements = dotNotation.split("\\.");
    Expression scope = new NameExpr(elements[0]);
    if (elements.length == 1) {
        return new AssignExpr(
                scope,
                new NameExpr(value),
                AssignExpr.Operator.ASSIGN);
    }
    for (int i = 1; i < elements.length - 1; i++) {
        scope = new MethodCallExpr()
                .setScope(scope)
                .setName("get" + StringUtils.capitalize(elements[i]));
    }

    return new MethodCallExpr()
            .setScope(scope)
            .setName("set" + StringUtils.capitalize(elements[elements.length - 1]))
            .addArgument(value);
}
 
Example #10
Source Project: kogito-runtimes   Author: kiegroup   File: LambdaSubProcessNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
protected Expression dotNotationToGetExpression(String dotNotation) {
    String[] elements = dotNotation.split("\\.");
    Expression scope = new NameExpr(elements[0]);

    if (elements.length == 1) {
        return scope;
    }

    for (int i = 1; i < elements.length; i++) {
        scope = new MethodCallExpr()
                .setScope(scope)
                .setName("get" + StringUtils.capitalize(elements[i]));
    }

    return scope;
}
 
Example #11
Source Project: kogito-runtimes   Author: kiegroup   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 #12
Source Project: kogito-runtimes   Author: kiegroup   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 #13
Source Project: kogito-runtimes   Author: kiegroup   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: TestSmellDetector   Author: TestSmells   File: PrintStatement.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        // if the name of a method being called is 'print' or 'println' or 'printf' or 'write'
        if (n.getNameAsString().equals("print") || n.getNameAsString().equals("println") || n.getNameAsString().equals("printf") || n.getNameAsString().equals("write")) {
            //check the scope of the method & proceed only if the scope is "out"
            if ((n.getScope().isPresent() &&
                    n.getScope().get() instanceof FieldAccessExpr &&
                    (((FieldAccessExpr) n.getScope().get())).getNameAsString().equals("out"))) {

                FieldAccessExpr f1 = (((FieldAccessExpr) n.getScope().get()));

                //check the scope of the field & proceed only if the scope is "System"
                if ((f1.getScope() != null &&
                        f1.getScope() instanceof NameExpr &&
                        ((NameExpr) f1.getScope()).getNameAsString().equals("System"))) {
                    //a print statement exists in the method body
                    printCount++;
                }
            }

        }
    }
}
 
Example #15
Source Project: TestSmellDetector   Author: TestSmells   File: SleepyTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null) {
        // if the name of a method being called is 'sleep'
        if (n.getNameAsString().equals("sleep")) {
            //check the scope of the method
            if ((n.getScope().isPresent() && n.getScope().get() instanceof NameExpr)) {
                //proceed only if the scope is "Thread"
                if ((((NameExpr) n.getScope().get()).getNameAsString().equals("Thread"))) {
                    sleepCount++;
                }
            }

        }
    }
}
 
Example #16
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 6 votes vote down vote up
/**
   * visitor for field access expressions
   *   - convert ((...type_Type)jcasType).casFeatCode_XXXX to _FI_xxx
   * @param n -
   * @param ignore -
   */
  @Override
  public void visit(FieldAccessExpr n, Object ignore) {
    Expression e;
    Optional<Expression> oe;
    String nname = n.getNameAsString();
    
    if (get_set_method != null) {  
      if (nname.startsWith("casFeatCode_") &&
          ((oe = n.getScope()).isPresent()) &&
          ((e = getUnenclosedExpr(oe.get())) instanceof CastExpr) &&
          ("jcasType".equals(getName(((CastExpr)e).getExpression())))) {
        String featureName = nname.substring("casFeatCode_".length());
//        replaceInParent(n, new NameExpr("_FI_" + featureName)); // repl last in List<Expression> (args)
        
        MethodCallExpr getint = new MethodCallExpr(null, "wrapGetIntCatchException");
        getint.addArgument(new NameExpr("_FH_" + featureName));
        replaceInParent(n, getint);
        
        return;
      } else if (nname.startsWith("casFeatCode_")) {
        reportMigrateFailed("Found field casFeatCode_ ... without a previous cast expr using jcasType");
      }
    }
    super.visit(n,  ignore);      
  }
 
Example #17
Source Project: kogito-runtimes   Author: kiegroup   File: ConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodCallExpr callMerge(String configsName, Class<?> configToListenersScope, String configToListenersIdentifier, String listenersName) {
    return new MethodCallExpr(null, "merge", NodeList.nodeList(
            new NameExpr(configsName),
            new MethodReferenceExpr(
                    new TypeExpr(new ClassOrInterfaceType(null, configToListenersScope.getCanonicalName())),
                    null,
                    configToListenersIdentifier
            ),
            new NameExpr(listenersName)
    ));
}
 
Example #18
Source Project: kogito-runtimes   Author: kiegroup   File: CDIDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Expression getMultiInstance(String fieldName) {
    return new MethodCallExpr(
            new MethodCallExpr(new NameExpr("java.util.stream.StreamSupport"), "stream", NodeList.nodeList(
                    new MethodCallExpr(new NameExpr(fieldName), "spliterator"),
                    new BooleanLiteralExpr(false)
            )),
            "collect",
            NodeList.nodeList(
                    new MethodCallExpr(new NameExpr("java.util.stream.Collectors"), "toList")
            )
    );
}
 
Example #19
Source Project: JCTools   Author: JCTools   File: JavaParsingAtomicQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(FieldAccessExpr n, Void arg) {
    super.visit(n, arg);
    if (n.getScope() instanceof NameExpr) {
        NameExpr name = (NameExpr) n.getScope();
        name.setName(translateQueueName(name.getNameAsString()));
    }
}
 
Example #20
Source Project: kogito-runtimes   Author: kiegroup   File: SpringDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Expression getMultiInstance(String fieldName) {
    return new ConditionalExpr(
            new BinaryExpr(new NameExpr(fieldName), new NullLiteralExpr(), BinaryExpr.Operator.NOT_EQUALS),
            new NameExpr(fieldName),
            new MethodCallExpr(new TypeExpr(new ClassOrInterfaceType(null, Collections.class.getCanonicalName())), "emptyList")
    );
}
 
Example #21
Source Project: kogito-runtimes   Author: kiegroup   File: CodegenUtils.java    License: 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 #22
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example #23
Source Project: kogito-runtimes   Author: kiegroup   File: MessageProducerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType())));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
    });
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class).filter(fd -> fd.getVariable(0).getNameAsString().equals("emitter")).get();
        annotator.withInjection(emitterField);
        annotator.withOutgoingMessage(emitterField, trigger.getName());
        emitterField.getVariable(0).setType(annotator.emitterType("String"));
        
        MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methos in MessageProducerTemplate"));
        BlockStmt body = new BlockStmt();
        MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send");
        annotator.withMessageProducer(sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall").addArgument(new NameExpr("pi")).addArgument(new NameExpr(EVENT_DATA_VAR)));
        body.addStatement(sendMethodCall);
        produceMethod.setBody(body);

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
    } 
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example #24
Source Project: kogito-runtimes   Author: kiegroup   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 #25
Source Project: CodeDefenders   Author: CodeDefenders   File: MutationVisitor.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Node visit(NameExpr stmt, Void args) {
    if (!isValid) {
        return stmt;
    }
    super.visit(stmt, args);
    if (stmt.getNameAsString().equals("System")) {
        this.message = ValidationMessage.MUTATION_SYSTEM_USE;
        isValid = false;
    }
    return stmt;
}
 
Example #26
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessGenerator.java    License: 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 #27
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: 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 #28
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: 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 #29
Source Project: kogito-runtimes   Author: kiegroup   File: AbstractResourceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void interpolateUserTaskNameExp(NameExpr name, UserTaskModelMetaData userTask) {
    String identifier = name.getNameAsString();

    name.setName(identifier.replace("$TaskInput$", userTask.getInputMoodelClassSimpleName()));

    identifier = name.getNameAsString();
    name.setName(identifier.replace("$TaskOutput$", userTask.getOutputMoodelClassSimpleName()));
}
 
Example #30
Source Project: kogito-runtimes   Author: kiegroup   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));
    });
}