Java Code Examples for com.github.javaparser.ast.stmt.BlockStmt#addStatement()

The following examples show how to use com.github.javaparser.ast.stmt.BlockStmt#addStatement() . 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: ProcessVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void visitHeader(WorkflowProcess process, BlockStmt body) {
    Map<String, Object> metaData = getMetaData(process.getMetaData());
    Set<String> imports = ((org.jbpm.process.core.Process) process).getImports();
    Map<String, String> globals = ((org.jbpm.process.core.Process) process).getGlobals();
    if ((imports != null && !imports.isEmpty()) || (globals != null && globals.size() > 0) || !metaData.isEmpty()) {
        if (imports != null) {
            for (String s : imports) {
                body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_IMPORTS, new StringLiteralExpr(s)));
            }
        }
        if (globals != null) {
            for (Map.Entry<String, String> global : globals.entrySet()) {
                body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_GLOBAL, new StringLiteralExpr(global.getKey()), new StringLiteralExpr(global.getValue())));
            }
        }
    }
}
 
Example 2
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with 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 3
Source File: CompositeContextNodeVisitor.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(String factoryField, T node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, factoryClass(), getNodeId(node), factoryMethod(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, getDefaultName()));
    visitMetaData(node.getMetaData(), body, getNodeId(node));
    VariableScope variableScopeNode = (VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE);

    if (variableScope != null) {
        visitVariableScope(getNodeId(node), variableScopeNode, body, new HashSet<>());
    }

    visitCustomFields(node, variableScope).forEach(body::addStatement);

    // composite context node might not have variable scope
    // in that case inherit it from parent
    VariableScope scope = variableScope;
    if (node.getDefaultContext(VariableScope.VARIABLE_SCOPE) != null && !((VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE)).getVariables().isEmpty()) {
        scope = (VariableScope) node.getDefaultContext(VariableScope.VARIABLE_SCOPE);
    }
    body.addStatement(getFactoryMethod(getNodeId(node), CompositeContextNodeFactory.METHOD_AUTO_COMPLETE, new BooleanLiteralExpr(node.isAutoComplete())));
    visitNodes(getNodeId(node), node.getNodes(), body, scope, metadata);
    visitConnections(getNodeId(node), node.getNodes(), body);
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example 4
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public BlockStmt copyInto(String sourceVarName, String destVarName, ModelMetaData dest, Map<String, String> mapping) {
    BlockStmt blockStmt = new BlockStmt();

    for (Map.Entry<String, String> e : mapping.entrySet()) {
        String destField = variableScope.getTypes().get(e.getKey()).getSanitizedName();
        String sourceField = e.getValue();
        blockStmt.addStatement(
                dest.callSetter(destVarName, destField, dest.callGetter(sourceVarName, sourceField)));
    }

    return blockStmt;
}
 
Example 5
Source File: ProcessVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void visitVariableScope(VariableScope variableScope, BlockStmt body, Set<String> visitedVariables) {
    if (variableScope != null && !variableScope.getVariables().isEmpty()) {
        for (Variable variable : variableScope.getVariables()) {

            if (!visitedVariables.add(variable.getName())) {
                continue;
            }
            String tags = (String) variable.getMetaData(Variable.VARIABLE_TAGS);
            ClassOrInterfaceType variableType = new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName());
            ObjectCreationExpr variableValue = new ObjectCreationExpr(null, variableType, new NodeList<>(new StringLiteralExpr(variable.getType().getStringType())));
            body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VARIABLE, new StringLiteralExpr(variable.getName()), variableValue, new StringLiteralExpr(Variable.VARIABLE_TAGS), tags != null ? new StringLiteralExpr(tags) : new NullLiteralExpr()));
        }
    }
}
 
