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

The following examples show how to use com.github.javaparser.ast.body.ConstructorDeclaration. 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: Siamese   Author: UCL-CREST   File: JavaMethodParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visit(ConstructorDeclaration c, Object arg) {
    ArrayList<crest.siamese.document.Parameter> paramsList = new ArrayList<>();
    // do not include comments in the indexed code
    PrettyPrinterConfiguration ppc = new PrettyPrinterConfiguration();
    ppc.setPrintComments(false);
    ppc.setPrintJavaDoc(false);
    String comment = retrieveComments(c);
    int begin = -1;
    int end = -1;
    if (c.getBegin().isPresent()) begin = c.getBegin().get().line;
    if (c.getEnd().isPresent()) end = c.getEnd().get().line;
    methodList.add(createNewMethod(c.getName().asString(), comment, c.toString(ppc), begin,
            end, paramsList, c.getDeclarationAsString()));
    super.visit(c, arg);
}
 
Example #3
Source Project: dolphin   Author: beihaifeiwu   File: ConstructorDeclarationMerger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ConstructorDeclaration doMerge(ConstructorDeclaration first, ConstructorDeclaration second) {

  ConstructorDeclaration cd = new ConstructorDeclaration();

  cd.setName(first.getName());
  cd.setJavaDoc(mergeSingle(first.getJavaDoc(), second.getJavaDoc()));
  cd.setModifiers(mergeModifiers(first.getModifiers(), second.getModifiers()));
  cd.setAnnotations(mergeCollections(first.getAnnotations(), second.getAnnotations()));
  cd.setParameters(mergeCollectionsInOrder(first.getParameters(), second.getParameters()));
  cd.setTypeParameters(mergeCollectionsInOrder(first.getTypeParameters(), second.getTypeParameters()));

  cd.setThrows(mergeListNoDuplicate(first.getThrows(), second.getThrows(), false));
  cd.setBlock(mergeSingle(first.getBlock(), second.getBlock()));
  return cd;
}
 
Example #4
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 extractResultsFromConstructorDeclaration(ConstructorDeclaration cd, CodeAnalysisResult result) {
    // Constructors always have a body.
    int constructorBegin = cd.getBegin().get().line;
    int constructorBodyBegin = cd.getBody().getBegin().get().line;
    int constructorEnd = cd.getEnd().get().line;

    for (int line = constructorBegin; line <= constructorBodyBegin; line++) {
        // constructor signatures are non coverable
        result.nonCoverableCode(line);
    }

    String signature = cd.getDeclarationAsString(false, false, false);
    result.testAccordionMethodDescription(signature, constructorBegin, constructorEnd);

    result.methodSignatures(Range.between(constructorBegin, constructorBodyBegin));
    result.methods(Range.between(constructorBegin, constructorEnd));
}
 
Example #5
Source Project: selenium   Author: SeleniumHQ   File: CdpClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(String.format("return %s;", getMapper()));

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example #6
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example #7
Source Project: kogito-runtimes   Author: kiegroup   File: ProcessInstanceGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private ConstructorDeclaration constructorWithBusinessKeyDecl() {
    return new ConstructorDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(ProcessGenerator.processType(canonicalName), PROCESS)
            .addParameter(model.getModelClassSimpleName(), VALUE)
            .addParameter(String.class.getCanonicalName(), "businessKey")
            .addParameter(ProcessRuntime.class.getCanonicalName(), PROCESS_RUNTIME)
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr(PROCESS),
                    new NameExpr(VALUE),
                    new NameExpr("businessKey"),
                    new NameExpr(PROCESS_RUNTIME))));
}
 
Example #8
Source Project: kogito-runtimes   Author: kiegroup   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 #9
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 #10
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateConstructors(ClassOrInterfaceDeclaration clazz) {
    for (ConstructorDeclaration c : clazz.getConstructors()) {
        c.setName(targetCanonicalName);
        if (!c.getParameters().isEmpty()) {
            setUnitGeneric(c.getParameter(0).getType());
        }
    }
}
 
