com.github.javaparser.ast.body.TypeDeclaration Java Examples

The following examples show how to use com.github.javaparser.ast.body.TypeDeclaration. 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: AnnotatedClassPostProcessor.java    License: Apache License 2.0 6 votes vote down vote up
String generate() {
    String imports = unitClass.getImports().stream()
            .map(i -> String.format(
                    "import %s %s;",
                    (i.isStatic() ? "static" : ""),
                    i.getName()))
            .collect(joining("\n"));
    TypeDeclaration<?> typeDeclaration = unitClass.getPrimaryType()
            .orElseThrow(() -> new IllegalArgumentException("Java class should have a primary type"));
    String rules = typeDeclaration.getMethods().stream()
            .filter(m -> m.getParameters().stream().flatMap(p -> p.getAnnotations().stream()).anyMatch(a -> a.getNameAsString().endsWith("When")))
            .map(this::generateRule).collect(joining());
    String drl = String.format(

            "package %s;\n" +
                    "unit %s;\n" +
                    "%s\n" +
                    "%s\n",

            packageName(), // package
            typeDeclaration.getName(),
            imports,
            rules);
    return drl;
}
 
Example #2
Source Project: kogito-runtimes   Author: kiegroup   File: ApplicationGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void compilationUnitWithFactoryMethods() {
    final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, new File("target"));
    final String testMethodName = "testMethod";
    final MethodDeclaration methodDeclaration = new MethodDeclaration();
    methodDeclaration.setName(testMethodName);

    appGenerator.addFactoryMethods(Collections.singleton(methodDeclaration));

    final CompilationUnit compilationUnit = appGenerator.compilationUnit();
    assertCompilationUnit(compilationUnit, false, 5);

    final TypeDeclaration mainAppClass = compilationUnit.getTypes().get(0);
    assertThat(mainAppClass.getMembers())
            .filteredOn(member -> member instanceof MethodDeclaration
                    && ((MethodDeclaration) member).getName().toString().equals(testMethodName))
            .hasSize(1);
}
 
Example #3
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 CompilationUnit n, final Void arg) {
    printJavaComment(n.getComment(), arg);

    if (n.getPackageDeclaration().isPresent()) {
        n.getPackageDeclaration().get().accept(this, arg);
    }

    n.getImports().accept(this, arg);
    if (!n.getImports().isEmpty()) {
        printer.println();
    }

    for (final Iterator<TypeDeclaration<?>> i = n.getTypes().iterator(); i.hasNext(); ) {
        i.next().accept(this, arg);
        printer.println();
        if (i.hasNext()) {
            printer.println();
        }
    }

    n.getModule().ifPresent(m -> m.accept(this, arg));

    printOrphanCommentsEnding(n);
}
 
Example #4
Source Project: Briefness   Author: hacknife   File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception {
  CompilationUnit compilationUnit = JavaParser.parse(rFile);
  TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

  TypeSpec.Builder result = TypeSpec.classBuilder(className)
      .addModifiers(PUBLIC, FINAL);

  for (Node node : resourceClass.getChildNodes()) {
    if (node instanceof ClassOrInterfaceDeclaration) {
      addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes);
    }
  }

  JavaFile finalR = JavaFile.builder(packageName, result.build())
      .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
      .build();

  finalR.writeTo(outputDir);
}
 
Example #5
Source Project: groovy   Author: apache   File: GroovydocJavaVisitor.java    License: Apache License 2.0 6 votes vote down vote up
private SimpleGroovyClassDoc visit(TypeDeclaration<?> n) {
    SimpleGroovyClassDoc parent = null;
    List<String> imports = getImports();
    String name = n.getNameAsString();
    if (n.isNestedType()) {
        parent = currentClassDoc;
        name = parent.name() + "$" + name;
    }
    currentClassDoc = new SimpleGroovyClassDoc(imports, aliases, name.replace('$', '.'), links);
    NodeList<Modifier> mods = n.getModifiers();
    if (parent != null) {
        parent.addNested(currentClassDoc);
        if (parent.isInterface()) {
            // an inner interface/class within an interface is public
            mods.add(Modifier.publicModifier());
        }
    }
    setModifiers(mods, currentClassDoc);
    processAnnotations(currentClassDoc, n);
    currentClassDoc.setFullPathName(withSlashes(packagePath + FS + name));
    classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc);
    n.getJavadocComment().ifPresent(javadocComment ->
            currentClassDoc.setRawCommentText(javadocComment.getContent()));
    return parent;
}
 
