Java Code Examples for com.github.javaparser.ast.type.ClassOrInterfaceType

The following examples show how to use com.github.javaparser.ast.type.ClassOrInterfaceType. 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   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration unbind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(model.fromMap("variables", "vmap"));

    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("unbind")
            .setType(new VoidType())
            .addParameter(modelName, "variables")
            .addParameter(new ClassOrInterfaceType()
                                  .setName("java.util.Map")
                                  .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                                    new ClassOrInterfaceType().setName("Object")),
                          "vmap")
            .setBody(body);
}
 
Example 2
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance")
            .addArgument(new NameExpr(BUSINESS_KEY))
            .addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 3
public ProcessesContainerGenerator(String packageName) {
    super("Processes", "processes", Processes.class);
    this.packageName = packageName;
    this.processes = new ArrayList<>();
    this.factoryMethods = new ArrayList<>();
    this.applicationDeclarations = new NodeList<>();

    byProcessIdMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processById")
            .setType(new ClassOrInterfaceType(null, org.kie.kogito.process.Process.class.getCanonicalName())
                             .setTypeArguments(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName()))))
            .setBody(new BlockStmt())
            .addParameter("String", "processId");

    processesMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processIds")
            .setType(new ClassOrInterfaceType(null, Collection.class.getCanonicalName())
                             .setTypeArguments(new ClassOrInterfaceType(null, "String")))
            .setBody(new BlockStmt());

    applicationDeclarations.add(byProcessIdMethodDeclaration);
    applicationDeclarations.add(processesMethodDeclaration);
}
 
Example 4
Source Project: kogito-runtimes   Source File: RuleUnitInstanceGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String canonicalName = ruleUnitDescription.getRuleUnitName();
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractRuleUnitInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, canonicalName)))
            .addConstructor(Modifier.Keyword.PUBLIC)
            .addParameter(RuleUnitGenerator.ruleUnitType(canonicalName), "unit")
            .addParameter(canonicalName, "value")
            .addParameter(KieSession.class.getCanonicalName(), "session")
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr("unit"),
                    new NameExpr("value"),
                    new NameExpr("session")
            )));
    classDecl.addMember(bindMethod());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example 5
Source Project: kogito-runtimes   Source File: RuleConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration relcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleEventListenerConfig.class), VAR_RULE_EVENT_LISTENER_CONFIGS)));
            members.add(relcFieldDeclaration);

            FieldDeclaration aelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), AgendaEventListener.class), VAR_AGENDA_EVENT_LISTENERS)));
            members.add(aelFieldDeclaration);

            FieldDeclaration rrelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleRuntimeEventListener.class), VAR_RULE_RUNTIME_EVENT_LISTENERS)));
            members.add(rrelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultRelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, RuleEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_RULE_EVENT_LISTENER_CONFIG, newObject(DefaultRuleEventListenerConfig.class)));
            members.add(defaultRelcFieldDeclaration);
        }

        return members;
    }
 
Example 6
Source Project: kogito-runtimes   Source File: DecisionConfigGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration delcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DecisionEventListenerConfig.class), VAR_DECISION_EVENT_LISTENER_CONFIG)));
            members.add(delcFieldDeclaration);

            FieldDeclaration drelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DMNRuntimeEventListener.class), VAR_DMN_RUNTIME_EVENT_LISTENERS)));
            members.add(drelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultDelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, DecisionEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_DECISION_EVENT_LISTENER_CONFIG, newObject(DefaultDecisionEventListenerConfig.class)));
            members.add(defaultDelcFieldDeclaration);
        }

        return members;
    }
 