Example #11
Source Project: kogito-runtimes   Author: kiegroup   File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
    ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
    clazz.addMember(resultClass);

    ConstructorDeclaration constructor = resultClass.addConstructor(Modifier.Keyword.PUBLIC);
    BlockStmt constructorBody = constructor.createBody();

    ObjectCreationExpr resultCreation = new ObjectCreationExpr();
    resultCreation.setType("Result");
    BlockStmt resultMethodBody = toResultMethod.createBody();
    resultMethodBody.addStatement(new ReturnStmt(resultCreation));

    query.getBindings().forEach((name, type) -> {
        resultClass.addField(type, name, Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL);

        MethodDeclaration getterMethod = resultClass.addMethod("get" + ucFirst(name), Modifier.Keyword.PUBLIC);
        getterMethod.setType(type);
        BlockStmt body = getterMethod.createBody();
        body.addStatement(new ReturnStmt(new NameExpr(name)));

        constructor.addAndGetParameter(type, name);
        constructorBody.addStatement(new AssignExpr(new NameExpr("this." + name), new NameExpr(name), AssignExpr.Operator.ASSIGN));

        MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
        callExpr.addArgument(new StringLiteralExpr(name));
        resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
    });
}
 
Example #12
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void classDeclaration(ClassOrInterfaceDeclaration cls) {
    cls.setName(targetTypeName)
            .setModifiers(Modifier.Keyword.PUBLIC)
            .getExtendedTypes().get(0).setTypeArguments(nodeList(new ClassOrInterfaceType(null, typeName)));

    if (annotator != null) {
        annotator.withSingletonComponent(cls);
        cls.findFirst(ConstructorDeclaration.class, c -> !c.getParameters().isEmpty()) // non-empty constructor
                .ifPresent(annotator::withInjection);
    }

    String ruleUnitInstanceFQCN = RuleUnitInstanceGenerator.qualifiedName(packageName, typeName);
    cls.findAll(ConstructorDeclaration.class).forEach(this::setClassName);
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$InstanceName$"))
            .forEach(o -> o.setType(ruleUnitInstanceFQCN));
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$Application$"))
            .forEach(o -> o.setType(applicationPackageName + ".Application"));
    cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$RuleModelName$"))
            .forEach(o -> o.setType(packageName + "." + generatedSourceFile + "_" + typeName));
    cls.findAll(MethodDeclaration.class, m -> m.getType().asString().equals("$InstanceName$"))
            .stream()
            .map(m -> m.setType(ruleUnitInstanceFQCN))
            .flatMap(m -> m.getParameters().stream())
            .filter(p -> p.getType().asString().equals("$ModelName$"))
            .forEach(o -> o.setType(typeName));
    cls.findAll( MethodCallExpr.class).stream()
            .flatMap( mCall -> mCall.getArguments().stream() )
            .filter( e -> e.isNameExpr() && e.toNameExpr().get().getNameAsString().equals( "$ModelClass$" ) )
            .forEach( e -> e.toNameExpr().get().setName( typeName + ".class" ) );
    cls.findAll(TypeParameter.class)
            .forEach(tp -> tp.setName(typeName));
}
 
Example #13
Source Project: stategen   Author: stategen   File: PrettyPrintVisitor.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void visit(final ConstructorDeclaration n, final Void arg) {
    printJavaComment(n.getComment(), arg);
    printMemberAnnotations(n.getAnnotations(), arg);
    printModifiers(n.getModifiers());

    printTypeParameters(n.getTypeParameters(), arg);
    if (n.isGeneric()) {
        printer.print(" ");
    }
    n.getName().accept(this, arg);

    printer.print("(");
    if (!n.getParameters().isEmpty()) {
        for (final Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext(); ) {
            final Parameter p = i.next();
            p.accept(this, arg);
            if (i.hasNext()) {
                printer.print(", ");
            }
        }
    }
    printer.print(")");

    if (!isNullOrEmpty(n.getThrownExceptions())) {
        printer.print(" throws ");
        for (final Iterator<ReferenceType<?>> i = n.getThrownExceptions().iterator(); i.hasNext(); ) {
            final ReferenceType name = i.next();
            name.accept(this, arg);
            if (i.hasNext()) {
                printer.print(", ");
            }
        }
    }
    printer.print(" ");
    n.getBody().accept(this, arg);
}
 