Example #6
Source Project: dolphin   Author: beihaifeiwu   File: CompilationUnitMerger.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean doIsEquals(CompilationUnit first, CompilationUnit second) {
  // 检测包声明
  if (!isEqualsUseMerger(first.getPackage(), second.getPackage())) return false;

  // 检查公共类声明
  for (TypeDeclaration outer : first.getTypes()) {
    for (TypeDeclaration inner : second.getTypes()) {
      if (ModifierSet.isPublic(outer.getModifiers()) && ModifierSet.isPublic(inner.getModifiers())) {
        if (outer.getName().equals(inner.getName())) {
          return true;
        }
      }
    }
  }

  return false;
}
 
Example #7
Source Project: flow   Author: vaadin   File: OpenApiObjectGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private Schema createSingleSchema(String fullQualifiedName,
        TypeDeclaration<?> typeDeclaration) {
    Optional<String> description = typeDeclaration.getJavadoc()
            .map(javadoc -> javadoc.getDescription().toText());
    Schema schema = new ObjectSchema();
    schema.setName(fullQualifiedName);
    description.ifPresent(schema::setDescription);
    Map<String, Schema> properties = getPropertiesFromClassDeclaration(
            typeDeclaration);
    schema.properties(properties);
    List<String> requiredList = properties.entrySet().stream()
            .filter(stringSchemaEntry -> GeneratorUtils
                    .isNotTrue(stringSchemaEntry.getValue().getNullable()))
            .map(Map.Entry::getKey).collect(Collectors.toList());
    // Nullable is represented in requiredList instead.
    properties.values()
            .forEach(propertySchema -> propertySchema.nullable(null));
    schema.setRequired(requiredList);
    return schema;
}
 
Example #8
Source Project: selenium   Author: SeleniumHQ   File: CdpClientGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  TypeDeclaration<?> typeDeclaration =
      type instanceof VoidType
      ? new ClassOrInterfaceDeclaration().setName(capitalize(name)).setPublic(true)
      : type.toTypeDeclaration().setPublic(true);

  if (description != null) {
    typeDeclaration.setJavadocComment(description);
  }
  if (experimental) {
    typeDeclaration.addAnnotation(Beta.class.getCanonicalName());
  }
  if (deprecated) {
    typeDeclaration.addAnnotation(Deprecated.class.getCanonicalName());
  }

  return typeDeclaration;
}
 
Example #9
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 #10
Source Project: butterfly   Author: paypal   File: Extends.java    License: MIT License 5 votes vote down vote up
@Override
protected int getNumberOfTypes(CompilationUnit compilationUnit) {
    TypeDeclaration<?> typeDeclaration = compilationUnit.getType(0);
    if (typeDeclaration instanceof ClassOrInterfaceDeclaration) {
        ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
        NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes();
        return extendedTypes.size();
    }

    // If typeDeclaration is not ClassOrInterfaceDeclaration, then it is
    // EnumDeclaration or AnnotationDeclaration, and none of them have
    // a getExtendedTypes operation

    return 0;
}
 
Example #11
Source Project: Recaf   Author: Col-E   File: SourceCode.java    License: MIT License 5 votes vote down vote up
/**
 * @return Class name.
 */
public String getName() {
	if (simpleName != null)
		return simpleName;
	// fetch declared name (Should be same as source file name)
	TypeDeclaration<?> type = unit.getType(0);
	if(type != null)
		return simpleName = type.getNameAsString();
	throw new IllegalStateException("Failed to fetch type from source file: " + code);
}
 
Example #12
Source Project: jql   Author: benas   File: CompilationUnitIndexer.java    License: MIT License 5 votes vote down vote up
public void index(com.github.javaparser.ast.CompilationUnit compilationUnit, String fileName) {
    String packageName = compilationUnit.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse("");
    io.github.benas.jql.model.CompilationUnit cu = new io.github.benas.jql.model.CompilationUnit(fileName, packageName);
    int cuId =  compilationUnitDao.save(cu);
    List<TypeDeclaration<?>> types = compilationUnit.getTypes();
    for (TypeDeclaration<?> type : types) {
        typeIndexer.index(type, cuId);
    }
}
 
