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

The following examples show how to use com.github.javaparser.ast.expr.Expression. 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: kogito-runtimes   Author: kiegroup   File: CDIDependencyInjectionAnnotator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MethodDeclaration withInitMethod(Expression... expression) {
    BlockStmt body = new BlockStmt();
    for (Expression exp : expression) {
        body.addStatement(exp);
    }
    MethodDeclaration method = new MethodDeclaration()
            .addModifier(Keyword.PUBLIC)
            .setName("init")
            .setType(void.class)
            .setBody(body);

    method.addAndGetParameter("io.quarkus.runtime.StartupEvent", "event").addAnnotation("javax.enterprise.event.Observes");

    return method;
}
 
Example #2
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitHandler.java    License: Apache License 2.0 6 votes vote down vote up
public Expression invoke() {
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/class-templates/RuleUnitFactoryTemplate.java");
    Expression ruleUnitFactory = parse(resourceAsStream).findFirst(Expression.class)
            .orElseThrow(() -> new IllegalArgumentException("Template does not contain an Expression"));

    String unitName = ruleUnit.getCanonicalName();

    ruleUnitFactory.findAll(ClassOrInterfaceType.class)
            .stream()
            .filter(t -> t.getNameAsString().equals("$Type$"))
            .forEach(t -> t.setName(unitName));

    ruleUnitFactory.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("bind"))
            .ifPresent(m -> m.setBody(bind(variableScope, ruleSetNode, ruleUnit)));
    ruleUnitFactory.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("unit"))
            .ifPresent(m -> m.setBody(unit(unitName)));
    ruleUnitFactory.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("unbind"))
            .ifPresent(m -> m.setBody(unbind(variableScope, ruleSetNode, ruleUnit)));

    return ruleUnitFactory;
}
 
Example #3
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 #4
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 #5
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 #6
Source Project: kogito-runtimes   Author: kiegroup   File: RuleSetNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodCallExpr handleRuleUnit(VariableScope variableScope, ProcessMetaData metadata, RuleSetNode ruleSetNode, String nodeName, RuleSetNode.RuleType ruleType) {
    String unitName = ruleType.getName();
    ProcessContextMetaModel processContext = new ProcessContextMetaModel(variableScope, contextClassLoader);
    RuleUnitDescription description;

    try {
        Class<?> unitClass = loadUnitClass(nodeName, unitName, metadata.getPackageName());
        description = new ReflectiveRuleUnitDescription(null, (Class<? extends RuleUnitData>) unitClass);
    } catch (ClassNotFoundException e) {
        logger.warn("Rule task \"{}\": cannot load class {}. " +
                "The unit data object will be generated.", nodeName, unitName);

        GeneratedRuleUnitDescription d = generateRuleUnitDescription(unitName, processContext);
        RuleUnitComponentFactoryImpl impl = (RuleUnitComponentFactoryImpl) RuleUnitComponentFactory.get();
        impl.registerRuleUnitDescription(d);
        description = d;
    }

    RuleUnitHandler handler = new RuleUnitHandler(description, processContext, ruleSetNode, assignableChecker);
    Expression ruleUnitFactory = handler.invoke();

    return new MethodCallExpr("ruleUnit")
            .addArgument(new StringLiteralExpr(ruleType.getName()))
            .addArgument(ruleUnitFactory);

}
 
Example #7
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 #8
Source Project: stategen   Author: stategen   File: PrettyPrintVisitor.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void visit(final ArrayInitializerExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printer.print("{");
    if (!isNullOrEmpty(n.getValues())) {
        printer.print(" ");
        for (final Iterator<Expression> i = n.getValues().iterator(); i.hasNext(); ) {
            final Expression expr = i.next();
            expr.accept(this, arg);
            if (i.hasNext()) {
                printer.print(", ");
            }
        }
        printer.print(" ");
    }
    printer.print("}");
}
 
Example #9
Source Project: apigcc   Author: apigcc   File: AnnotationHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 获取注解的属性
 * @param expr
 * @param keys 从前往后找,返回第一个存在的属性
 * @return
 */