Example 6
Source File: MessageProducerGenerator.java    From kogito-runtimes with 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 7
Source File: PersistenceGenerator.java    From kogito-runtimes with 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 8
Source File: ProcessVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void visitConnection(Connection connection, BlockStmt body) {
    // if the connection was generated by a link event, don't dump.
    if (isConnectionRepresentingLinkEvent(connection)) {
        return;
    }
    // if the connection is a hidden one (compensations), don't dump
    Object hidden = ((ConnectionImpl) connection).getMetaData(HIDDEN);
    if (hidden != null && ((Boolean) hidden)) {
        return;
    }

    body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_CONNECTION, new LongLiteralExpr(connection.getFrom().getId()),
            new LongLiteralExpr(connection.getTo().getId()),
            new StringLiteralExpr(getOrDefault((String) connection.getMetaData().get(UNIQUE_ID), ""))));
}
 
Example 9
Source File: LambdaSubProcessNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private BlockStmt unbind(VariableScope variableScope, SubProcessNode subProcessNode) {
    BlockStmt stmts = new BlockStmt();

    for (Map.Entry<String, String> e : subProcessNode.getOutMappings().entrySet()) {

        // check if given mapping is an expression
        Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(e.getValue());
        if (matcher.find()) {

            String expression = matcher.group(1);
            String topLevelVariable = expression.split("\\.")[0];
            Map<String, String> dataOutputs = (Map<String, String>) subProcessNode.getMetaData("BPMN.OutputTypes");
            Variable variable = new Variable();
            variable.setName(topLevelVariable);
            variable.setType(new ObjectDataType(dataOutputs.get(e.getKey())));

            stmts.addStatement(makeAssignment(variableScope.findVariable(topLevelVariable)));
            stmts.addStatement(makeAssignmentFromModel(variable, e.getKey()));

            stmts.addStatement(dotNotationToSetExpression(expression, e.getKey()));

            stmts.addStatement(new MethodCallExpr()
                    .setScope(new NameExpr(KCONTEXT_VAR))
                    .setName("setVariable")
                    .addArgument(new StringLiteralExpr(topLevelVariable))
                    .addArgument(topLevelVariable));
        } else {

            stmts.addStatement(makeAssignmentFromModel(variableScope.findVariable(e.getValue()), e.getKey()));
            stmts.addStatement(new MethodCallExpr()
                    .setScope(new NameExpr(KCONTEXT_VAR))
                    .setName("setVariable")
                    .addArgument(new StringLiteralExpr(e.getValue()))
                    .addArgument(e.getKey()));
        }

    }

    return stmts;
}
 
Example 10
Source File: RuleUnitDTOSourceClass.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(packageName);

    ClassOrInterfaceDeclaration dtoClass = cu.addClass(targetCanonicalName, Modifier.Keyword.PUBLIC);
    dtoClass.addImplementedType(String.format("java.util.function.Supplier<%s>", ruleUnit.getSimpleName()));

    MethodDeclaration supplier = dtoClass.addMethod("get", Modifier.Keyword.PUBLIC);
    supplier.addAnnotation(Override.class);
    supplier.setType(ruleUnit.getSimpleName());
    BlockStmt supplierBlock = supplier.createBody();
    supplierBlock.addStatement(String.format("%s unit = new %s();", ruleUnit.getSimpleName(), ruleUnit.getSimpleName()));

    for (RuleUnitVariable unitVarDeclaration : ruleUnit.getUnitVarDeclarations()) {
        FieldProcessor fieldProcessor = new FieldProcessor(unitVarDeclaration, ruleUnitHelper );
        FieldDeclaration field = fieldProcessor.createField();
        supplierBlock.addStatement(fieldProcessor.fieldInitializer());
        dtoClass.addMember(field);
        field.createGetter();
        field.createSetter();
    }

    supplierBlock.addStatement("return unit;");

    return cu.toString();
}
 