Example #13
Source Project: jql   Author: benas   File: RelationCalculator.java    License: MIT License 5 votes vote down vote up
public void calculateRelations(Collection<File> files) {
    System.out.println();
    int totalFiles = files.size();
    int fileIndex = 1;
    for (File file : files) {
        try {
            CompilationUnit cu = parse(file);
            NodeList<TypeDeclaration<?>> types = cu.getTypes();
            for (TypeDeclaration<?> type : types) {
                boolean isInterface = type instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) type).isInterface();
                boolean isAnnotation = type instanceof AnnotationDeclaration;
                boolean isEnumeration = type instanceof EnumDeclaration;
                boolean isClass = !isAnnotation && !isEnumeration && !isInterface;
                if (isInterface) {
                    // check if this interface extends another interface and persist relation in EXTENDS table
                    ClassOrInterfaceDeclaration interfaceDeclaration = (ClassOrInterfaceDeclaration) type;
                    extendsRelationCalculator.calculate(interfaceDeclaration, cu);
                }
                if (isClass) {
                    ClassOrInterfaceDeclaration classDeclaration = (ClassOrInterfaceDeclaration) type;
                    // check if this class implements an interface and persist relation in IMPLEMENTS table
                    implementsRelationCalculator.calculate(classDeclaration, cu);
                    // check if this class extends another class and persist relation in EXTENDS table
                    extendsRelationCalculator.calculate(classDeclaration, cu);
                }
                if (isClass || isInterface) {
                    annotatedWithCalculator.calculate((ClassOrInterfaceDeclaration) type, cu);
                }
            }
        } catch (ParseProblemException | IOException e) {
            System.err.println("Error while parsing " + file.getAbsolutePath());
        }
        System.out.print("\rCalculating relations: " + getPercent(fileIndex, totalFiles) + "% " + ("(" + fileIndex + "/" + totalFiles + ")"));
        fileIndex++;
    }
    System.out.println();
}
 
Example #14
Source Project: flow   Author: vaadin   File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<TypeDeclaration<?>> appendNestedClasses(
        ClassOrInterfaceDeclaration topLevelClass) {
    Set<TypeDeclaration<?>> nestedClasses = topLevelClass
            .getMembers().stream()
            .filter(bodyDeclaration -> bodyDeclaration.isClassOrInterfaceDeclaration()
                    || bodyDeclaration.isEnumDeclaration())
            .map(bodyDeclaration -> (TypeDeclaration<?>) bodyDeclaration.asTypeDeclaration())
            .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator
                    .comparing(NodeWithSimpleName::getNameAsString))));
    nestedClasses.add(topLevelClass);
    return nestedClasses;
}
 
Example #15
Source Project: flow   Author: vaadin   File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void parseClass(TypeDeclaration<?> typeDeclaration,
        CompilationUnit compilationUnit) {
    if (typeDeclaration.isClassOrInterfaceDeclaration()) {
        parseClass(typeDeclaration.asClassOrInterfaceDeclaration(), compilationUnit);
    } else if (typeDeclaration.isEnumDeclaration()) {
        EnumDeclaration enumDeclaration = typeDeclaration.asEnumDeclaration();
        compilationUnit.getStorage().ifPresent(storage -> {
            String className = enumDeclaration.getFullyQualifiedName()
                    .orElse(enumDeclaration.getNameAsString());
            qualifiedNameToPath.put(className, storage.getPath().toString());
        });
        nonEndpointMap.put(enumDeclaration.resolve().getQualifiedName(),
                enumDeclaration);
    }
}
 