Example #14
Source Project: TestSmellDetector   Author: TestSmells   File: ConstructorInitialization.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ConstructorDeclaration n, Void arg) {
    // This check is needed to handle java files that have multiple classes
    if(n.getNameAsString().equals(testFileName)) {
        if(!constructorAllowed) {
            testClass = new TestClass(n.getNameAsString());
            testClass.setHasSmell(true);
            smellyElementList.add(testClass);
        }
    }
}
 
Example #15
Source Project: meghanada-server   Author: mopemope   File: ParameterNameVisitor.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
  super.visit(n, arg);
  NodeList<Modifier> modifiers = n.getModifiers();
  if (!modifiers.contains(Modifier.privateModifier())) {
    final List<BodyDeclaration<?>> members = n.getMembers();
    final SimpleName simpleName = n.getName();
    final String clazz = simpleName.getId();
    // String clazz = n.getName();
    this.className = this.pkg + '.' + clazz;
    log.debug("class {}", this.className);
    int i = 0;
    for (final BodyDeclaration<?> body : members) {
      if (body instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) body;
        this.getParameterNames(methodDeclaration, n.isInterface());
        i++;
      } else if (body instanceof ConstructorDeclaration) {
        // Constructor
      } else if (body instanceof ClassOrInterfaceDeclaration) {
        final ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
            (ClassOrInterfaceDeclaration) body;
        String name = classOrInterfaceDeclaration.getName().getIdentifier();
        String key = this.pkg + '.' + name;
        name = this.originClassName + '.' + name;
        for (MethodParameterNames mpn : this.parameterNamesList) {
          if (mpn != null && mpn.className != null && mpn.className.equals(key)) {
            mpn.className = name;
          }
        }
      }
    }

    if (i > 0 && this.names.className != null) {
      this.parameterNamesList.add(this.names);
      this.names = new MethodParameterNames();
    }
  }
}
 
Example #16
Source Project: jql   Author: benas   File: ConstructorIndexer.java    License: MIT License 5 votes vote down vote up
public void index(ConstructorDeclaration constructorDeclaration, int typeId) {
    List<Parameter> parameters = constructorDeclaration.getParameters();
    String name = constructorDeclaration.getNameAsString();
    int methodId = methodDao.save(new Method(name,
            constructorDeclaration.isPublic(), constructorDeclaration.isStatic(), constructorDeclaration.isFinal(), constructorDeclaration.isAbstract(), true, typeId));
    for (Parameter parameter : parameters) {
        parameterIndexer.index(parameter, methodId);
    }
}
 
Example #17
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ConstructorDeclaration c, Object arg) {
    SimpleGroovyConstructorDoc meth = new SimpleGroovyConstructorDoc(c.getNameAsString(), currentClassDoc);
    setConstructorOrMethodCommon(c, meth);
    currentClassDoc.add(meth);
    super.visit(c, arg);
}
 
Example #18
Source Project: jeddict   Author: jeddict   File: JavaClassSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncConstructorSnippet(ConstructorDeclaration constructor, Map<String, ImportDeclaration> imports) {
    String signature
            = constructor.getParameters()
                    .stream()
                    .map(Parameter::getTypeAsString)
                    .collect(joining(", "));
    if (!javaClass.getConstructors()
            .stream()
            .filter(Constructor::isEnable)
            .filter(cot -> cot.getSignature().equals(signature))
            .findAny()
            .isPresent()) {
        syncClassSnippet(AFTER_FIELD, constructor.toString(), imports);
    }
}
 
Example #19
Source Project: CodeDefenders   Author: CodeDefenders   File: CodeValidator.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Set<String> extractMethodSignaturesByType(TypeDeclaration td) {
    Set<String> methodSignatures = new HashSet<>();
    // Method signatures in the class including constructors
    for (Object bd : td.getMembers()) {
        if (bd instanceof MethodDeclaration) {
            methodSignatures.add(((MethodDeclaration) bd).getDeclarationAsString());
        } else if (bd instanceof ConstructorDeclaration) {
            methodSignatures.add(((ConstructorDeclaration) bd).getDeclarationAsString());
        } else if (bd instanceof TypeDeclaration) {
            // Inner classes
            methodSignatures.addAll(extractMethodSignaturesByType((TypeDeclaration) bd));
        }
    }
    return methodSignatures;
}
 