public static Optional<Expression> attr(AnnotationExpr expr, String ... keys) {
    for (String key : keys) {
        if (Objects.equals("value", key) && expr.isSingleMemberAnnotationExpr()) {
            return Optional.of(expr.asSingleMemberAnnotationExpr().getMemberValue());
        }
        if (expr.isNormalAnnotationExpr()) {
            for (MemberValuePair pair : expr.asNormalAnnotationExpr().getPairs()) {
                if (Objects.equals(key, pair.getNameAsString())) {
                    return Optional.of(pair.getValue());
                }
            }
        }
    }
    return Optional.empty();
}
 
Example #10
Source Project: jeddict   Author: jeddict   File: MemberExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public String getDefaultValue() {
    String defaultValue = null;
    if (field != null && field.getVariables().get(0).getChildNodes().size() == 3) {
        Node node = field.getVariables().get(0).getChildNodes().get(2);
        if (node instanceof Expression) { //FieldAccessExpr, MethodCallExpr, ObjectCreationExpr
            defaultValue = node.toString();
            Map<String, ImportDeclaration> imports = clazz.getImports();
             String importList = imports.keySet()
                     .stream()
                    .filter(defaultValue::contains)
                    .map(imports::get)
                    .map(ImportDeclaration::getNameAsString)
                    .collect(joining(" ,\n"));
            defaultValue = importList.isEmpty() ? defaultValue : "[\n" + importList + "\n]\n" + defaultValue;
        } else if (node instanceof NodeWithSimpleName) {
            defaultValue = ((NodeWithSimpleName) node).getNameAsString();
        } else if (node instanceof LiteralStringValueExpr) {
            defaultValue = "'" + ((LiteralStringValueExpr) node).getValue() + "'";
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return defaultValue;
}
 
Example #11
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 #12
Source Project: jeddict   Author: jeddict   File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static Optional<Long> getLongAttribute(AnnotationExpr annotationExpr, String attributeName) {
    Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName);
    if (expressionOpt.isPresent()) {
        Expression expression = expressionOpt.get();
        if (expression.isLongLiteralExpr()) {
            return expressionOpt.flatMap(exp -> exp.toLongLiteralExpr())
                    .map(exp -> exp.asLong());
        } else if (expression.isIntegerLiteralExpr()) {
            return expressionOpt.flatMap(exp -> exp.toIntegerLiteralExpr())
                    .map(exp -> exp.asInt())
                    .map(Long::valueOf);
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return Optional.empty();
}
 
Example #13
Source Project: jeddict   Author: jeddict   File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> getClassNameAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isClassExpr()) {
            values.add(expression.asClassExpr().getTypeAsString());
        } else if (expression.isArrayInitializerExpr()) {
            for (Node node : expression.asArrayInitializerExpr().getChildNodes()) {
                if (node instanceof ClassExpr) {
                    values.add(((ClassExpr) node).getTypeAsString());
                } else {
                    throw new UnsupportedOperationException();
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example #14
Source Project: CodeDefenders   Author: CodeDefenders   File: TestCodeVisitor.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void visit(VariableDeclarator stmt, Void args) {
    if (!isValid) {
        return;
    }
    Optional<Expression> initializer = stmt.getInitializer();
    if (initializer.isPresent()) {
        String initString = initializer.get().toString();
        if (initString.startsWith("System.*") || initString.startsWith("Random.*") ||
                initString.contains("Thread")) {
            messages.add("Test contains an invalid variable declaration: " + initString);
            isValid = false;
        }
    }
    super.visit(stmt, args);
}
 
Example #15
Source Project: gauge-java   Author: getgauge   File: RegistryMethodVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(MethodDeclaration methodDeclaration, Object arg) {
    List<AnnotationExpr> annotations = methodDeclaration.getAnnotations();
    if (annotations.isEmpty()) {
        return;
    }

    for (AnnotationExpr annotationExpr : annotations) {
        if (!(annotationExpr instanceof SingleMemberAnnotationExpr)) {
            continue;
        }
        SingleMemberAnnotationExpr annotation = (SingleMemberAnnotationExpr) annotationExpr;
        if (annotation.getMemberValue() instanceof ArrayInitializerExpr) {
            ArrayInitializerExpr memberValue = (ArrayInitializerExpr) annotation.getMemberValue();
            for (Expression expression : memberValue.getValues()) {
                addStepToRegistry(expression, methodDeclaration, annotation);
            }
        } else {
            addStepToRegistry(annotation.getMemberValue(), methodDeclaration, annotation);
        }
    }
}
 
Example #16
Source Project: gauge-java   Author: getgauge   File: RegistryMethodVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private void addStepToRegistry(Expression expression, MethodDeclaration methodDeclaration, SingleMemberAnnotationExpr annotation) {
    String parameterizedStep = getParameterizedStep(expression);
    String stepText = new StepsUtil().getStepText(parameterizedStep);
    stepValue = new StepValue(stepText, parameterizedStep);

    entry = new StepRegistryEntry();
    entry.setName(methodDeclaration.getDeclarationAsString());
    String className = getClassName(methodDeclaration);
    String fullyQualifiedName = className == null
            ? methodDeclaration.getNameAsString() : className + "." + methodDeclaration.getNameAsString();
    entry.setFullyQualifiedName(fullyQualifiedName);
    entry.setStepText(parameterizedStep);
    entry.setStepValue(stepValue);
    entry.setParameters(methodDeclaration.getParameters());
    entry.setSpan(methodDeclaration.getRange().get());
    entry.setHasAlias(hasAlias(annotation));
    entry.setAliases(getAliases(annotation));
    entry.setFileName(file);

    stepRegistry.addStep(stepValue, entry);
}
 
Example #17
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 #18
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
private void addCastExpr(Statement stmt, Type castType) {
  ReturnStmt rstmt = (ReturnStmt) stmt;
  Optional<Expression> o_expr = rstmt.getExpression(); 
  Expression expr = o_expr.isPresent() ? o_expr.get() : null;
  CastExpr ce = new CastExpr(castType, expr);
  rstmt.setExpression(ce);  // removes the parent link from expr
  if (expr != null) {
    expr.setParentNode(ce); // restore it
  }
}
 
Example #19
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 #20
Source Project: kogito-runtimes   Author: kiegroup   File: DependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Annotates given node with set of roles to enforce security
 *
 * @param node  node to be annotated
 * @param roles roles that are allowed
 */
default <T extends NodeWithAnnotations<?>> T withSecurityRoles(T node, String[] roles) {
    if (roles != null && roles.length > 0) {
        List<Expression> rolesExpr = new ArrayList<>();

        for (String role : roles) {
            rolesExpr.add(new StringLiteralExpr(role.trim()));
        }

        node.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.annotation.security.RolesAllowed"), new ArrayInitializerExpr(NodeList.nodeList(rolesExpr))));
    }
    return node;
}
 
Example #21
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 #22
Source Project: kogito-runtimes   Author: kiegroup   File: SpringDependencyInjectionAnnotator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MethodDeclaration withInitMethod(Expression... expression) {
    BlockStmt body = new BlockStmt();
    for (Expression exp : expression) {
        body.addStatement(exp);
    }
    return new MethodDeclaration()
            .addModifier(Keyword.PUBLIC)
            .setName("init")
            .setType(void.class)
            .addAnnotation("javax.annotation.PostConstruct")
            .setBody(body);
}
 
Example #23
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
private Expression getExpressionFromStmt(Statement stmt) {
  stmt = getStmtFromStmt(stmt);
  if (stmt instanceof ExpressionStmt) {
    return getUnenclosedExpr(((ExpressionStmt)stmt).getExpression());
  }
  return null;
}
 
Example #24
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 #25
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 #26
Source Project: kogito-runtimes   Author: kiegroup   File: DecisionContainerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
    //        FieldDeclaration dmnRuntimeField = new FieldDeclaration().addModifier(Modifier.Keyword.STATIC)
    //                                                                 .addVariable(new VariableDeclarator().setType(DMNRuntime.class.getCanonicalName())
    //                                                                                                      .setName("dmnRuntime")
    //                                                                                                      .setInitializer(new MethodCallExpr("org.kie.dmn.kogito.rest.quarkus.DMNKogitoQuarkus.createGenericDMNRuntime")));
    //        ClassOrInterfaceDeclaration cls = super.classDeclaration();
    //        cls.addModifier(Modifier.Keyword.STATIC);
    //        cls.addMember(dmnRuntimeField);
    //
    //        MethodDeclaration getDecisionMethod = new MethodDeclaration().setName("getDecision")
    //                                                                     .setType(Decision.class.getCanonicalName())
    //                                                                     .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "namespace"))
    //                                                                     .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "name"))
    //        ;
    //        cls.addMember(getDecisionMethod);
    CompilationUnit clazz = StaticJavaParser.parse(this.getClass().getResourceAsStream(TEMPLATE_JAVA));
    ClassOrInterfaceDeclaration typeDeclaration = (ClassOrInterfaceDeclaration) clazz.getTypes().get(0);
    ClassOrInterfaceType applicationClass = StaticJavaParser.parseClassOrInterfaceType(applicationCanonicalName);
    ClassOrInterfaceType inputStreamReaderClass = StaticJavaParser.parseClassOrInterfaceType(java.io.InputStreamReader.class.getCanonicalName());
    for (DMNResource resource : resources) {
        MethodCallExpr getResAsStream = getReadResourceMethod( applicationClass, resource );
        ObjectCreationExpr isr = new ObjectCreationExpr().setType(inputStreamReaderClass).addArgument(getResAsStream);
        Optional<FieldDeclaration> dmnRuntimeField = typeDeclaration.getFieldByName("dmnRuntime");
        Optional<Expression> initalizer = dmnRuntimeField.flatMap(x -> x.getVariable(0).getInitializer());
        if (initalizer.isPresent()) {
            initalizer.get().asMethodCallExpr().addArgument(isr);
        } else {
            throw new RuntimeException("The template " + TEMPLATE_JAVA + " has been modified.");
        }
    }
    if (useTracing) {
        VariableDeclarator execIdSupplierVariable = typeDeclaration.getFieldByName("execIdSupplier")
                .map(x -> x.getVariable(0))
                .orElseThrow(() -> new RuntimeException("Can't find \"execIdSupplier\" field in " + TEMPLATE_JAVA));
        execIdSupplierVariable.setInitializer(newObject(DmnExecutionIdSupplier.class));
    }
    return typeDeclaration;
}
 
Example #27
Source Project: kogito-runtimes   Author: kiegroup   File: AbstractNodeVisitor.java    License: 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 #28
Source Project: kogito-runtimes   Author: kiegroup   File: ModelMetaData.java    License: Apache License 2.0 5 votes vote down vote up
public MethodCallExpr callSetter(String targetVar, String destField, Expression value) {
    String name = variableScope.getTypes().get(destField).getSanitizedName();
    String type = variableScope.getType(destField);
    String setter = "set" + StringUtils.capitalize(name); // todo cache FieldDeclarations in compilationUnit()
    return new MethodCallExpr(new NameExpr(targetVar), setter).addArgument(
            new CastExpr(
                    new ClassOrInterfaceType(null, type),
                    new EnclosedExpr(value)));
}
 
Example #29
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessContextMetaModel.java    License: Apache License 2.0 5 votes vote down vote up
public Expression getVariable(String procVar) {
    String interpolatedVar = extractVariableFromExpression(procVar);
    Variable v = variableScope.findVariable(interpolatedVar);
    if (v == null) {
        throw new IllegalArgumentException("No such variable " + procVar);
    }
    MethodCallExpr getter = new MethodCallExpr().setScope(new NameExpr(kcontext))
            .setName("getVariable")
            .addArgument(new StringLiteralExpr(interpolatedVar));
    CastExpr castExpr = new CastExpr()
            .setExpression(new EnclosedExpr(getter))
            .setType(v.getType().getStringType());
    return castExpr;
}
 
Example #30
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessContextMetaModel.java    License: 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);
}