Example #16
Source Project: flow   Author: vaadin   File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private List<Schema> parseNonEndpointClassAsSchema(
        String fullQualifiedName) {
    TypeDeclaration<?> typeDeclaration = nonEndpointMap.get(fullQualifiedName);
    if (typeDeclaration == null || typeDeclaration.isEnumDeclaration()) {
        return Collections.emptyList();
    }
    List<Schema> result = new ArrayList<>();

    Schema schema = createSingleSchema(fullQualifiedName, typeDeclaration);
    generatedSchema.add(fullQualifiedName);

    NodeList<ClassOrInterfaceType> extendedTypes = null;
    if (typeDeclaration.isClassOrInterfaceDeclaration()) {
        extendedTypes = typeDeclaration.asClassOrInterfaceDeclaration()
                .getExtendedTypes();
    }
    if (extendedTypes == null || extendedTypes.isEmpty()) {
        result.add(schema);
        result.addAll(generatedRelatedSchemas(schema));
    } else {
        ComposedSchema parentSchema = new ComposedSchema();
        parentSchema.setName(fullQualifiedName);
        result.add(parentSchema);
        extendedTypes.forEach(parentType -> {
            ResolvedReferenceType resolvedParentType = parentType.resolve();
            String parentQualifiedName = resolvedParentType
                    .getQualifiedName();
            String parentRef = schemaResolver
                    .getFullQualifiedNameRef(parentQualifiedName);
            parentSchema.addAllOfItem(new ObjectSchema().$ref(parentRef));
            schemaResolver.addFoundTypes(parentQualifiedName,
                    resolvedParentType);
        });
        // The inserting order matters for `allof` property.
        parentSchema.addAllOfItem(schema);
        result.addAll(generatedRelatedSchemas(parentSchema));
    }
    return result;
}
 
Example #17
Source Project: flow   Author: vaadin   File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Schema> getPropertiesFromClassDeclaration(
        TypeDeclaration<?> typeDeclaration) {
    Map<String, Schema> properties = new TreeMap<>();
    for (FieldDeclaration field : typeDeclaration.getFields()) {
        if (field.isTransient() || field.isStatic()
                || field.isAnnotationPresent(JsonIgnore.class)) {
            continue;
        }
        Optional<String> fieldDescription = field.getJavadoc()
                .map(javadoc -> javadoc.getDescription().toText());
        field.getVariables().forEach(variableDeclarator -> {
            Schema propertySchema = parseTypeToSchema(
                    variableDeclarator.getType(),
                    fieldDescription.orElse(""));
            if (field.isAnnotationPresent(Nullable.class)
                    || GeneratorUtils.isTrue(propertySchema.getNullable())) {
                // Temporarily set nullable to indicate this property is
                // not required
                propertySchema.setNullable(true);
            }
            addFieldAnnotationsToSchema(field, propertySchema);
            properties.put(variableDeclarator.getNameAsString(),
                    propertySchema);
        });
    }
    return properties;
}
 
Example #18
Source Project: sundrio   Author: sundrio   File: PareserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testParser() throws Exception {

    CompilationUnit cu = Sources.FROM_CLASSPATH_TO_COMPILATIONUNIT.apply("io/sundr/builder/BaseFluent.java");
    String packageName = cu.getPackage().getPackageName();
    Assert.assertEquals("io.sundr.builder", packageName);

    for (TypeDeclaration typeDeclaration : cu.getTypes()) {
        TypeDef typeDef = Sources.TYPEDEF.apply(typeDeclaration);
        System.out.print(typeDef);
    }
}
 
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 Map<String, EnumSet> extractTypeDeclaration(TypeDeclaration td ){
    Map<String, EnumSet> typeData = new HashMap<>();
    typeData.put( td.getNameAsString(), td.getModifiers());
    // Inspect if this type declares inner classes
    for (Object bd : td.getMembers()) {
        if (bd instanceof TypeDeclaration) {
            // Handle Inner classes - recursively
            typeData.putAll(extractTypeDeclaration((TypeDeclaration) bd));
        }
    }
    return typeData;
}
 
Example #20
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 #21
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> extractFieldNamesByType(TypeDeclaration td) {
    Set<String> fieldNames = new HashSet<>();

    // Method signatures in the class including constructors
    for ( Object bd : td.getMembers()) {
        if (bd instanceof FieldDeclaration) {
            for (VariableDeclarator vd : ((FieldDeclaration) bd).getVariables()) {
                fieldNames.add(vd.getNameAsString());
            }
        } else if (bd instanceof TypeDeclaration) {
            fieldNames.addAll(extractFieldNamesByType((TypeDeclaration) bd));
        }
    }
    return fieldNames;
}
 