Example #20
Source Project: JCTools   Author: JCTools   File: JavaParsingAtomicLinkedQueueGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ConstructorDeclaration n, Void arg) {
    super.visit(n, arg);
    // Update the ctor to match the class name
    n.setName(translateQueueName(n.getNameAsString()));
    if (MPSC_LINKED_ATOMIC_QUEUE_NAME.equals(n.getNameAsString())) {
        // Special case for MPSC because the Unsafe variant has a static factory method and a protected constructor.
        n.setModifier(Keyword.PROTECTED, false);
        n.setModifier(Keyword.PUBLIC, true);
    }
}
 
Example #21
Source Project: deadcode4j   Author: Scout24   File: TypeErasureAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ConstructorDeclaration n, A arg) {
    this.definedTypeParameters.addLast(getTypeParameterNames(n.getTypeParameters()));
    try {
        super.visit(n, arg);
    } finally {
        this.definedTypeParameters.removeLast();
    }
}
 
Example #22
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
/***************
 * Constructors
 *   - modify the 2 arg constructor - changing the args and the body
 * @param n - the constructor node
 * @param ignored -
 */
@Override
public void visit(ConstructorDeclaration n, Object ignored) {
  super.visit(n, ignored);  // processes the params 
  if (!isConvert2v3) {  // for enums, annotations
    return;
  }
  List<Parameter> ps = n.getParameters();
  
  if (ps.size() == 2 && 
      getParmTypeName(ps, 0).equals("int") &&
      getParmTypeName(ps, 1).equals("TOP_Type")) {
      
    /** public Foo(TypeImpl type, CASImpl casImpl) {
     *   super(type, casImpl);
     *   readObject();
     */
    setParameter(ps, 0, "TypeImpl", "type");
    setParameter(ps, 1, "CASImpl", "casImpl");
    
    // Body: change the 1st statement (must be super)
    NodeList<Statement> stmts = n.getBody().getStatements();
    if (!(stmts.get(0) instanceof ExplicitConstructorInvocationStmt)) {
      recordBadConstructor("missing super call");
      return;
    }
    NodeList<Expression> args = ((ExplicitConstructorInvocationStmt)(stmts.get(0))).getArguments();
    args.set(0, new NameExpr("type"));
    args.set(1,  new NameExpr("casImpl"));
   
    // leave the rest unchanged.
  }      
}
 
Example #23
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
private int findConstructor(NodeList<BodyDeclaration<?>> classMembers) {
  int i = 0;
  for (BodyDeclaration<?> bd : classMembers) {
    if (bd instanceof ConstructorDeclaration) {
      return i;
    }
    i++;
  }
  return -1;
}
 
Example #24
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Heuristic:
 *   JCas classes have 0, 1, and 2 arg constructors with particular arg types
 *   0 -
 *   1 - JCas
 *   2 - int, TOP_Type  (v2) or TypeImpl, CASImpl (v3)
 *   
 * Additional 1 and 2 arg constructors are permitted.
 * 
 * Sets fields hasV2Constructors, hasV3Constructors
 * @param members
 */
private void setHasJCasConstructors(NodeList<BodyDeclaration<?>> members) {
  boolean has0ArgConstructor = false;
  boolean has1ArgJCasConstructor = false;
  boolean has2ArgJCasConstructorV2 = false;
  boolean has2ArgJCasConstructorV3 = false;
  
  for (BodyDeclaration<?> bd : members) {
    if (bd instanceof ConstructorDeclaration) {
      List<Parameter> ps = ((ConstructorDeclaration)bd).getParameters();
      if (ps.size() == 0) has0ArgConstructor = true;
      if (ps.size() == 1 && getParmTypeName(ps, 0).equals("JCas")) {
        has1ArgJCasConstructor = true;
      }
      if (ps.size() == 2) {
        if (getParmTypeName(ps, 0).equals("int") &&
            getParmTypeName(ps, 1).equals("TOP_Type")) {
          has2ArgJCasConstructorV2 = true;
        } else if (getParmTypeName(ps, 0).equals("TypeImpl") &&
                   getParmTypeName(ps, 1).equals("CASImpl")) {
          has2ArgJCasConstructorV3 = true;
        }
      } // end of 2 arg constructor
    } // end of is-constructor
  } // end of for loop
  
  hasV2Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV2;
  hasV3Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV3;
}
 