Example 7
Source Project: kogito-runtimes   Source File: TriggerMetaData.java    License: Apache License 2.0 6 votes vote down vote up
public static LambdaExpr buildLambdaExpr(Node node, ProcessMetaData metadata) {
    Map<String, Object> nodeMetaData = node.getMetaData();
    TriggerMetaData triggerMetaData = new TriggerMetaData(
            (String) nodeMetaData.get(TRIGGER_REF),
            (String) nodeMetaData.get(TRIGGER_TYPE),
            (String) nodeMetaData.get(MESSAGE_TYPE),
            (String) nodeMetaData.get(MAPPING_VARIABLE),
            String.valueOf(node.getId()))
            .validate();
    metadata.getTriggers().add(triggerMetaData);

    // and add trigger action
    BlockStmt actionBody = new BlockStmt();
    CastExpr variable = new CastExpr(
            new ClassOrInterfaceType(null, triggerMetaData.getDataType()),
            new MethodCallExpr(new NameExpr(KCONTEXT_VAR), "getVariable")
                    .addArgument(new StringLiteralExpr(triggerMetaData.getModelRef())));
    MethodCallExpr producerMethodCall = new MethodCallExpr(new NameExpr("producer_" + node.getId()), "produce").addArgument(new MethodCallExpr(new NameExpr("kcontext"), "getProcessInstance")).addArgument(variable);
    actionBody.addStatement(producerMethodCall);
    return new LambdaExpr(
            new Parameter(new UnknownType(), KCONTEXT_VAR), // (kcontext) ->
            actionBody
    );
}
 