Example #22
Source Project: deadcode4j   Author: Scout24   File: Nodes.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getTypeName(@Nonnull Node node) {
    List<Node> anonymousClasses = newArrayList();
    StringBuilder buffy = new StringBuilder();
    Node loopNode = node;
    for (; ; ) {
        if (ObjectCreationExpr.class.isInstance(loopNode)) {
            if (!isEmpty(ObjectCreationExpr.class.cast(loopNode).getAnonymousClassBody())) {
                anonymousClasses.add(loopNode);
            }
        } else if (TypeDeclarationStmt.class.isInstance(loopNode)) {
            anonymousClasses.add(loopNode);
        } else if (TypeDeclaration.class.isInstance(loopNode)
                && !TypeDeclarationStmt.class.isInstance(loopNode.getParentNode())) {
            TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode);
            prependSeparatorIfNecessary('$', buffy).insert(0, typeDeclaration.getName());
            appendAnonymousClasses(anonymousClasses, typeDeclaration, buffy);
        } else if (CompilationUnit.class.isInstance(loopNode)) {
            if (buffy.length() == 0) {
                buffy.append("package-info");
            }
            final CompilationUnit compilationUnit = CompilationUnit.class.cast(loopNode);
            if (compilationUnit.getPackage() != null) {
                prepend(compilationUnit.getPackage().getName(), buffy);
            }
        }
        loopNode = loopNode.getParentNode();
        if (loopNode == null) {
            return buffy.toString();
        }
    }
}
 
Example #23
Source Project: deadcode4j   Author: Scout24   File: JavaFileAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Optional<String> apply(@Nonnull Qualifier<?> typeReference) {
    Qualifier firstQualifier = typeReference.getFirstQualifier();
    for (Node loopNode = typeReference.getNode(); ; ) {
        Optional<String> reference;
        if (TypeDeclaration.class.isInstance(loopNode)) {
            TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode);
            reference = resolveInnerReference(firstQualifier, singleton(typeDeclaration));
            if (reference.isPresent()) {
                return reference;
            }
            reference = resolveInnerReference(firstQualifier, typeDeclaration.getMembers());
            if (reference.isPresent()) {
                return reference;
            }
        } else if (CompilationUnit.class.isInstance(loopNode)) {
            reference = resolveInnerReference(firstQualifier, CompilationUnit.class.cast(loopNode).getTypes());
            if (reference.isPresent()) {
                return reference;
            }
        }
        loopNode = loopNode.getParentNode();
        if (loopNode == null) {
            return absent();
        }
    }
}
 
Example #24
Source Project: deadcode4j   Author: Scout24   File: JavaFileAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private Optional<String> resolveInnerReference(
        @Nonnull Qualifier firstQualifier,
        @Nullable Iterable<? extends BodyDeclaration> bodyDeclarations) {
    for (TypeDeclaration typeDeclaration : emptyIfNull(bodyDeclarations).filter(TypeDeclaration.class)) {
        if (firstQualifier.getName().equals(typeDeclaration.getName())) {
            return of(resolveReferencedType(firstQualifier, typeDeclaration));
        }
    }
    return absent();
}
 
Example #25
Source Project: deadcode4j   Author: Scout24   File: JavaFileAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private String resolveReferencedType(@Nonnull Qualifier qualifier, @Nonnull TypeDeclaration type) {
    Qualifier parentQualifier = qualifier.getParentQualifier();
    if (parentQualifier != null) {
        for (TypeDeclaration innerType : emptyIfNull(type.getMembers()).filter(TypeDeclaration.class)) {
            if (parentQualifier.getName().equals(innerType.getName())) {
                return resolveReferencedType(parentQualifier, innerType);
            }
        }
    }

    return getTypeName(type);
}
 
