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

The following examples show how to use com.github.javaparser.ast.expr.VariableDeclarationExpr. 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: MysteryGuest.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(VariableDeclarationExpr n, Void arg) {
    super.visit(n, arg);
    //Note: the null check limits the identification of variable types declared within the method body.
    // Removing it will check for variables declared at the class level.
    //TODO: to null check or not to null check???
    if (currentMethod != null) {
        for (String variableType : mysteryTypes) {
            //check if the type variable encountered is part of the mystery type collection
            if ((n.getVariable(0).getType().asString().equals(variableType))) {
                //check if the variable has been mocked
                for (AnnotationExpr annotation : n.getAnnotations()) {
                    if (annotation.getNameAsString().equals("Mock") || annotation.getNameAsString().equals("Spy"))
                        break;
                }
                // variable is not mocked, hence it's a smell
                mysteryCount++;
            }
        }
    }
}
 
Example #2
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void visit(final VariableDeclarationExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printAnnotations(n.getAnnotations(), false, arg);
    printModifiers(n.getModifiers());

    if (!n.getVariables().isEmpty()) {
        n.getMaximumCommonType().accept(this, arg);
    }
    printer.print(" ");

    for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
        final VariableDeclarator v = i.next();
        v.accept(this, arg);
        if (i.hasNext()) {
            printer.print(", ");
        }
    }
}
 
Example #3
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected AssignExpr getAssignedFactoryMethod(String factoryField, Class<?> typeClass, String variableName, String methodName, Expression... args) {
    ClassOrInterfaceType type = new ClassOrInterfaceType(null, typeClass.getCanonicalName());

    MethodCallExpr variableMethod = new MethodCallExpr(new NameExpr(factoryField), methodName);

    for (Expression arg : args) {
        variableMethod.addArgument(arg);
    }

    return new AssignExpr(
            new VariableDeclarationExpr(type, variableName),
            variableMethod,
            AssignExpr.Operator.ASSIGN);
}
 
Example #4
Source File: VariableDeclarationExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public VariableDeclarationExpr doMerge(VariableDeclarationExpr first, VariableDeclarationExpr second) {
  VariableDeclarationExpr vde = new VariableDeclarationExpr();

  vde.setType(mergeSingle(first.getType(),second.getType()));
  vde.setAnnotations(mergeCollections(first.getAnnotations(),second.getAnnotations()));
  vde.setModifiers(mergeModifiers(first.getModifiers(),second.getModifiers()));
  vde.setVars(mergeCollectionsInOrder(first.getVars(),second.getVars()));

  return vde;
}
 
Example #5
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 TryStmt n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("try ");
    if (!n.getResources().isEmpty()) {
        printer.print("(");
        Iterator<VariableDeclarationExpr> resources = n.getResources().iterator();
        boolean first = true;
        while (resources.hasNext()) {
            visit(resources.next(), arg);
            if (resources.hasNext()) {
                printer.print(";");
                printer.println();
                if (first) {
                    printer.indent();
                }
            }
            first = false;
        }
        if (n.getResources().size() > 1) {
            printer.unindent();
        }
        printer.print(") ");
    }
    if (n.getTryBlock().isPresent()) {
        n.getTryBlock().get().accept(this, arg);
    }
    for (final CatchClause c : n.getCatchClauses()) {
        c.accept(this, arg);
    }
    if (n.getFinallyBlock().isPresent()) {
        printer.print(" finally ");
        n.getFinallyBlock().get().accept(this, arg);
    }
}
 
Example #6
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public AssignExpr assignVar(RuleUnitVariable v) {
    ClassOrInterfaceType type = new ClassOrInterfaceType(null, v.getType().getCanonicalName());
    return new AssignExpr(
            new VariableDeclarationExpr(type, localVarName(v)),
            get(v),
            AssignExpr.Operator.ASSIGN);
}
 
Example #7
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public AssignExpr newInstance() {
    ClassOrInterfaceType type = new ClassOrInterfaceType(null, modelClassName);
    return new AssignExpr(
            new VariableDeclarationExpr(type, instanceVarName),
            new ObjectCreationExpr().setType(type),
            AssignExpr.Operator.ASSIGN);
}
 
Example #8
Source File: ProcessContextMetaModel.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public AssignExpr assignVariable(String procVar) {
    Expression e = getVariable(procVar);
    return new AssignExpr()
            .setTarget(new VariableDeclarationExpr(
                    new VariableDeclarator()
                            .setType(variableScope.findVariable(procVar).getType().getStringType())
                            .setName(procVar)))
            .setOperator(AssignExpr.Operator.ASSIGN)
            .setValue(e);
}
 