Example 11
Source File: RuleUnitHelper.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
BlockStmt fieldInitializer( RuleUnitVariable ruleUnitVariable, String genericType, boolean isDataSource) {
    BlockStmt supplierBlock = new BlockStmt();

    if (!isDataSource) {
        if (ruleUnitVariable.setter() != null) {
            supplierBlock.addStatement(String.format("unit.%s(%s);", ruleUnitVariable.setter(), ruleUnitVariable.getName()));
        }
    } else if ( isAssignableFrom( DataStream.class, ruleUnitVariable.getType())) {
        if (ruleUnitVariable.setter() != null) {
            supplierBlock.addStatement(String.format("org.kie.kogito.rules.DataStream<%s> %s = org.kie.kogito.rules.DataSource.createStream();", genericType, ruleUnitVariable.getName()));
            supplierBlock.addStatement(String.format("unit.%s(%s);", ruleUnitVariable.setter(), ruleUnitVariable.getName()));
        }
        supplierBlock.addStatement(String.format("this.%s.forEach( unit.%s()::append);", ruleUnitVariable.getName(), ruleUnitVariable.getter()));
    } else if ( isAssignableFrom( DataStore.class, ruleUnitVariable.getType())) {
        if (ruleUnitVariable.setter() != null) {
            supplierBlock.addStatement(String.format("org.kie.kogito.rules.DataStore<%s> %s = org.kie.kogito.rules.DataSource.createStore();", genericType, ruleUnitVariable.getName()));
            supplierBlock.addStatement(String.format("unit.%s(%s);", ruleUnitVariable.setter(), ruleUnitVariable.getName()));
        }
        supplierBlock.addStatement(String.format("this.%s.forEach( unit.%s()::add);", ruleUnitVariable.getName(), ruleUnitVariable.getter()));
    } else if ( isAssignableFrom( SingletonStore.class, ruleUnitVariable.getType())) {
        supplierBlock.addStatement(String.format("unit.%s().set(this.%s );", ruleUnitVariable.getter(), ruleUnitVariable.getName()));
    } else {
        throw new IllegalArgumentException("Unknown data source type " + ruleUnitVariable.getType());
    }

    return supplierBlock;
}
 
Example 12
Source File: BoundaryEventNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void visitNode(String factoryField, BoundaryEventNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, BoundaryEventNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "BoundaryEvent"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_EVENT_TYPE, new StringLiteralExpr(node.getType())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_ATTACHED_TO, new StringLiteralExpr(node.getAttachedToNodeId())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_SCOPE, getOrNullExpr(node.getScope())));

    Variable variable = null;
    if (node.getVariableName() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE_NAME, new StringLiteralExpr(node.getVariableName())));
        variable = variableScope.findVariable(node.getVariableName());
    }

    if (EVENT_TYPE_SIGNAL.equals(node.getMetaData(EVENT_TYPE))) {
        metadata.getSignals().put(node.getType(), variable != null ? variable.getType().getStringType() : null);
    } else if (EVENT_TYPE_MESSAGE.equals(node.getMetaData(EVENT_TYPE))) {
        Map<String, Object> nodeMetaData = node.getMetaData();
        metadata.getTriggers().add(new TriggerMetaData((String) nodeMetaData.get(TRIGGER_REF),
                (String) nodeMetaData.get(TRIGGER_TYPE),
                (String) nodeMetaData.get(MESSAGE_TYPE),
                node.getVariableName(),
                String.valueOf(node.getId())).validate());
    }

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example 13
Source File: AbstractNodeVisitor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected void visitConnection(String factoryField, Connection connection, BlockStmt body) {
    // if the connection is a hidden one (compensations), don't dump
    Object hidden = ((ConnectionImpl) connection).getMetaData(HIDDEN);
    if (hidden != null && ((Boolean) hidden)) {
        return;
    }

    body.addStatement(getFactoryMethod(factoryField, "connection", new LongLiteralExpr(connection.getFrom().getId()),
            new LongLiteralExpr(connection.getTo().getId()),
            new StringLiteralExpr(getOrDefault((String) connection.getMetaData().get("UniqueId"), ""))));
}
 