Example 8
Source Project: kogito-runtimes   Source 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 9
Source Project: sundrio   Source File: Sources.java    License: Apache License 2.0 6 votes vote down vote up
public TypeRef apply(Type type) {
    if (type instanceof VoidType) {
        return new VoidRef();
    } else if (type instanceof WildcardType) {
        return new WildcardRef();
    } else if (type instanceof ReferenceType) {
        ReferenceType referenceType = (ReferenceType) type;
        int dimensions = referenceType.getArrayCount();
        TypeRef typeRef = TYPEREF.apply(referenceType.getType());
        if (dimensions == 0) {
            return typeRef;
        } else if (typeRef instanceof ClassRef) {
            return new ClassRefBuilder((ClassRef)typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof PrimitiveRef) {
            return new PrimitiveRefBuilder((PrimitiveRef)typeRef).withDimensions(dimensions).build();
        } else if (typeRef instanceof TypeParamRef) {
            return new TypeParamRefBuilder((TypeParamRef)typeRef).withDimensions(dimensions).build();
        }
    } else if (type instanceof PrimitiveType) {
        PrimitiveType primitiveType = (PrimitiveType) type;
        return new PrimitiveRefBuilder().withName(primitiveType.getType().name()).build();
    } else if (type instanceof ClassOrInterfaceType) {
        return CLASS_OR_TYPEPARAM_REF.apply((ClassOrInterfaceType) type);
    }
    throw new IllegalArgumentException("Can't handle type:[" + type + "].");
}
 
Example 10
Source Project: kogito-runtimes   Source File: ForEachNodeVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visitNode(String factoryField, ForEachNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
    body.addStatement(getAssignedFactoryMethod(factoryField, ForEachNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
            .addStatement(getNameMethod(node, "ForEach"));
    visitMetaData(node.getMetaData(), body, getNodeId(node));

    body.addStatement(getFactoryMethod(getNodeId(node), METHOD_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getCollectionExpression()))))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE, new StringLiteralExpr(node.getVariableName()),
                    new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
                            new StringLiteralExpr(node.getVariableType().getStringType())
                    ))));

    if (node.getOutputCollectionExpression() != null) {
        body.addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getOutputCollectionExpression()))))
                .addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_VARIABLE, new StringLiteralExpr(node.getOutputVariableName()),
                        new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
                                new StringLiteralExpr(node.getOutputVariableType().getStringType())
                        ))));
    }
    // visit nodes
    visitNodes(getNodeId(node), node.getNodes(), body, ((VariableScope) node.getCompositeNode().getDefaultContext(VariableScope.VARIABLE_SCOPE)), metadata);
    body.addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_INCOMING_CONNECTIONS, new LongLiteralExpr(node.getLinkedIncomingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
            .addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_OUTGOING_CONNECTIONS, new LongLiteralExpr(node.getLinkedOutgoingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
            .addStatement(getDoneMethod(getNodeId(node)));

}
 
Example 11
@Override
public void visit(final ClassOrInterfaceType n, final Void arg) {
    printJavaComment(n.getComment(), arg);

    if (n.getScope().isPresent()) {
        n.getScope().get().accept(this, arg);
        printer.print(".");
    }
    for (AnnotationExpr ae : n.getAnnotations()) {
        ae.accept(this, arg);
        printer.print(" ");
    }

    n.getName().accept(this, arg);

    if (n.isUsingDiamondOperator()) {
        printer.print("<>");
    } else {
        printTypeArgs(n, arg);
    }
}
 
Example 12
@Override
public void visit(final TypeParameter n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    for (AnnotationExpr ann : n.getAnnotations()) {
        ann.accept(this, arg);
        printer.print(" ");
    }
    n.getName().accept(this, arg);
    if (!isNullOrEmpty(n.getTypeBound())) {
        printer.print(" extends ");
        for (final Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext(); ) {
            final ClassOrInterfaceType c = i.next();
            c.accept(this, arg);
            if (i.hasNext()) {
                printer.print(" & ");
            }
        }
    }
}
 
Example 13
Source Project: butterfly   Source File: Extends.java    License: MIT License 6 votes vote down vote up
@Override
protected String getTypeName(CompilationUnit compilationUnit, int index) {
    ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
    NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
    ClassOrInterfaceType extendedType = extendedTypes.get(index);
    String typeSimpleName = extendedType.getName().getIdentifier();
    Optional<ClassOrInterfaceType> scope = extendedType.getScope();
    String typeName;
    if (scope.isPresent()) {
        String typePackageName = scope.get().toString();
        typeName = String.format("%s.%s", typePackageName, typeSimpleName);
    } else {
        typeName = typeSimpleName;
    }
    return typeName;
}
 
Example 14
Source Project: jql   Source File: ImplementsRelationCalculator.java    License: MIT License 6 votes vote down vote up
public void calculate(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, CompilationUnit compilationUnit) {
    List<ClassOrInterfaceType> implementedInterfaces = classOrInterfaceDeclaration.getImplementedTypes();
    for (ClassOrInterfaceType implementedInterface : implementedInterfaces) {
        String implementedInterfaceName = implementedInterface.getNameAsString();
        String implementedInterfacePackageName = implementedInterface
                .findCompilationUnit()
                .flatMap(CompilationUnit::getPackageDeclaration)
                .flatMap(pkg -> Optional.of(pkg.getNameAsString())).orElse("???");
        if (typeDao.exist(implementedInterfaceName, implementedInterfacePackageName)) { // JDK interfaces are not indexed
            int interfaceId = typeDao.getId(implementedInterfaceName, implementedInterfacePackageName);
            String cuPackageName = compilationUnit.getPackageDeclaration().get().getNameAsString();
            int nbClasses = typeDao.count(classOrInterfaceDeclaration.getNameAsString(), cuPackageName);
            if (nbClasses > 1) {
                System.err.println("More than one class having the same name '" + classOrInterfaceDeclaration.getName() + "' and package '" + cuPackageName + "'");
            } else {
                int classId = typeDao.getId(classOrInterfaceDeclaration.getNameAsString(), cuPackageName);
                implementsDao.save(new Implements(classId, interfaceId));
            }
        }
    }
}
 
Example 15
Source Project: JRemapper   Source File: ParserTypeUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param type
 *            JavaParser type. Must be an object type.
 * @return Internal descriptor from type, assuming the type is available.
 */
private static String typeToDesc(Type type) {
	String key = null;
	if (type instanceof ClassOrInterfaceType) {
		try {
			key = ((ClassOrInterfaceType) type).resolve().getQualifiedName();
		} catch(Exception ex) { /* ignored */ }
	}
	if (key == null)
		key = type.asString();
	StringBuilder sbDesc = new StringBuilder();
	for (int i = 0; i < type.getArrayLevel(); i++)
		sbDesc.append("[");
	sbDesc.append("L");
	sbDesc.append(key.replace('.', '/'));
	sbDesc.append(";");
	return sbDesc.toString();
}
 
Example 16
Source Project: dolphin   Source File: TypeParameterMerger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean doIsEquals(TypeParameter first, TypeParameter second) {

    if(!StringUtils.equals(first.getName(),second.getName())) return false;

    List<ClassOrInterfaceType> firstTypeBounds = first.getTypeBound();
    List<ClassOrInterfaceType> secondTypeBounds = second.getTypeBound();

    if(firstTypeBounds == null) return secondTypeBounds == null;
    if(secondTypeBounds == null) return false;

    if(firstTypeBounds.size() != secondTypeBounds.size()) return false;

    AbstractMerger<ClassOrInterfaceType> merger = getMerger(ClassOrInterfaceType.class);

    for(int i = 0; i < firstTypeBounds.size(); i++){
        if(!merger.isEquals(firstTypeBounds.get(i),secondTypeBounds.get(i))){
            return false;
        }
    }

    return true;
}
 
Example 17
Source Project: kogito-runtimes   Source File: ConfigGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodCallExpr callMerge(String configsName, Class<?> configToListenersScope, String configToListenersIdentifier, String listenersName) {
    return new MethodCallExpr(null, "merge", NodeList.nodeList(
            new NameExpr(configsName),
            new MethodReferenceExpr(
                    new TypeExpr(new ClassOrInterfaceType(null, configToListenersScope.getCanonicalName())),
                    null,
                    configToListenersIdentifier
            ),
            new NameExpr(listenersName)
    ));
}
 
Example 18
Source Project: JCTools   Source File: JavaParsingAtomicQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean isRefType(Type in, String className) {
    // Does not check type parameters
    if (in instanceof ClassOrInterfaceType) {
        return (className.equals(((ClassOrInterfaceType) in).getNameAsString()));
    }
    return false;
}
 
Example 19
Source Project: JCTools   Source File: JavaParsingAtomicQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected ClassOrInterfaceType simpleParametricType(String className, String... typeArgs) {
    NodeList<Type> typeArguments = new NodeList<Type>();
    for (String typeArg : typeArgs) {
        typeArguments.add(classType(typeArg));
    }
    return new ClassOrInterfaceType(null, new SimpleName(className), typeArguments);
}
 
Example 20
Source Project: uima-uimaj   Source File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
private String getTypeName(Type t) {
//    if (t instanceof ReferenceType) {
//      t = ((ReferenceType<?>)t).getType();
//    }
    
    if (t instanceof PrimitiveType) {
      return ((PrimitiveType)t).toString(); 
    }
    if (t instanceof ClassOrInterfaceType) {
      return ((ClassOrInterfaceType)t).getNameAsString();
    }
    Misc.internalError(); return null;
  }
 
Example 21
Source Project: kogito-runtimes   Source File: CodegenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void interpolateTypes(ClassOrInterfaceType t, String dataClazzName) {
    SimpleName returnType = t.getName();
    Map<String, String> interpolatedTypes = new HashMap<>();
    interpolatedTypes.put("$Type$", dataClazzName);
    interpolateTypes(returnType, interpolatedTypes);
    t.getTypeArguments().ifPresent(ta -> interpolateTypeArguments(ta, interpolatedTypes));
}
 
Example 22
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractProcessInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, model.getModelClassSimpleName())))
            .addMember(constructorDecl())
            .addMember(constructorWithBusinessKeyDecl())
            .addMember(bind())
            .addMember(unbind());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example 23
