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

The following examples show how to use com.github.javaparser.ast.body.VariableDeclarator. 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: 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 2
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 3
Source Project: kogito-runtimes   Source File: RuleUnitMetaModel.java    License: Apache License 2.0 6 votes vote down vote up
public Statement injectCollection(
        String targetUnitVar, String sourceProcVar) {
    BlockStmt blockStmt = new BlockStmt();
    RuleUnitVariable v = ruleUnitDescription.getVar(targetUnitVar);
    String appendMethod = appendMethodOf(v.getType());
    blockStmt.addStatement(assignVar(v));
    blockStmt.addStatement(
            iterate(new VariableDeclarator()
                            .setType("Object").setName("it"),
                    new NameExpr(sourceProcVar))
                    .setBody(new ExpressionStmt(
                            new MethodCallExpr()
                                    .setScope(new NameExpr(localVarName(v)))
                                    .setName(appendMethod)
                                    .addArgument(new NameExpr("it")))));
    return blockStmt;
}
 
Example 4
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the field declaration map.
 *
 * @param <T> the generic type
 * @param node the class declaration
 * @param type the type
 * @return the field declaration map
 */
static <T extends BodyDeclaration> Map<String, T> getBodyDeclarationMap(Node node, Class<T> type) {
    List<Node> children = node.getChildNodes();
    if (CollectionUtil.isEmpty(children)) {
        return new HashMap<String, T>(0);
    }

    Map<String, T> bodyMap = new CaseInsensitiveHashMap<T>(children.size());

    List<T> bodyDeclarations = getNodesByType(node, type);

    for (T bodyDeclaration : bodyDeclarations) {
        if (bodyDeclaration instanceof FieldDeclaration) {
            FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration;
            VariableDeclarator variableDeclaratorId = getOneNodesByType(fieldDeclaration, VariableDeclarator.class);
            bodyMap.put(variableDeclaratorId.getName().toString(), bodyDeclaration);
        } else if (bodyDeclaration instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
            bodyMap.put(methodDeclaration.getNameAsString(), bodyDeclaration);
        }
    }
    return bodyMap;
}
 
Example 5
@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 6
@Override
public void visit(final VariableDeclarator n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    n.getName().accept(this, arg);

    Type commonType = n.getAncestorOfType(NodeWithVariables.class).get().getMaximumCommonType();

    Type type = n.getType();

    ArrayType arrayType = null;

    for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) {
        if (arrayType == null) {
            arrayType = (ArrayType) type;
        } else {
            arrayType = (ArrayType) arrayType.getComponentType();
        }
        printAnnotations(arrayType.getAnnotations(), true, arg);
        printer.print("[]");
    }

    if (n.getInitializer().isPresent()) {
        printer.print(" = ");
        n.getInitializer().get().accept(this, arg);
    }
}
 
Example 7
@Override
public void visit(final VariableDeclarationExpr n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printAnnotations(n.getAnnotations(), false, 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 v = i.next();
        v.accept(this, arg);
        if (i.hasNext()) {
            printer.print(", ");
        }
    }
}
 
Example 8
Source Project: Briefness   Source File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
                                     ClassName annotation) {
  String fieldName = variable.getNameAsString();
  String fieldValue = variable.getInitializer()
      .map(Node::toString)
      .orElseThrow(
          () -> new IllegalStateException("Field " + fieldName + " missing initializer"));
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
 
Example 9
@SuppressWarnings("try")
private static Location getFieldLocation(
    SearchContext context, File targetFile, FieldDeclaration declaration) throws IOException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("LocationSearcher.getFieldLocation")) {

    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("targetFile", targetFile.getPath()).build("args"));

    final List<VariableDeclarator> variables = declaration.getVariables();
    for (final VariableDeclarator variable : variables) {
      final SimpleName simpleName = variable.getName();
      final String name = simpleName.getIdentifier();
      final Optional<Position> begin = simpleName.getBegin();
      if (name.equals(context.name) && begin.isPresent()) {
        final Position position = begin.get();
        return new Location(targetFile.getCanonicalPath(), position.line, position.column);
      }
    }
    return null;
  }
}
 