Example 14
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(capitalize(name));

  properties.stream().filter(property -> property.type instanceof EnumType).forEach(
      property -> classDecl.addMember(((EnumType) property.type).toTypeDeclaration()));

  properties.forEach(property -> classDecl.addField(
      property.getJavaType(), property.getFieldName()).setPrivate(true).setFinal(true));

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  properties.forEach(
      property -> constructor.addParameter(property.getJavaType(), property.getFieldName()));
  properties.forEach(property -> {
    if (property.optional) {
      constructor.getBody().addStatement(String.format(
          "this.%s = %s;", property.getFieldName(), property.getFieldName()));
    } else {
      constructor.getBody().addStatement(String.format(
          "this.%s = java.util.Objects.requireNonNull(%s, \"%s is required\");",
          property.getFieldName(), property.getFieldName(), property.name));
    }
  });

  properties.forEach(property -> {
    MethodDeclaration getter = classDecl.addMethod("get" + capitalize(property.name)).setPublic(true);
    getter.setType(property.getJavaType());
    if (property.description != null) {
      getter.setJavadocComment(property.description);
    }
    if (property.experimental) {
      getter.addAnnotation(Beta.class);
    }
    if (property.deprecated) {
      getter.addAnnotation(Deprecated.class);
    }
    getter.getBody().get().addStatement(String.format("return %s;", property.getFieldName()));
  });

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(capitalize(name));
  fromJson.addParameter(JsonInput.class, "input");
  BlockStmt body = fromJson.getBody().get();
  if (properties.size() > 0) {
    properties.forEach(property -> {
      if (property.optional) {
        body.addStatement(String.format("%s %s = java.util.Optional.empty();", property.getJavaType(), property.getFieldName()));
      } else {
        body.addStatement(String.format("%s %s = null;", property.getJavaType(), property.getFieldName()));
      }
    });

    body.addStatement("input.beginObject();");
    body.addStatement(
        "while (input.hasNext()) {"
        + "switch (input.nextName()) {"
        + properties.stream().map(property -> {
          String mapper = String.format(
            property.optional ? "java.util.Optional.ofNullable(%s)" : "%s",
            property.type.getMapper());

          return String.format(
            "case \"%s\":"
              + "  %s = %s;"
              + "  break;",
            property.name, property.getFieldName(), mapper);
        })
            .collect(joining("\n"))
        + "  default:\n"
        + "    input.skipValue();\n"
        + "    break;"
        + "}}");
    body.addStatement("input.endObject();");
    body.addStatement(String.format(
        "return new %s(%s);", capitalize(name),
        properties.stream().map(VariableSpec::getFieldName)
            .collect(joining(", "))));
  } else {
    body.addStatement(String.format("return new %s();", capitalize(name)));
  }

  return classDecl;
}
 
Example 15
Source File: LambdaSubProcessNodeVisitor.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Override
public void visitNode(String factoryField, SubProcessNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/class-templates/SubProcessFactoryTemplate.java");
    Optional<Expression> retValue = parse(resourceAsStream).findFirst(Expression.class);
    String name = node.getName();
    String subProcessId = node.getProcessId();

    NodeValidator.of(getNodeKey(), name)
            .notEmpty("subProcessId", subProcessId)
            .validate();


    body.addStatement(getAssignedFactoryMethod(factoryField, SubProcessNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "Call Activity"))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_PROCESS_ID, new StringLiteralExpr(subProcessId)))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_PROCESS_NAME, new StringLiteralExpr(getOrDefault(node.getProcessName(), ""))))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_WAIT_FOR_COMPLETION, new BooleanLiteralExpr(node.isWaitForCompletion())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_INDEPENDENT, new BooleanLiteralExpr(node.isIndependent())));

    Map<String, String> inputTypes = (Map<String, String>) node.getMetaData("BPMN.InputTypes");

    String subProcessModelClassName = ProcessToExecModelGenerator.extractModelClassName(subProcessId);
    ModelMetaData subProcessModel = new ModelMetaData(subProcessId,
            metadata.getPackageName(),
            subProcessModelClassName,
            WorkflowProcess.PRIVATE_VISIBILITY,
            VariableDeclarations.ofRawInfo(inputTypes),
            false);

    retValue.ifPresent(retValueExpression -> {
        retValueExpression.findAll(ClassOrInterfaceType.class)
                .stream()
                .filter(t -> t.getNameAsString().equals("$Type$"))
                .forEach(t -> t.setName(subProcessModelClassName));

        retValueExpression.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("bind"))
                .ifPresent(m -> m.setBody(bind(variableScope, node, subProcessModel)));
        retValueExpression.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("createInstance"))
                .ifPresent(m -> m.setBody(createInstance(node, metadata)));
        retValueExpression.findFirst(MethodDeclaration.class, m -> m.getNameAsString().equals("unbind"))
                .ifPresent(m -> m.setBody(unbind(variableScope, node)));
    });

    if (retValue.isPresent()) {
        body.addStatement(getFactoryMethod(getNodeId(node), getNodeKey(), retValue.get()));
    } else {
        body.addStatement(getFactoryMethod(getNodeId(node), getNodeKey()));
    }

    visitMetaData(node.getMetaData(), body, getNodeId(node));
    body.addStatement(getDoneMethod(getNodeId(node)));
}
 