Source Project: kogito-runtimes   Source File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration bind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(new ReturnStmt(model.toMap("variables")));
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("bind")
            .addParameter(modelName, "variables")
            .setType(new ClassOrInterfaceType()
                             .setName("java.util.Map")
                             .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                               new ClassOrInterfaceType().setName("Object")))
            .setBody(body);

}
 
Example 24
Source Project: JCTools   Source File: JavaParsingAtomicQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates something like
 * <code>private static final AtomicLongFieldUpdater<MpmcAtomicArrayQueueProducerIndexField> P_INDEX_UPDATER = AtomicLongFieldUpdater.newUpdater(MpmcAtomicArrayQueueProducerIndexField.class, "producerIndex");</code>
 *
 * @param className
 * @param variableName
 * @return
 */
protected FieldDeclaration declareLongFieldUpdater(String className, String variableName) {
    MethodCallExpr initializer = newAtomicLongFieldUpdater(className, variableName);

    ClassOrInterfaceType type = simpleParametricType("AtomicLongFieldUpdater", className);
    FieldDeclaration newField = fieldDeclarationWithInitialiser(type, fieldUpdaterFieldName(variableName),
            initializer, Keyword.PRIVATE, Keyword.STATIC, Keyword.FINAL);
    return newField;
}
 