Example #25
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitContainerGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ClassOrInterfaceDeclaration classDeclaration() {

    NodeList<BodyDeclaration<?>> declarations = new NodeList<>();

    // declare field `application`
    FieldDeclaration applicationFieldDeclaration = new FieldDeclaration();
    applicationFieldDeclaration
            .addVariable( new VariableDeclarator( new ClassOrInterfaceType(null, "Application"), "application") )
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(applicationFieldDeclaration);

    ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration("RuleUnits")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter( "Application", "application" )
            .setBody( new BlockStmt().addStatement( "this.application = application;" ) );
    declarations.add(constructorDeclaration);

    // declare field `ruleRuntimeBuilder`
    FieldDeclaration kieRuntimeFieldDeclaration = new FieldDeclaration();
    kieRuntimeFieldDeclaration
            .addVariable(new VariableDeclarator( new ClassOrInterfaceType(null, KieRuntimeBuilder.class.getCanonicalName()), "ruleRuntimeBuilder")
            .setInitializer(new ObjectCreationExpr().setType(ProjectSourceClass.PROJECT_RUNTIME_CLASS)))
            .setModifiers( Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL );
    declarations.add(kieRuntimeFieldDeclaration);

    // declare method ruleRuntimeBuilder()
    MethodDeclaration methodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("ruleRuntimeBuilder")
            .setType(KieRuntimeBuilder.class.getCanonicalName())
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new FieldAccessExpr(new ThisExpr(), "ruleRuntimeBuilder"))));
    declarations.add(methodDeclaration);

    declarations.addAll(factoryMethods);
    declarations.add(genericFactoryById());

    ClassOrInterfaceDeclaration cls = super.classDeclaration()
            .setMembers(declarations);

    cls.getMembers().sort(new BodyDeclarationComparator());

    return cls;
}
 
Example #26
Source Project: kogito-runtimes   Author: kiegroup   File: RuleUnitGenerator.java    License: Apache License 2.0 4 votes vote down vote up
private void setClassName(ConstructorDeclaration constructorDeclaration) {
    constructorDeclaration.setName(targetTypeName);
}
 
Example #27
Source Project: CodeDefenders   Author: CodeDefenders   File: ClassCodeAnalyser.java    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void visit(ConstructorDeclaration n, CodeAnalysisResult arg) {
    super.visit(n, arg);
    extractResultsFromConstructorDeclaration(n, arg);
}
 
Example #28
Source Project: selenium   Author: SeleniumHQ   File: CdpClientGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  if (type.equals("object")) {
    classDecl.addExtendedType("com.google.common.collect.ForwardingMap<String, Object>");
  }

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  if (type.equals("object")) {
    MethodDeclaration delegate = classDecl.addMethod("delegate").setProtected(true);
    delegate.setType("java.util.Map<String, Object>");
    delegate.getBody().get().addStatement(String.format("return %s;", propertyName));
  }

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(
      String.format("return new %s(%s);", name, getMapper()));

  MethodDeclaration toJson = classDecl.addMethod("toJson").setPublic(true);
  if (type.equals("object")) {
    toJson.setType("java.util.Map<String, Object>");
    toJson.getBody().get().addStatement(String.format("return %s;", propertyName));
  } else {
    toJson.setType(String.class);
    toJson.getBody().get().addStatement(String.format("return %s.toString();", propertyName));
  }

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example #29
Source Project: selenium   Author: SeleniumHQ   File: CdpClientGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(capitalize(name));

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

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

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

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

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

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

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

  return classDecl;
}
 
Example #30
Source Project: JCTools   Author: JCTools   File: TraceVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visit(ConstructorDeclaration n, Void arg) {
    out.println("ConstructorDeclaration: " + (extended ? n : n.getDeclarationAsString()));
    super.visit(n, arg);
}