Java Code Examples for com.github.javaparser.ast.body.FieldDeclaration

The following examples show how to use com.github.javaparser.ast.body.FieldDeclaration. 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: BodyDeclarationComparator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int compare(BodyDeclaration<?> o1, BodyDeclaration<?> o2) {
    if (o1 instanceof FieldDeclaration && o2 instanceof FieldDeclaration) {
        return 0;
    }
    if (o1 instanceof FieldDeclaration && !(o2 instanceof FieldDeclaration)) {
        return -1;
    }
    
    if (o1 instanceof ConstructorDeclaration && o2 instanceof ConstructorDeclaration) {
        return 0;
    }
    if (o1 instanceof ConstructorDeclaration && o2 instanceof MethodDeclaration) {
        return -1;
    }
    if (o1 instanceof ConstructorDeclaration && o2 instanceof FieldDeclaration) {
        return 1;
    }
    return 1;
}
 
Example #2
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessesContainerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CompilationUnit injectableClass() {
    CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream(RESOURCE)).setPackageDeclaration(packageName);                        
    ClassOrInterfaceDeclaration cls = compilationUnit
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));
    
    cls.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("processes")).forEach(fd -> {
        annotator.withInjection(fd);
        fd.getVariable(0).setType(new ClassOrInterfaceType(null, new SimpleName(annotator.multiInstanceInjectionType()), 
                                                           NodeList.nodeList(new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName())))))));
    });
    
    annotator.withApplicationComponent(cls);
    
    return compilationUnit;
}
 
Example #3
Source Project: kogito-runtimes   Author: kiegroup   File: IncrementalRuleCodegen.java    License: Apache License 2.0 6 votes vote down vote up
private void generateSessionUnits( List<org.kie.kogito.codegen.GeneratedFile> generatedFiles ) {
    for (KieBaseModel kBaseModel : kieModuleModel.getKieBaseModels().values()) {
        for (String sessionName : kBaseModel.getKieSessionModels().keySet()) {
            CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) );
            ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get();
            annotator.withNamedSingletonComponent(template, "$SessionName$");
            template.setName( "SessionRuleUnit_" + sessionName );

            template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd));

            template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) );
            generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile(
                    org.kie.kogito.codegen.GeneratedFile.Type.RULE,
                    "org/drools/project/model/SessionRuleUnit_" + sessionName + ".java",
                    log( cu.toString() ) ));
        }
    }
}
 
Example #4
Source Project: kogito-runtimes   Author: kiegroup   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 #5
Source Project: kogito-runtimes   Author: kiegroup   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 #6
Source Project: CodeDefenders   Author: CodeDefenders   File: ClassCodeAnalyser.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void extractResultsFromFieldDeclaration(FieldDeclaration f, CodeAnalysisResult result) {
    final boolean compileTimeConstant = f.isFinal() && ((f.getCommonType() instanceof PrimitiveType) || (String.class.getSimpleName().equals(f.getElementType().asString())));
    for (VariableDeclarator v : f.getVariables()) {
        for (int line = v.getBegin().get().line; line <= v.getEnd().get().line; line++) {
            if (compileTimeConstant) {
                logger.debug("Found compile-time constant " + v);
                // compile time targets are non coverable, too
                result.compileTimeConstant(line);
                result.nonCoverableCode(line);
            }
            if (!v.getInitializer().isPresent()) {
                // non initialized fields are non coverable
                result.nonInitializedField(line);
                result.nonCoverableCode(line);
            }
        }
    }
}
 
Example #7
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 FieldDeclaration n, final Void arg) {
    printOrphanCommentsBeforeThisChildNode(n);

    printJavaComment(n.getComment(), arg);
    printMemberAnnotations(n.getAnnotations(), arg);
    printModifiers(n.getModifiers());
    if (!n.getVariables().isEmpty()) {
        n.getMaximumCommonType().accept(this, arg);
    }

    printer.print(" ");
    for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) {
        final VariableDeclarator var = i.next();
        var.accept(this, arg);
        if (i.hasNext()) {
            printer.print(", ");
        }
    }

    printer.print(";");
}
 
Example #8
Source Project: Briefness   Author: hacknife   File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addResourceType(List<String> supportedTypes, TypeSpec.Builder result,
                                    ClassOrInterfaceDeclaration node, boolean useLegacyTypes) {
  if (!supportedTypes.contains(node.getNameAsString())) {
    return;
  }

  String type = node.getNameAsString();
  TypeSpec.Builder resourceType = TypeSpec.classBuilder(type)
      .addModifiers(PUBLIC, STATIC, FINAL);

  for (BodyDeclaration field : node.getMembers()) {
    if (field instanceof FieldDeclaration) {
      FieldDeclaration declaration = (FieldDeclaration) field;
      // Check that the field is an Int because styleable also contains Int arrays which can't be
      // used in annotations.
      if (isInt(declaration)) {
        addResourceField(resourceType, declaration.getVariables().get(0),
                getSupportAnnotationClass(type, useLegacyTypes));
      }
    }
  }

  result.addType(resourceType.build());
}
 