Example 25
Source Project: kogito-runtimes   Source File: PersistenceGenerator.java    License: 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 26
Source Project: kogito-runtimes   Source File: MessageDataEventGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in MessageDataEventTemplate"));
    template.setName(resourceClazzName);  
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(ConstructorDeclaration.class).stream().forEach(cd -> cd.setName(resourceClazzName));

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 27
Source Project: kogito-runtimes   Source File: ProcessGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodDeclaration createInstanceGenericMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance").addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example 28
@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 29
private MethodDeclaration genericFactoryById() {
    ClassOrInterfaceType returnType = new ClassOrInterfaceType(null, RuleUnit.class.getCanonicalName())
            .setTypeArguments(new WildcardType());

    SwitchStmt switchStmt = new SwitchStmt();
    switchStmt.setSelector(new NameExpr("fqcn"));

    for (RuleUnitGenerator ruleUnit : ruleUnits) {
        SwitchEntry switchEntry = new SwitchEntry();
        switchEntry.getLabels().add(new StringLiteralExpr(ruleUnit.getRuleUnitDescription().getCanonicalName()));
        ObjectCreationExpr ruleUnitConstructor = new ObjectCreationExpr()
                .setType(ruleUnit.targetCanonicalName())
                .addArgument("application");
        switchEntry.getStatements().add(new ReturnStmt(ruleUnitConstructor));
        switchStmt.getEntries().add(switchEntry);
    }

    SwitchEntry defaultEntry = new SwitchEntry();
    defaultEntry.getStatements().add(new ThrowStmt(new ObjectCreationExpr().setType(UnsupportedOperationException.class.getCanonicalName())));
    switchStmt.getEntries().add(defaultEntry);

    return new MethodDeclaration()
            .addModifier(Modifier.Keyword.PROTECTED)
            .setType(returnType)
            .setName("create")
            .addParameter(String.class, "fqcn")
            .setBody(new BlockStmt().addStatement(switchStmt));
}
 
Example 30
/**
 * Searches all extended or implemented super classes or interfaces for
 * special classes that differ with the atomics version and replaces them
 * with the appropriate class.
 */
private void replaceParentClassesForAtomics(ClassOrInterfaceDeclaration n) {
    for (ClassOrInterfaceType parent : n.getExtendedTypes()) {
        if ("ConcurrentCircularArrayQueue".equals(parent.getNameAsString())) {
            parent.setName("AtomicReferenceArrayQueue");
        } else if ("ConcurrentSequencedCircularArrayQueue".equals(parent.getNameAsString())) {
            parent.setName("SequencedAtomicReferenceArrayQueue");
        } else {
            // Padded super classes are to be renamed and thus so does the
            // class we must extend.
            parent.setName(translateQueueName(parent.getNameAsString()));
        }
    }
}