Example #26
Source Project: uima-uimaj   Author: apache   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
/**
   * Called on Annotation Decl, Class/intfc decl, empty type decl, enum decl
   * Does nothing unless at top level of compilation unit
   * 
   * Otherwise, adds an entry to c2ps for the classname and package, plus full path
   * 
   * @param n type being declared
   */
  private void updateClassName(TypeDeclaration<?> n) {
    Optional<Node> pnode = n.getParentNode();
    Node node;
    if (pnode.isPresent() && 
        (node = pnode.get()) instanceof CompilationUnit) {
      CompilationUnit cu2 = (CompilationUnit) node;
      className = cu2.getType(0).getNameAsString();
      String packageAndClassName = 
          (className.contains(".")) 
            ? className 
            : packageName + '.' + className;
      packageAndClassNameSlash = packageAndClassName.replace('.', '/');
//      assert current_cc.fqcn_slash == null;  // for decompiling, already set
      assert (current_cc.fqcn_slash != null) ? current_cc.fqcn_slash.equals(packageAndClassNameSlash) : true;
      current_cc.fqcn_slash = packageAndClassNameSlash;
      
      TypeImpl ti = TypeSystemImpl.staticTsi.getType(Misc.javaClassName2UimaTypeName(packageAndClassName));
      if (null != ti) {
        // is a built-in type
//        ContainerAndPath p = new ContainerAndPath(
//            current_path,
//            current_container,packageAndClassNameSlash, 
//            current_cc., 
//            current_cc.pearClasspath);
        skippedBuiltins.add(new PathContainerAndReason(current_path, current_container, "built-in"));
        isBuiltinJCas = true;
        isConvert2v3 = false;
        return;  
      } else {
        VariableDeclarator vd_typename = new VariableDeclarator(
            stringType, "_TypeName", new StringLiteralExpr(packageAndClassName));
        fi_fields.add(new FieldDeclaration(public_static_final, vd_typename));
      }

      return;
    }
    return;
  }
 
Example #27
Source Project: mapper-generator-javafx   Author: alansun2   File: MyShellCallback.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * merge java bean
 *
 * @param newCompilationUnit      新的
 * @param existingCompilationUnit 旧的
 * @return merge 后的
 */
private String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {

    Optional<PackageDeclaration> newPackageDeclaration = newCompilationUnit.getPackageDeclaration();
    newPackageDeclaration.ifPresent(existingCompilationUnit::setPackageDeclaration);

    //合并imports
    NodeList<ImportDeclaration> oldImports = existingCompilationUnit.getImports();
    NodeList<ImportDeclaration> newImports = newCompilationUnit.getImports();
    oldImports.addAll(newImports);
    Set<ImportDeclaration> importSet = new HashSet<>(oldImports);

    existingCompilationUnit.setImports(new NodeList<>(importSet));

    //处理类 comment
    TypeDeclaration<?> newType = newCompilationUnit.getTypes().get(0);
    TypeDeclaration<?> existType = existingCompilationUnit.getTypes().get(0);
    newType.getComment().ifPresent(existType::setComment);

    List<FieldDeclaration> existFields = existType.getFields();
    List<FieldDeclaration> newFields = newType.getFields();

    //合并fields
    int size = newFields.size();
    for (int i = 0; i < size; i++) {
        FieldDeclaration existField = newFields.get(0);
        VariableDeclarator existVar = existField.getVariables().get(0);
        for (FieldDeclaration newField : existFields) {
            VariableDeclarator newVar = newField.getVariables().get(0);
            // 名称相同
            if (newVar.getName().equals(existVar.getName())) {
                // 名称相同 且 类型相同
                if (newVar.getTypeAsString().equals(existVar.getTypeAsString())) {
                    newType.getComment().ifPresent(existType::setComment);
                } else {

                }
            }
        }

        //合并methods
    }

    return existingCompilationUnit.toString();
}
 