Example #9
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public AssignExpr newInstance(String assignVarName) {
    ClassOrInterfaceType type = new ClassOrInterfaceType(null, modelClassName);
    return new AssignExpr(
            new VariableDeclarationExpr(type, assignVarName),
            new ObjectCreationExpr().setType(type),
            AssignExpr.Operator.ASSIGN);
}
 
Example #10
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Statement makeAssignmentFromModel(Variable v, String name) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(v.getType().getStringType());
    // `type` `name` = (`type`) `model.get<Name>
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, name),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr("model"),
                            "get" + StringUtils.capitalize(name))),
            AssignExpr.Operator.ASSIGN);

    return new ExpressionStmt(assignExpr);
}
 
Example #11
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static Statement makeAssignment(String targetLocalVariable, Variable processVariable) {
    ClassOrInterfaceType type = parseClassOrInterfaceType(processVariable.getType().getStringType());
    // `type` `name` = (`type`) `kcontext.getVariable
    AssignExpr assignExpr = new AssignExpr(
            new VariableDeclarationExpr(type, targetLocalVariable),
            new CastExpr(
                    type,
                    new MethodCallExpr(
                            new NameExpr(KCONTEXT_VAR),
                            "getVariable")
                            .addArgument(new StringLiteralExpr(targetLocalVariable))),
            AssignExpr.Operator.ASSIGN);
    return new ExpressionStmt(assignExpr);
}
 
Example #12
Source File: ProcessVisitor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void visitProcess(WorkflowProcess process, MethodDeclaration processMethod, ProcessMetaData metadata) {
    BlockStmt body = new BlockStmt();

    ClassOrInterfaceType processFactoryType = new ClassOrInterfaceType(null, RuleFlowProcessFactory.class.getSimpleName());

    // create local variable factory and assign new fluent process to it
    VariableDeclarationExpr factoryField = new VariableDeclarationExpr(processFactoryType, FACTORY_FIELD_NAME);
    MethodCallExpr assignFactoryMethod = new MethodCallExpr(new NameExpr(processFactoryType.getName().asString()), "createProcess");
    assignFactoryMethod.addArgument(new StringLiteralExpr(process.getId()));
    body.addStatement(new AssignExpr(factoryField, assignFactoryMethod, AssignExpr.Operator.ASSIGN));

    // item definitions
    Set<String> visitedVariables = new HashSet<>();
    VariableScope variableScope = (VariableScope) ((org.jbpm.process.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);

    visitVariableScope(variableScope, body, visitedVariables);
    visitSubVariableScopes(process.getNodes(), body, visitedVariables);

    visitInterfaces(process.getNodes(), body);

    // the process itself
    body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_NAME, new StringLiteralExpr(process.getName())))
            .addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_PACKAGE_NAME, new StringLiteralExpr(process.getPackageName())))
            .addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_DYNAMIC, new BooleanLiteralExpr(((org.jbpm.workflow.core.WorkflowProcess) process).isDynamic())))
            .addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VERSION, new StringLiteralExpr(getOrDefault(process.getVersion(), DEFAULT_VERSION))))
            .addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VISIBILITY, new StringLiteralExpr(getOrDefault(process.getVisibility(), WorkflowProcess.PUBLIC_VISIBILITY))));

    visitMetaData(process.getMetaData(), body, FACTORY_FIELD_NAME);

    visitHeader(process, body);

    List<Node> processNodes = new ArrayList<>();
    for (org.kie.api.definition.process.Node procNode : process.getNodes()) {
        processNodes.add((org.jbpm.workflow.core.Node) procNode);
    }
    visitNodes(processNodes, body, variableScope, metadata);
    visitConnections(process.getNodes(), body);

    body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VALIDATE));

    MethodCallExpr getProcessMethod = new MethodCallExpr(new NameExpr(FACTORY_FIELD_NAME), "getProcess");
    body.addStatement(new ReturnStmt(getProcessMethod));
    processMethod.setBody(body);
}
 
