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

The following examples show how to use com.github.javaparser.ast.expr.AssignExpr. 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: LambdaSubProcessNodeVisitor.java    From kogito-runtimes with 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 #2
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 #3
Source File: TestCodeVisitor.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final AssignExpr stmt, Void args) {
    if (!isValid) {
        return;
    }
    final AssignExpr.Operator operator = stmt.getOperator();
    if (operator != null && (Stream.of(AssignExpr.Operator.AND, AssignExpr.Operator.OR, AssignExpr.Operator.XOR)
            .anyMatch(op -> operator == op))) {
        isValid = false;
    }
    super.visit(stmt, args);
}
 
Example #4
Source File: AssignExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public boolean doIsEquals(AssignExpr first, AssignExpr second) {

    if(!isEqualsUseMerger(first.getTarget(),second.getTarget())) return false;
    if(!isEqualsUseMerger(first.getValue(),second.getValue())) return false;
    if(!first.getOperator().equals(second.getOperator())) return false;

    return true;
  }
 
Example #5
Source File: AssignExprMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
@Override public AssignExpr doMerge(AssignExpr first, AssignExpr second) {
  AssignExpr ae = new AssignExpr();

  ae.setOperator(first.getOperator());
  ae.setTarget(mergeSingle(first.getTarget(),second.getTarget()));
  ae.setValue(mergeSingle(first.getValue(),second.getValue()));

  return ae;
}
 
Example #6
Source File: GeneralFixture.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void runAnalysis(CompilationUnit testFileCompilationUnit, CompilationUnit productionFileCompilationUnit, String testFileName, String productionFileName) throws FileNotFoundException {
    GeneralFixture.ClassVisitor classVisitor;
    classVisitor = new GeneralFixture.ClassVisitor();
    classVisitor.visit(testFileCompilationUnit, null); //This call will populate the list of test methods and identify the setup method [visit(ClassOrInterfaceDeclaration n)]

    //Proceed with general fixture analysis if setup method exists
    if (setupMethod != null) {
        //Get all fields that are initialized in the setup method
        //The following code block will identify the class level variables (i.e. fields) that are initialized in the setup method
        // TODO: There has to be a better way to do this identification/check!
        Optional<BlockStmt> blockStmt = setupMethod.getBody();
        NodeList nodeList = blockStmt.get().getStatements();
        for (int i = 0; i < nodeList.size(); i++) {
            for (int j = 0; j < fieldList.size(); j++) {
                for (int k = 0; k < fieldList.get(j).getVariables().size(); k++) {
                    if (nodeList.get(i) instanceof ExpressionStmt) {
                        ExpressionStmt expressionStmt = (ExpressionStmt) nodeList.get(i);
                        if (expressionStmt.getExpression() instanceof AssignExpr) {
                            AssignExpr assignExpr = (AssignExpr) expressionStmt.getExpression();
                            if (fieldList.get(j).getVariable(k).getNameAsString().equals(assignExpr.getTarget().toString())) {
                                setupFields.add(assignExpr.getTarget().toString());
                            }
                        }
                    }
                }
            }
        }
    }

    for (MethodDeclaration method : methodList) {
        //This call will visit each test method to identify the list of variables the method contains [visit(MethodDeclaration n)]
        classVisitor.visit(method, null);
    }
}
 
Example #7
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 AssignExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    n.getTarget().accept(this, arg);
    printer.print(" ");
    printer.print(n.getOperator().asString());
    printer.print(" ");
    n.getValue().accept(this, arg);
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: ConfigGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private MethodDeclaration generateInitMethod() {
    BlockStmt body = new BlockStmt()
            .addStatement(new AssignExpr(new NameExpr("processConfig"), newProcessConfigInstance(), AssignExpr.Operator.ASSIGN))
            .addStatement(new AssignExpr(new NameExpr("ruleConfig"), newRuleConfigInstance(), AssignExpr.Operator.ASSIGN))
            .addStatement(new AssignExpr(new NameExpr("decisionConfig"), newDecisionConfigInstance(), AssignExpr.Operator.ASSIGN));

    return method(Keyword.PUBLIC, void.class, "init", body);
}
 
Example #16
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 #17
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 #18
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 #19
Source File: TraceVisitor.java    From JCTools with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(AssignExpr n, Void arg) {
    out.println("AssignExpr: " + (extended ? n : n.getTarget() + " = " + n.getValue()));
    super.visit(n, arg);
}
 
Example #20
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 3 votes vote down vote up
/**
 * Generates something like <code>field = newValue</code>
 *
 * @param fieldName
 * @param valueName
 * @return
 */
protected BlockStmt fieldAssignment(String fieldName, String valueName) {
    BlockStmt body = new BlockStmt();
    body.addStatement(
            new ExpressionStmt(new AssignExpr(new NameExpr(fieldName), new NameExpr(valueName), Operator.ASSIGN)));
    return body;
}