Example 16
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public MethodDeclaration toMethodDeclaration() {
  MethodDeclaration methodDecl = new MethodDeclaration().setName(name).setPublic(true).setStatic(true);
  if (description != null) {
    methodDecl.setJavadocComment(description);
  }
  if (experimental) {
    methodDecl.addAnnotation(Beta.class);
  }
  if (deprecated) {
    methodDecl.addAnnotation(Deprecated.class);
  }

  methodDecl.setType(String.format("Command<%s>", type.getJavaType()));

  parameters.forEach(param -> {
    if (param.optional) {
      methodDecl.addParameter(String.format("java.util.Optional<%s>", param.type.getJavaType()), param.name);
    } else {
      methodDecl.addParameter(param.type.getJavaType(), param.name);
    }
  });

  BlockStmt body = methodDecl.getBody().get();

  parameters.stream().filter(parameter -> !parameter.optional)
      .map(parameter -> parameter.name)
      .forEach(name -> body.addStatement(
          String.format("java.util.Objects.requireNonNull(%s, \"%s is required\");", name, name)));
  body.addStatement("ImmutableMap.Builder<String, Object> params = ImmutableMap.builder();");
  parameters.forEach(parameter -> {
    if (parameter.optional) {
      body.addStatement(String.format("%s.ifPresent(p -> params.put(\"%s\", p));", parameter.name, parameter.name));
    } else {
      body.addStatement(String.format("params.put(\"%s\", %s);", parameter.name, parameter.name));
    }
  });

  if (type instanceof VoidType) {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build());", domain.name, name));
  } else if (type instanceof ObjectType) {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build(), input -> %s);",
        domain.name, name, type.getMapper()));
  } else {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build(), ConverterFunctions.map(\"%s\", %s));",
        domain.name, name, type.getName(), type.getTypeToken()));
  }

  return methodDecl;
}
 
Example 17
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 18
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 19
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 3 votes vote down vote up
/**
 * Generates something like
 * <code>return P_INDEX_UPDATER.compareAndSet(this, expectedValue, newValue)</code>
 *
 * @param fieldUpdaterFieldName
 * @param expectedValueName
 * @param newValueName
 * @return
 */
protected BlockStmt fieldUpdaterCompareAndSet(String fieldUpdaterFieldName, String expectedValueName,
        String newValueName) {
    BlockStmt body = new BlockStmt();
    body.addStatement(new ReturnStmt(methodCallExpr(fieldUpdaterFieldName, "compareAndSet", new ThisExpr(),
            new NameExpr(expectedValueName), new NameExpr(newValueName))));
    return body;
}
 
Example 20
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 3 votes vote down vote up
/**
 * Generates something like
 * <code>return P_INDEX_UPDATER.getAndSet(this, newValue)</code>
 *
 * @param fieldUpdaterFieldName
 * @param newValueName
 * @return
 */
private BlockStmt fieldUpdaterGetAndSet(String fieldUpdaterFieldName, String newValueName) {
    BlockStmt body = new BlockStmt();
    body.addStatement(new ReturnStmt(
            methodCallExpr(fieldUpdaterFieldName, "getAndSet", new ThisExpr(), new NameExpr(newValueName))));
    return body;
}