Example #28
Source Project: kogito-runtimes   Author: kiegroup   File: ApplicationGeneratorTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void generateWithOtherGenerator() throws IOException {
    final Generator mockGenerator = Mockito.mock(Generator.class);

    ApplicationSection appSection = new ApplicationSection() {

        private ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
                new ClassOrInterfaceDeclaration().setName("Foo");
        private MethodDeclaration methodDeclaration =
                new MethodDeclaration().setType("void");
        private FieldDeclaration fieldDeclaration =
                new FieldDeclaration().addVariable(new VariableDeclarator().setType(int.class).setName("i"));

        @Override
        public String sectionClassName() {
            return "Foo";
        }

        @Override
        public FieldDeclaration fieldDeclaration() {
            return fieldDeclaration;
        }

        @Override
        public MethodDeclaration factoryMethod() {
            return methodDeclaration;
        }

        @Override
        public ClassOrInterfaceDeclaration classDeclaration() {
            return classOrInterfaceDeclaration;
        }
    };

    when(mockGenerator.section()).thenReturn(appSection);

    final GeneratedFile generatedFile = mock(GeneratedFile.class);
    when(generatedFile.getType()).thenReturn(GeneratedFile.Type.RULE);
    final Collection<GeneratedFile> mockFiles = Collections.singleton(generatedFile);
    when(mockGenerator.generate()).thenReturn(mockFiles);

    final Map<String, String> mockLabels = new HashMap<>();
    mockLabels.put("testKey", "testValue");
    when(mockGenerator.getLabels()).thenReturn(mockLabels);

    final ApplicationGenerator appGenerator = new ApplicationGenerator(PACKAGE_NAME, new File("target/classes"));
    appGenerator.withGenerator(mockGenerator);

    final Collection<GeneratedFile> generatedFiles = appGenerator.generate();
    final CompilationUnit compilationUnit = appGenerator.compilationUnit();
    assertGeneratedFiles(generatedFiles, compilationUnit.toString().getBytes(StandardCharsets.UTF_8), 4);

    assertCompilationUnit(compilationUnit, false, 6);
    final TypeDeclaration mainAppClass = compilationUnit.getTypes().get(0);
    assertThat(mainAppClass.getMembers()).filteredOn(member -> member == appSection.factoryMethod()).hasSize(1);
    assertThat(mainAppClass.getMembers()).filteredOn(member -> member == appSection.classDeclaration()).hasSize(0);

    assertImageMetadata(Paths.get("target/classes"), mockLabels);
}
 
Example #29
Source Project: kogito-runtimes   Author: kiegroup   File: ApplicationGeneratorTest.java    License: Apache License 2.0 4 votes vote down vote up
private void assertCompilationUnit(final CompilationUnit compilationUnit, final boolean checkCDI,
                                   final int expectedNumberOfCustomFactoryMethods) {
    assertThat(compilationUnit).isNotNull();

    assertThat(compilationUnit.getPackageDeclaration()).isPresent();
    assertThat(compilationUnit.getPackageDeclaration().get().getName().toString()).isEqualTo(PACKAGE_NAME);

    assertThat(compilationUnit.getImports()).isNotNull();
    assertThat(compilationUnit.getImports()).hasSize(2);
    assertThat(compilationUnit.getImports().get(0).getName().toString()).isEqualTo(Config.class.getCanonicalName());

    assertThat(compilationUnit.getTypes()).isNotNull();
    assertThat(compilationUnit.getTypes()).hasSize(1);

    final TypeDeclaration mainAppClass = compilationUnit.getTypes().get(0);
    assertThat(mainAppClass).isNotNull();
    assertThat(mainAppClass.getName().toString()).isEqualTo("Application");

    if (checkCDI) {
        assertThat(mainAppClass.getAnnotations()).isNotEmpty();
        assertThat(mainAppClass.getAnnotationByName("Singleton")).isPresent();
    } else {
        assertThat(mainAppClass.getAnnotationByName("Singleton")).isNotPresent();
    }

    assertThat(mainAppClass.getMembers()).isNotNull();
    assertThat(mainAppClass.getMembers()).hasSize(2 + expectedNumberOfCustomFactoryMethods);

    assertThat(mainAppClass.getMembers())
            .filteredOn(member -> member instanceof MethodDeclaration
                    && ((MethodDeclaration) member).getName().toString().equals("config")
                    && !((MethodDeclaration) member).isStatic())
            .hasSize(1);

    assertThat(mainAppClass.getMembers())
            .filteredOn(member -> member instanceof FieldDeclaration
                    && ((FieldDeclaration) member).getVariable(0).getName().toString().equals("config")
                    && ((FieldDeclaration) member).isStatic())
            .hasSize(0);

    assertThat(mainAppClass.getMember(0)).isInstanceOfAny(MethodDeclaration.class, FieldDeclaration.class);
    assertThat(mainAppClass.getMember(1)).isInstanceOfAny(MethodDeclaration.class, FieldDeclaration.class);
}
 
Example #30
Source Project: jeddict   Author: jeddict   File: JavaClassSyncHandler.java    License: Apache License 2.0 4 votes vote down vote up
private void syncClassOrInterfaceOrEnumSnippet(TypeDeclaration<?> type, Map<String, ImportDeclaration> imports) {
    if (!javaClass.getSnippets(AFTER_CLASS).isEmpty()) {
        return;
    }
    syncClassSnippet(AFTER_CLASS, type.toString(), imports);
}