Example 10
Source Project: state-machine   Source File: ImmutableBeanGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static void writeEquals(PrintStream s, Map<String, String> imports, String indent,
        ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) {
    s.format("\n\n%[email protected]%s", indent, resolve(imports, Override.class));
    s.format("\n%spublic boolean equals(Object o) {", indent);
    s.format("\n%s%sif (o == null) {", indent, indent);
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else if (!(o instanceof %s)) {", indent, indent, c.getName());
    s.format("\n%s%s%sreturn false;", indent, indent, indent);
    s.format("\n%s%s} else {", indent, indent);
    if (vars.isEmpty()) {
        s.format("\n%s%s%sreturn true;", indent, indent, indent);
    } else {
        s.format("\n%s%s%s%s other = (%s) o;", indent, indent, indent, c.getName(), c.getName());
        s.format("\n%s%s%sreturn", indent, indent, indent);
        String expression = vars.stream() ///
                .map(x -> String.format("%s.deepEquals(this.%s, other.%s)", //
                        resolve(imports, Objects.class), x.getName(), x.getName())) //
                .collect(Collectors.joining(String.format("\n%s%s%s%s&& ", indent, indent, indent, indent)));
        s.format("\n%s%s%s%s%s;", indent, indent, indent, indent, expression);
    }
    s.format("\n%s%s}", indent, indent);
    s.format("\n%s}", indent);
}
 
Example 11
Source Project: android-reverse-r   Source 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 12
@Override
public void visit(VariableDeclarator stmt, Void args) {
    if (!isValid) {
        return;
    }
    Optional<Expression> initializer = stmt.getInitializer();
    if (initializer.isPresent()) {
        String initString = initializer.get().toString();
        if (initString.startsWith("System.*") || initString.startsWith("Random.*") ||
                initString.contains("Thread")) {
            messages.add("Test contains an invalid variable declaration: " + initString);
            isValid = false;
        }
    }
    super.visit(stmt, args);
}
 
Example 13
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 14
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 15
@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 16
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateQueryMethods(CompilationUnit cu, ClassOrInterfaceDeclaration clazz, String returnType) {
    boolean hasDI = annotator != null;
    MethodDeclaration queryMethod = clazz.getMethodsByName("executeQuery").get(0);
    queryMethod.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    setGeneric(queryMethod.getType(), returnType);

    Statement statement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statement.findAll(VariableDeclarator.class).forEach(decl -> setUnitGeneric(decl.getType()));
    statement.findAll( MethodCallExpr.class ).forEach( m -> m.addArgument( hasDI ? "unitDTO" : "unitDTO.get()" ) );

    Statement returnStatement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnStatement.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    MethodDeclaration queryMethodSingle = clazz.getMethodsByName("executeQueryFirst").get(0);
    queryMethodSingle.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    queryMethodSingle.setType(toNonPrimitiveType(returnType));

    Statement statementSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statementSingle.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    Statement returnMethodSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnMethodSingle.findAll(VariableDeclarator.class).forEach(decl -> decl.setType(toNonPrimitiveType(returnType)));

    if (useMonitoring) {
        addMonitoringToResource(cu, new MethodDeclaration[]{queryMethod, queryMethodSingle}, endpointName);
    }
}
 
Example 17
Source Project: kogito-runtimes   Source 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   Source 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
@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
@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   Source 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: kogito-runtimes   Source File: ProcessContextMetaModel.java    License: Apache License 2.0 5 votes vote down vote up
public AssignExpr assignVariable(String procVar) {
    Expression e = getVariable(procVar);
    return new AssignExpr()
            .setTarget(new VariableDeclarationExpr(
                    new VariableDeclarator()
                            .setType(variableScope.findVariable(procVar).getType().getStringType())
                            .setName(procVar)))
            .setOperator(AssignExpr.Operator.ASSIGN)
            .setValue(e);
}
 
Example 23
Source Project: Recaf   Source File: SourceCodeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testNodeAtPos() {
	SourceCode code = resource.getClassSource("Start");
	// Line 7: Two tabs then this:
	//
	// Scanner scanner = new Scanner(System.in);
	//
	// First "Scanner" is an AST Tyoe
	Node node = code.getNodeAt(7, 5); // Scanner
	assertTrue(node instanceof ClassOrInterfaceType);
	assertEquals("Scanner", ((ClassOrInterfaceType)node).asString());
	// "scanner" is just a SimpleName, so we return the parent VariableDeclarator
	node = code.getNodeAt(7, 13); // scanner
	assertTrue(node instanceof VariableDeclarator);
	assertEquals("scanner", ((VariableDeclarator)node).getNameAsString());
	// Second "Scanner" is also an AST Type
	node = code.getNodeAt(7, 27); // Scanner
	assertTrue(node instanceof ClassOrInterfaceType);
	assertEquals("Scanner", ((ClassOrInterfaceType)node).asString());
	// "System.in" is a FieldAccessExpr
	// - "System" is a NameExpr - Field.scope
	// - "in" is a NameExpr - Field.name
	node = code.getNodeAt(7, 34); // System
	assertTrue(node instanceof FieldAccessExpr);
	assertTrue(((FieldAccessExpr)node).getScope() instanceof NameExpr);
	assertEquals("System", ((NameExpr)((FieldAccessExpr)node).getScope()).getNameAsString());
	assertEquals("in", ((FieldAccessExpr)node).getNameAsString());
}
 
Example 24
Source Project: TestSmellDetector   Source File: LazyTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(VariableDeclarator n, Void arg) {
    if (Objects.equals(fileType, TEST_FILE)) {
        if (productionClassName.equals(n.getType().asString())) {
            productionVariables.add(n.getNameAsString());
        }
    }
    super.visit(n, arg);
}
 
Example 25
Source Project: TestSmellDetector   Source File: EagerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(VariableDeclarator n, Void arg) {
    if (Objects.equals(fileType, TEST_FILE)) {
        if (productionClassName.equals(n.getType().asString())) {
            productionVariables.add(n.getNameAsString());
        }
    }
    super.visit(n, arg);
}
 
Example 26
@Override
public void visit(VariableDeclarationExpr n, Void arg) {
    if (currentMethod != null) {
        for (VariableDeclarator variableDeclarator : n.getVariables()) {
            if (variableDeclarator.getType().equals("File")) {
                methodVariables.add(variableDeclarator.getNameAsString());
            }
        }
    }
    super.visit(n, arg);
}
 
Example 27
@Override
public void visit(ObjectCreationExpr n, Void arg) {
    if (currentMethod != null) {
        if (n.getParentNode().isPresent()) {
            if (!(n.getParentNode().get() instanceof VariableDeclarator)) { // VariableDeclarator is handled in the override method
                if (n.getType().asString().equals("File")) {
                    hasSmell = true;
                }
            }
        }
    } else {
        System.out.println(n.getType());
    }
    super.visit(n, arg);
}
 
Example 28
@Override
public void visit(VariableDeclarator n, Void arg) {
    if (currentMethod != null) {
        if (n.getType().asString().equals("File")) {
            methodVariables.add(n.getNameAsString());
        }
    } else {
        if (n.getType().asString().equals("File")) {
            classVariables.add(n.getNameAsString());
        }
    }
    super.visit(n, arg);
}
 
Example 29
@Override
public void visit(FieldDeclaration n, Void arg) {
    for (VariableDeclarator variableDeclarator : n.getVariables()) {
        if (variableDeclarator.getType().equals("File")) {
            classVariables.add(variableDeclarator.getNameAsString());
        }
    }
    super.visit(n, arg);
}
 
Example 30
Source Project: jql   Source File: FieldIndexer.java    License: MIT License 5 votes vote down vote up
public void index(FieldDeclaration fieldDeclaration, int typeId) {
    List<VariableDeclarator> variables = fieldDeclaration.getVariables();
    for (VariableDeclarator variable : variables) {
        String name = variable.getNameAsString();
        fieldDao.save(new Field(name, fieldDeclaration.getElementType().asString(),
                fieldDeclaration.isPublic(), fieldDeclaration.isStatic(), fieldDeclaration.isFinal(), fieldDeclaration.isTransient(), typeId));
    }
}