Example #9
Source Project: enkan   Author: kawasima   File: EntitySourceAnalyzer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public List<EntityField> analyze(File source) throws IOException, ParseException {
    List<EntityField> entityFields = new ArrayList<>();
    CompilationUnit cu = JavaParser.parse(source);
    cu.accept(new VoidVisitorAdapter<List<EntityField>>() {
        @Override
        public void visit(FieldDeclaration fd, List<EntityField> f) {
            if (fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Column"))) {
                Class<?> type = null;
                switch (fd.getType().toString()) {
                    case "String": type = String.class; break;
                    case "Long": type = Long.class; break;
                    case "Integer": type = Integer.class; break;
                    case "boolean": type = boolean.class; break;
                }
                if (type == null) return;
                f.add(new EntityField(
                        fd.getVariables().get(0).getId().getName(),
                        type,
                        fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Id"))));
            }
        }
    }, entityFields);

    return entityFields;
}
 
Example #10
Source Project: android-reverse-r   Author: justingarrick   File: Reverser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration clazz, Object arg) {
    for (BodyDeclaration member : clazz.getMembers()) {
        if (member instanceof ClassOrInterfaceDeclaration)
            visit((ClassOrInterfaceDeclaration)member, arg);
        else if (member instanceof FieldDeclaration) {
            FieldDeclaration field = (FieldDeclaration)member;
            String type = null != field.getType() ? field.getType().toString() : "";
            if (type.equals("int")) {
                VariableDeclarator variable = field.getVariables().stream().findFirst().get();
                String name = variable.getId().toString();
                Integer value = null != variable.getInit() ? Integer.parseInt(variable.getInit().toString()) : 0;
                // decimal value of 0x7f000000, which is what AAPT starts numbering at - https://stackoverflow.com/questions/6517151/how-does-the-mapping-between-android-resources-and-resources-id-work/6646113#6646113
                if (value >= 2130706432) {
                    name = "R." + ((ClassOrInterfaceDeclaration)field.getParentNode()).getName() + "." + name;
                    transform.put(value, name);
                }
            }
        }
    }
}
 
Example #11
Source Project: kogito-runtimes   Author: kiegroup   File: MessageProducerGenerator.java    License: 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 #12
Source Project: kogito-runtimes   Author: kiegroup   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 #13
Source Project: JCTools   Author: JCTools   File: JavaParsingAtomicLinkedQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates something like
 * <code>private static final AtomicReferenceFieldUpdater<MpmcAtomicArrayQueueProducerNodeField> P_NODE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(MpmcAtomicArrayQueueProducerNodeField.class, "producerNode");</code>
 *
 * @param className
 * @param variableName
 * @return
 */
private FieldDeclaration declareRefFieldUpdater(String className, String variableName) {
    MethodCallExpr initializer = newAtomicRefFieldUpdater(className, variableName);

    ClassOrInterfaceType type = simpleParametricType("AtomicReferenceFieldUpdater", className,
            "LinkedQueueAtomicNode");
    FieldDeclaration newField = fieldDeclarationWithInitialiser(type, fieldUpdaterFieldName(variableName),
            initializer, Keyword.PRIVATE, Keyword.STATIC, Keyword.FINAL);
    return newField;
}
 
Example #14
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 #15
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/RestQueryTemplate.java"));
    cu.setPackageDeclaration(query.getNamespace());

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

    cu.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);

    FieldDeclaration ruleUnitDeclaration = clazz
            .getFieldByName("ruleUnit")
            .orElseThrow(() -> new NoSuchElementException("ClassOrInterfaceDeclaration doesn't contain a field named ruleUnit!"));
    setUnitGeneric(ruleUnitDeclaration.getElementType());
    if (annotator != null) {
        annotator.withInjection(ruleUnitDeclaration);
    }

    String returnType = getReturnType(clazz);
    generateConstructors(clazz);
    generateQueryMethods(cu, clazz, returnType);
    clazz.getMembers().sort(new BodyDeclarationComparator());
    return cu.toString();
}
 
Example #16
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitDTOSourceClass.java    License: 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 #17
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitDTOSourceClass.java    License: Apache License 2.0 5 votes vote down vote up
private FieldDeclaration createField() {
    Type type = toQueryType();

    VariableDeclarator variableDeclarator = new VariableDeclarator(type, ruleUnitVariable.getName());
    if (isDataSource && !isSingletonStore) {
        variableDeclarator.setInitializer("java.util.Collections.emptyList()");
    }

    return new FieldDeclaration()
            .setModifiers(Modifier.Keyword.PRIVATE)
            .addVariable(variableDeclarator);
}
 