Example #13
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private CompilationUnit compilationUnitOutput() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream("/class-templates/TaskOutputTemplate.java"));
    compilationUnit.setPackageDeclaration(packageName);
    Optional<ClassOrInterfaceDeclaration> processMethod = compilationUnit.findFirst(ClassOrInterfaceDeclaration.class, sl1 -> true);

    if (!processMethod.isPresent()) {
        throw new RuntimeException("Cannot find class declaration in the template");
    }
    ClassOrInterfaceDeclaration modelClass = processMethod.get();
    compilationUnit.addOrphanComment(new LineComment("Task output model for user task '" + humanTaskNode.getName() + "' in process '" + processId + "'"));
    addUserTaskAnnotation(modelClass);
    modelClass.setName(outputModelClassSimpleName);

    // setup of the toMap method body
    BlockStmt toMapBody = new BlockStmt();
    ClassOrInterfaceType toMap = new ClassOrInterfaceType(null, new SimpleName(Map.class.getSimpleName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getSimpleName()), new ClassOrInterfaceType(
                                                                                                                                                                                                                    null,
                                                                                                                                                                                                                    Object.class.getSimpleName())));
    VariableDeclarationExpr paramsField = new VariableDeclarationExpr(toMap, "params");
    toMapBody.addStatement(new AssignExpr(paramsField, new ObjectCreationExpr(null, new ClassOrInterfaceType(null, HashMap.class.getSimpleName()), NodeList.nodeList()), AssignExpr.Operator.ASSIGN));

    for (Entry<String, String> entry : humanTaskNode.getOutMappings().entrySet()) {
        if (entry.getValue() == null || INTERNAL_FIELDS.contains(entry.getKey())) {
            continue;
        }

        Variable variable = Optional.ofNullable(variableScope.findVariable(entry.getValue()))
                .orElse(processVariableScope.findVariable(entry.getValue()));

        if (variable == null) {
            // check if given mapping is an expression
            Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(entry.getValue());
            if (matcher.find()) {
                Map<String, String> dataOutputs = (Map<String, String>) humanTaskNode.getMetaData("DataOutputs");
                variable = new Variable();
                variable.setName(entry.getKey());
                variable.setType(new ObjectDataType(dataOutputs.get(entry.getKey())));
            } else {
                throw new IllegalStateException("Task " + humanTaskNode.getName() +" (output) " + entry.getKey() + " reference not existing variable " + entry.getValue());
            }
        }

        FieldDeclaration fd = new FieldDeclaration().addVariable(
                                                                 new VariableDeclarator()
                                                                                         .setType(variable.getType().getStringType())
                                                                                         .setName(entry.getKey()))
                                                    .addModifier(Modifier.Keyword.PRIVATE);
        modelClass.addMember(fd);
        addUserTaskParamAnnotation(fd, UserTaskParam.ParamType.OUTPUT);

        fd.createGetter();
        fd.createSetter();

        // toMap method body
        MethodCallExpr putVariable = new MethodCallExpr(new NameExpr("params"), "put");
        putVariable.addArgument(new StringLiteralExpr(entry.getKey()));
        putVariable.addArgument(new FieldAccessExpr(new ThisExpr(), entry.getKey()));
        toMapBody.addStatement(putVariable);
    }

    Optional<MethodDeclaration> toMapMethod = modelClass.findFirst(MethodDeclaration.class, sl -> sl.getName().asString().equals("toMap"));

    toMapBody.addStatement(new ReturnStmt(new NameExpr("params")));
    toMapMethod.ifPresent(methodDeclaration -> methodDeclaration.setBody(toMapBody));
    return compilationUnit;
}
 
Example #14
Source File: RuleUnitMetaModel.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private ForEachStmt iterate(VariableDeclarator iterVar, Expression sourceExpression) {
    return new ForEachStmt()
            .setVariable(new VariableDeclarationExpr(iterVar))
            .setIterable(sourceExpression);
}
 
Example #15
Source File: KieModuleModelMethod.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private AssignExpr newInstance( String type, String variableName, NameExpr scope, String methodName, String parameter) {
    MethodCallExpr initMethod = new MethodCallExpr(scope, methodName, nodeList(new StringLiteralExpr(parameter)));
    VariableDeclarationExpr var = new VariableDeclarationExpr(new ClassOrInterfaceType(null, type), variableName);
    return new AssignExpr(var, initMethod, AssignExpr.Operator.ASSIGN);
}
 
Example #16
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(VariableDeclarationExpr n, Void arg) {
    out.println("VariableDeclarationExpr: " + (extended ? n : n));
    super.visit(n, arg);
}
 
Example #17
Source File: VariableDeclarationExprMerger.java    From dolphin with Apache License 2.0 3 votes vote down vote up
@Override public boolean doIsEquals(VariableDeclarationExpr first, VariableDeclarationExpr second) {

    if(!isEqualsUseMerger(first.getType(),second.getType())) return false;
    if(!isEqualsUseMerger(first.getVars(),second.getVars())) return false;

    return true;
  }