Java Code Examples for com.github.javaparser.ast.expr.MethodCallExpr#addArgument()

The following examples show how to use com.github.javaparser.ast.expr.MethodCallExpr#addArgument() . 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: ConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateAddonsMethod() {
    MethodCallExpr asListOfAddons = new MethodCallExpr(new NameExpr("java.util.Arrays"), "asList");
    try {
        Enumeration<URL> urls = classLoader.getResources("META-INF/kogito.addon");
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String addon = StringUtils.readFileAsString(new InputStreamReader(url.openStream()));
            asListOfAddons.addArgument(new StringLiteralExpr(addon));
        }
    } catch (IOException e) {
        LOGGER.warn("Unexpected exception during loading of kogito.addon files", e);
    }

    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(
            newObject(Addons.class, asListOfAddons)
    ));

    return method(Keyword.PUBLIC, Addons.class, "addons", body);
}
 
Example 2
Source File: MigrateJCas.java    From uima-uimaj with 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 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: AbstractVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected MethodCallExpr getFactoryMethod(String object, String methodName, Expression... args) {
    MethodCallExpr variableMethod = new MethodCallExpr(new NameExpr(object), methodName);

    for (Expression arg : args) {
        variableMethod.addArgument(arg);
    }
    return variableMethod;
}
 
Example 5
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public MethodCallExpr withMessageProducer(MethodCallExpr produceMethod, String channel, Expression event) {
    produceMethod.addArgument(event);
    return produceMethod;
}
 
Example 6
Source File: RuleUnitInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private MethodDeclaration bindMethod() {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    BlockStmt methodBlock = new BlockStmt();
    methodDeclaration.setName("bind")
            .addAnnotation( "Override" )
            .addModifier(Modifier.Keyword.PROTECTED)
            .addParameter(KieSession.class.getCanonicalName(), "runtime")
            .addParameter(ruleUnitDescription.getRuleUnitName(), "value")
            .setType(void.class)
            .setBody(methodBlock);

    try {


        for (RuleUnitVariable m : ruleUnitDescription.getUnitVarDeclarations()) {
            String methodName = m.getter();
            String propertyName = m.getName();

            if ( m.isDataSource() ) {

                if (m.setter() != null) { // if writable and DataSource is null create and set a new one
                    Expression nullCheck = new BinaryExpr(new MethodCallExpr(new NameExpr("value"), methodName), new NullLiteralExpr(), BinaryExpr.Operator.EQUALS);
                    Expression createDataSourceExpr = new MethodCallExpr(new NameExpr(DataSource.class.getCanonicalName()), ruleUnitHelper.createDataSourceMethodName(m.getBoxedVarType()));
                    Expression dataSourceSetter = new MethodCallExpr(new NameExpr("value"), m.setter(), new NodeList<>(createDataSourceExpr));
                    methodBlock.addStatement( new IfStmt( nullCheck, new BlockStmt().addStatement( dataSourceSetter ), null ) );
                }

                //  value.$method())
                Expression fieldAccessor =
                        new MethodCallExpr(new NameExpr("value"), methodName);

                // .subscribe( new EntryPointDataProcessor(runtime.getEntryPoint()) )

                String entryPointName = getEntryPointName(ruleUnitDescription, propertyName);
                MethodCallExpr drainInto = new MethodCallExpr(fieldAccessor, "subscribe")
                        .addArgument(new ObjectCreationExpr(null, StaticJavaParser.parseClassOrInterfaceType( EntryPointDataProcessor.class.getName() ), NodeList.nodeList(
                                new MethodCallExpr(
                                        new NameExpr("runtime"), "getEntryPoint",
                                        NodeList.nodeList(new StringLiteralExpr( entryPointName ))))));

                methodBlock.addStatement(drainInto);
            }

            MethodCallExpr setGlobalCall = new MethodCallExpr( new NameExpr("runtime"), "setGlobal" );
            setGlobalCall.addArgument( new StringLiteralExpr( propertyName ) );
            setGlobalCall.addArgument( new MethodCallExpr(new NameExpr("value"), methodName) );
            methodBlock.addStatement(setGlobalCall);
        }

    } catch (Exception e) {
        throw new Error(e);
    }

    return methodDeclaration;
}
 