Example #18
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitPojoGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ClassOrInterfaceDeclaration classOrInterfaceDeclaration() {
    ClassOrInterfaceDeclaration c =
            new ClassOrInterfaceDeclaration()
                    .setPublic(true)
                    .addImplementedType(RuleUnitData.class.getCanonicalName())
                    .setName(ruleUnitDescription.getSimpleName());

    for (RuleUnitVariable v : ruleUnitDescription.getUnitVarDeclarations()) {
        ClassOrInterfaceType t = new ClassOrInterfaceType()
                .setName(v.getType().getCanonicalName());
        FieldDeclaration f = new FieldDeclaration();
        VariableDeclarator vd = new VariableDeclarator(t, v.getName());
        f.getVariables().add(vd);
        if (v.isDataSource()) {
            t.setTypeArguments( StaticJavaParser.parseType( v.getDataSourceParameterType().getCanonicalName() ) );
            if (ruleUnitHelper.isAssignableFrom(DataStore.class, v.getType())) {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createStore()");
            } else {
                vd.setInitializer("org.kie.kogito.rules.DataSource.createSingleton()");
            }
        }
        c.addMember(f);
        f.createGetter();
        if (v.setter() != null) {
            f.createSetter();
        }
    }

    return c;
}
 
Example #19
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 #20
Source Project: kogito-runtimes   Author: kiegroup   File: AbstractApplicationSection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FieldDeclaration fieldDeclaration() {
    ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr().setType( sectionClassName );
    if (useApplication()) {
        objectCreationExpr.addArgument( "this" );
    }
    return new FieldDeclaration()
            .addVariable(
                    new VariableDeclarator()
                            .setType( sectionClassName )
                            .setName(methodName)
                            .setInitializer(objectCreationExpr) );
}
 
Example #21
Source Project: kogito-runtimes   Author: kiegroup   File: ModelMetaData.java    License: Apache License 2.0 5 votes vote down vote up
private FieldDeclaration declareField(String name, String type) {
    return new FieldDeclaration().addVariable(
            new VariableDeclarator()
                    .setType(type)
                    .setName(name))
            .addModifier(Modifier.Keyword.PRIVATE);
}
 
Example #22
Source Project: stategen   Author: stategen   File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the field map.
 *
 * @param node the node
 * @return the field map
 */
static Map<String, String> getFieldMap(Node node) {
    Map<String, String> fieldmap = null;
    Map<String, FieldDeclaration> fieldDeclarationMap = getBodyDeclarationMap(node, FieldDeclaration.class);
    if (fieldDeclarationMap != null) {
        fieldmap = new CaseInsensitiveHashMap<String>(fieldDeclarationMap.size());
        for (String oldFieldName : fieldDeclarationMap.keySet()) {
            fieldmap.put(oldFieldName, oldFieldName);
        }
    }
    return fieldmap;
}
 
Example #23
Source Project: chrome-devtools-java-client   Author: kklisura   File: JavaClassBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds annotation to field.
 *
 * @param name Field name. Could not be in correct format.
 * @param annotationName Annotation name.
 */
@Override
public void addFieldAnnotation(String name, String annotationName) {
  Optional<FieldDeclaration> fieldDeclaration = declaration.getFieldByName(getFieldName(name));
  if (fieldDeclaration.isPresent()) {
    MarkerAnnotationExpr annotationExpr = new MarkerAnnotationExpr();
    annotationExpr.setName(annotationName);
    fieldDeclaration.get().addAnnotation(annotationExpr);

    importAnnotation(annotationName);
  } else {
    throw new RuntimeException("Field " + name + " is not present in current class.");
  }
}
 
Example #24
Source Project: chrome-devtools-java-client   Author: kklisura   File: JavaClassBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void generateGettersAndSetters() {
  List<FieldDeclaration> fields = declaration.getFields();
  for (FieldDeclaration fieldDeclaration : fields) {
    String fieldName = fieldDeclaration.getVariables().get(0).getNameAsString();

    setMethodJavadoc(fieldName, fieldDeclaration.createGetter());
    setMethodJavadoc(fieldName, fieldDeclaration.createSetter());
  }
}
 
Example #25
Source Project: apigcc   Author: apigcc   File: CommentHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 解析属性的注释
 * @param it
 * @return
 */