Example 7
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java"));
    clazz.setPackageDeclaration(this.packageName);

    ClassOrInterfaceDeclaration template = clazz
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));

    template.setName(resourceClazzName);

    template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);
    template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods);

    interpolateInputType(template);

    if (useInjection()) {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
    } else {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(this::initializeApplicationField);
    }

    MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0);
    for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) {
        if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) {
            continue;
        }

        MethodDeclaration clonedMethod = dmnMethod.clone();
        String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName());
        clonedMethod.setName(name);
        MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!"));
        evaluateCall.setName(new SimpleName("evaluateDecisionService"));
        evaluateCall.addArgument(new StringLiteralExpr(ds.getName()));
        clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName())));
        ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!"));
        if (ds.getOutputDecision().size() == 1) {
            MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class,
                                                                      mce -> mce.getNameAsString().equals("extractContextIfSucceded"))
                                                           .orElseThrow(() -> new RuntimeException("Template was modified!"));
            rewrittenReturnExpr.setName("extractSingletonDSIfSucceded");
        }

        if (useMonitoring) {
            addMonitoringToMethod(clonedMethod, ds.getName());
        }

        template.addMember(clonedMethod);
    }

    if (useMonitoring) {
        addMonitoringImports(clazz);
        ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString()))
                .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed."));
        addExceptionMetricsLogging(exceptionClazz, nameURL);
        addMonitoringToMethod(dmnMethod, nameURL);
    }

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 8
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 9
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 10
Source File: ServiceTaskDescriptor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String unqualifiedName = StaticJavaParser.parseName(mangledName).removeQualifier().asString();
    ClassOrInterfaceDeclaration cls = new ClassOrInterfaceDeclaration()
            .setName(unqualifiedName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .addImplementedType(WorkItemHandler.class.getCanonicalName());
    ClassOrInterfaceType serviceType = new ClassOrInterfaceType(null, interfaceName);
    FieldDeclaration serviceField = new FieldDeclaration()
            .addVariable(new VariableDeclarator(serviceType, "service"));
    cls.addMember(serviceField);

    // executeWorkItem method
    BlockStmt executeWorkItemBody = new BlockStmt();
    MethodDeclaration executeWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("executeWorkItem")
            .setBody(executeWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    MethodCallExpr callService = new MethodCallExpr(new NameExpr("service"), operationName);

    for (Map.Entry<String, String> paramEntry : parameters.entrySet()) {
        MethodCallExpr getParamMethod = new MethodCallExpr(new NameExpr("workItem"), "getParameter").addArgument(new StringLiteralExpr(paramEntry.getKey()));
        callService.addArgument(new CastExpr(new ClassOrInterfaceType(null, paramEntry.getValue()), getParamMethod));
    }
    MethodCallExpr completeWorkItem = completeWorkItem(executeWorkItemBody, callService);

    executeWorkItemBody.addStatement(completeWorkItem);

    // abortWorkItem method
    BlockStmt abortWorkItemBody = new BlockStmt();
    MethodDeclaration abortWorkItem = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(void.class)
            .setName("abortWorkItem")
            .setBody(abortWorkItemBody)
            .addParameter(WorkItem.class.getCanonicalName(), "workItem")
            .addParameter(WorkItemManager.class.getCanonicalName(), "workItemManager");

    // getName method
    MethodDeclaration getName = new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType(String.class)
            .setName("getName")
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new StringLiteralExpr(mangledName))));
    cls.addMember(executeWorkItem)
            .addMember(abortWorkItem)
            .addMember(getName);

    return cls;
}