public static Optional<Comment> getComment(ResolvedFieldDeclaration it) {
    if (it instanceof JavaParserFieldDeclaration) {
        FieldDeclaration wrappedNode = ((JavaParserFieldDeclaration) it).getWrappedNode();
        return wrappedNode.getComment();
    }
    if (it instanceof JavaParserClassDeclaration) {
        JavaParserClassDeclaration classDeclaration = (JavaParserClassDeclaration) it;
        return classDeclaration.getWrappedNode().getComment();
    }
    return Optional.empty();
}
 
Example #26
Source Project: apigcc   Author: apigcc   File: ValidationHelper.java    License: MIT License 5 votes vote down vote up
public static List<String> getValidations(ResolvedFieldDeclaration declaredField) {
    List<String> result = new ArrayList<>();
    if (declaredField instanceof JavaParserFieldDeclaration) {
        FieldDeclaration fieldDeclaration = ((JavaParserFieldDeclaration) declaredField).getWrappedNode();
        for (String value : values) {
            Optional<AnnotationExpr> optional = fieldDeclaration.getAnnotationByName(value);
            if (optional.isPresent()) {
                result.add(value);
            }
        }
    }
    return result;
}
 
Example #27
Source Project: apigcc   Author: apigcc   File: JsonPropertyHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 获取Json 别名
 *
 * @param declaredField
 * @return
 */
public static Optional<String> getJsonName(ResolvedFieldDeclaration declaredField) {
    if (declaredField instanceof JavaParserFieldDeclaration) {
        FieldDeclaration fieldDeclaration = ((JavaParserFieldDeclaration) declaredField).getWrappedNode();
        return OptionalHelper.any(
                AnnotationHelper.string(fieldDeclaration, ANNOTATION_JSON_PROPERTY, "value"),
                AnnotationHelper.string(fieldDeclaration, ANNOTATION_JSON_FIELD, "name"),
                AnnotationHelper.string(fieldDeclaration, ANNOTATION_SERIALIZED_NAME, "value")
        );
    }
    return Optional.empty();
}
 
Example #28
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: ReorderModifier.java    License: MIT License 5 votes vote down vote up
/**
 * Reorder modifiers of a given field or method to comply with the JLS
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	String filepath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	FileInputStream in = new FileInputStream(filepath);
	CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in));

	FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(issue.getLine(), compilationUnit);
	MethodDeclaration method = RefactoringHelper.getMethodDeclarationByLineNumber(issue.getLine(),
			compilationUnit);
	boolean isModifierListUnchanged = false;
	NodeList<Modifier> modifiersInCorrectOrder;
	if (field != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(field.getModifiers());
		isModifierListUnchanged = field.getModifiers().equals(modifiersInCorrectOrder);
		field.setModifiers(new NodeList<Modifier>());
		field.setModifiers(modifiersInCorrectOrder);
	} else if (method != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(method.getModifiers());
		isModifierListUnchanged = method.getModifiers().equals(modifiersInCorrectOrder);
		method.setModifiers(new NodeList<Modifier>());
		method.setModifiers(modifiersInCorrectOrder);
	} else {
		throw new BotRefactoringException("Could not find method or field declaration at the given line!");
	}

	if (isModifierListUnchanged) {
		throw new BotRefactoringException("All modifiers are in correct order! Nothing to refactor.");
	}

	// Save changes to file
	PrintWriter out = new PrintWriter(filepath);
	out.println(LexicalPreservingPrinter.print(compilationUnit));
	out.close();

	// Return commit message
	return "Reordered modifiers to comply with the Java Language Specification";
}
 
Example #29
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: RefactoringHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Finds a field declaration in a compilation unit that starts at the specified
 * line number
 * 
 * @param lineNumber
 * @param cu
 * @return FieldDeclaration or null if none found
 */
public static FieldDeclaration getFieldDeclarationByLineNumber(int lineNumber, CompilationUnit cu) {
	FieldDeclaration result = null;
	List<FieldDeclaration> fields = cu.findAll(FieldDeclaration.class);
	for (FieldDeclaration field : fields) {
		if (isFieldDeclarationAtLine(field, lineNumber)) {
			result = field;
		}
	}
	return result;
}
 
Example #30
Source Project: Refactoring-Bot   Author: Refactoring-Bot   File: ReorderModifiersTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testReorderFieldModifiers() throws Exception {
	// arrange
	int lineNumber = TestDataClassReorderModifiers.lineNumberOfFieldWithStaticAndFinalInWrongOrder;

	// act
	File tempFile = performReorderModifiers(lineNumber);

	// assert
	FileInputStream in = new FileInputStream(tempFile);
	CompilationUnit cu = StaticJavaParser.parse(in);
	FieldDeclaration fieldDeclarationAfterRefactoring = RefactoringHelper
			.getFieldDeclarationByLineNumber(lineNumber, cu);
	assertAllModifiersInCorrectOrder(fieldDeclarationAfterRefactoring.getModifiers());
}