Java Code Examples for com.github.javaparser.ast.ImportDeclaration

The following examples show how to use com.github.javaparser.ast.ImportDeclaration. 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: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addBlankImports(List<ImportDeclaration> imports, CompilationUnit nowCompilationUnit) {
    String lastStartWith = null;
    int size = imports.size();
    for (int i = size - 1; i >= 0; i--) {
        ImportDeclaration importDeclaration = imports.get(i);
        String importName = importDeclaration.getName().toString();
        int idx = importName.indexOf('.');
        if (idx > 0) {
            String nowStrartWith = importName.substring(0, idx + 1);
            if (lastStartWith != null && !lastStartWith.equals(nowStrartWith)) {
                Range range = new Range(Position.pos(0, 0), Position.pos(0, 0));
                ImportDeclaration emptyDeclaration = new ImportDeclaration(range, new Name(), false, false);
                imports.add(i + 1, emptyDeclaration);
                lastStartWith = null;
            } else {
                lastStartWith = nowStrartWith;
            }
        }
    }
}
 
Example 2
@Override
public void visit(final ImportDeclaration n, final Void arg) {
    boolean isEmpty = "empty".equals(n.getNameAsString());
    if (!isEmpty){
        printJavaComment(n.getComment(), arg);
        printer.print("import ");
        if (n.isStatic()) {
            printer.print("static ");
        }
        n.getName().accept(this, arg);
        if (n.isAsterisk()) {
            printer.print(".*");
        }
        printer.println(";");
    } else {
        printer.println("");
    }

    printOrphanCommentsEnding(n);
}
 
Example 3
Source Project: dolphin   Source File: JavaSourceUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String mergeContent(CompilationUnit one, CompilationUnit two) throws Exception {

        // 包声明不同,返回null
        if (!one.getPackage().equals(two.getPackage())) return null;

        CompilationUnit cu = new CompilationUnit();

        // add package declaration to the compilation unit
        PackageDeclaration pd = new PackageDeclaration();
        pd.setName(one.getPackage().getName());
        cu.setPackage(pd);

        // check and merge file comment;
        Comment fileComment = mergeSelective(one.getComment(), two.getComment());
        cu.setComment(fileComment);

        // check and merge imports
        List<ImportDeclaration> ids = mergeListNoDuplicate(one.getImports(), two.getImports());
        cu.setImports(ids);

        // check and merge Types
        List<TypeDeclaration> types = mergeTypes(one.getTypes(), two.getTypes());
        cu.setTypes(types);

        return cu.toString();
    }
 
Example 4
Source Project: jeddict   Source File: JavaClassSyncHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void syncImplementedTypes(List<ClassOrInterfaceType> implementedTypes, Map<String, ImportDeclaration> imports) {
    Set<ReferenceClass> allInterfaces = new LinkedHashSet<>(javaClass.getRootElement().getInterfaces());
    allInterfaces.addAll(javaClass.getInterfaces());

    for (ClassOrInterfaceType implementedType : implementedTypes) {
        String implementedExprName = implementedType.getNameAsString();
        String implementedName;
        if (isFQN(implementedExprName)) {
            implementedName = unqualify(implementedExprName);
        } else {
            implementedName = implementedExprName;
        }

        String value = implementedType.toString();
        if (!allInterfaces
                .stream()
                .filter(inter -> inter.isEnable())
                .filter(inter -> inter.getName().contains(implementedName))
                .findAny()
                .isPresent()) {
            javaClass.addRuntimeInterface(new ReferenceClass(value));
            syncImportSnippet(value, imports);;
        }
    }
}
 
Example 5
Source Project: jeddict   Source File: MemberExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public String getDefaultValue() {
    String defaultValue = null;
    if (field != null && field.getVariables().get(0).getChildNodes().size() == 3) {
        Node node = field.getVariables().get(0).getChildNodes().get(2);
        if (node instanceof Expression) { //FieldAccessExpr, MethodCallExpr, ObjectCreationExpr
            defaultValue = node.toString();
            Map<String, ImportDeclaration> imports = clazz.getImports();
             String importList = imports.keySet()
                     .stream()
                    .filter(defaultValue::contains)
                    .map(imports::get)
                    .map(ImportDeclaration::getNameAsString)
                    .collect(joining(" ,\n"));
            defaultValue = importList.isEmpty() ? defaultValue : "[\n" + importList + "\n]\n" + defaultValue;
        } else if (node instanceof NodeWithSimpleName) {
            defaultValue = ((NodeWithSimpleName) node).getNameAsString();
        } else if (node instanceof LiteralStringValueExpr) {
            defaultValue = "'" + ((LiteralStringValueExpr) node).getValue() + "'";
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return defaultValue;
}
 
Example 6
void organiseImports(CompilationUnit cu) {
    List<ImportDeclaration> importDecls = new ArrayList<>();
    for (ImportDeclaration importDeclaration : cu.getImports()) {
        if (importDeclaration.getNameAsString().startsWith("org.jctools.util.Unsafe")) {
            continue;
        }
        importDecls.add(importDeclaration);
    }
    cu.getImports().clear();
    for (ImportDeclaration importDecl : importDecls) {
        cu.addImport(importDecl);
    }
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceArray"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongArray"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueueUtil"));
    cu.addImport(staticImportDeclaration("org.jctools.queues.atomic.AtomicQueueUtil.*"));
}
 
Example 7
Source Project: deadcode4j   Source File: ReferenceToConstantsAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private static Function<? super ImportDeclaration, ? extends String> toImportedType() {
    return new Function<ImportDeclaration, String>() {
        @Nullable
        @Override
        public String apply(@Nullable ImportDeclaration input) {
            if (input == null) {
                return null;
            }
            NameExpr name = input.getName();
            if (input.isStatic() && !input.isAsterisk()) {
                name = QualifiedNameExpr.class.cast(name).getQualifier();
            }
            return name.toString();
        }
    };
}
 
Example 8
Source Project: kogito-runtimes   Source File: QueryEndpointGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void addMonitoringToResource(CompilationUnit cu, MethodDeclaration[] methods, String nameURL) {
    cu.addImport(new ImportDeclaration(new Name("org.kie.kogito.monitoring.system.metrics.SystemMetricsCollector"), false, false));

    for (MethodDeclaration md : methods) {
        BlockStmt body = md.getBody().orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"));
        NodeList<Statement> statements = body.getStatements();
        ReturnStmt returnStmt = body.findFirst(ReturnStmt.class).orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a return statement!"));
        statements.addFirst(parseStatement("double startTime = System.nanoTime();"));
        statements.addBefore(parseStatement("double endTime = System.nanoTime();"), returnStmt);
        statements.addBefore(parseStatement("SystemMetricsCollector.registerElapsedTimeSampleMetrics(\"" + nameURL + "\", endTime - startTime);"), returnStmt);
        md.setBody(wrapBodyAddingExceptionLogging(body, nameURL));
    }
}
 
Example 9
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the imports.
 *
 * @param cu the cu
 * @return the imports
 */
static Set<String> getImports(CompilationUnit cu) {
    Set<String> importSet = null;
    List<ImportDeclaration> imports = cu.getImports();
    if (CollectionUtil.isNotEmpty(imports)) {
        importSet = new HashSet<String>(imports.size());
        for (ImportDeclaration im : imports) {
            String imStr = (im.isStatic() ? "static " : "") + im.getName() + (im.isAsterisk() ? ".*" : "");
            importSet.add(imStr);
        }
    } else {
        importSet = new HashSet<String>(0);
    }
    return importSet;
}
 
Example 10
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public int compare(ImportDeclaration o1, ImportDeclaration o2) {
    String stringWithoutComments1 = o1.getName().toString(prettyPrinterConfiguration);
    String stringWithoutComments2 = o2.getName().toString(prettyPrinterConfiguration);

    if (o1.isStatic() && !o2.isStatic()) {
        return -1;
    } else if (!o1.isStatic() && o2.isStatic()) {
        return 1;
    } else if (o1.isStatic() && o2.isStatic()) {
        return stringWithoutComments1.compareTo(stringWithoutComments2);
    }

    int compareEclipseImport = compareEclipseImport(stringWithoutComments1, stringWithoutComments2, "java.");
    if (compareEclipseImport != -2) {
        return compareEclipseImport;
    }

    compareEclipseImport = compareEclipseImport(stringWithoutComments1, stringWithoutComments2, "javax.");
    if (compareEclipseImport != -2) {
        return compareEclipseImport;
    }

    compareEclipseImport = compareEclipseImport(stringWithoutComments1, stringWithoutComments2, "org.");
    if (compareEclipseImport != -2) {
        return compareEclipseImport;
    }

    compareEclipseImport = compareEclipseImport(stringWithoutComments1, stringWithoutComments2, "cn.");
    if (compareEclipseImport != -2) {
        return compareEclipseImport;
    }

    compareEclipseImport = compareEclipseImport(stringWithoutComments1, stringWithoutComments2, "com.");
    if (compareEclipseImport != -2) {
        return compareEclipseImport;
    }

    return stringWithoutComments1.compareTo(stringWithoutComments2);
}
 
Example 11
/**
 * Instantiates new java enum builder.
 *
 * @param packageName Package name.
 * @param name Enum name.
 */
public JavaEnumBuilderImpl(String packageName, String name) {
  super(packageName);
  declaration = getCompilationUnit().addEnum(name);
  declaration.setName(name);

  Name jsonPropertyName = new Name();
  jsonPropertyName.setQualifier(new Name(JSON_PROPERTY_PACKAGE));
  jsonPropertyName.setIdentifier(JSON_PROPERTY);
  getCompilationUnit().addImport(new ImportDeclaration(jsonPropertyName, false, false));
}
 
Example 12
/**
 * Checks if given name is already imported on compilation unit.
 *
 * @param compilationUnit Compilation unit.
 * @param name Name to check for.
 * @return True if name is already imported.
 */
public static boolean isImported(CompilationUnit compilationUnit, Name name) {
  NodeList<ImportDeclaration> imports = compilationUnit.getImports();
  if (CollectionUtils.isNotEmpty(imports)) {
    for (ImportDeclaration importDeclaration : imports) {
      if (name.equals(importDeclaration.getName())) {
        return true;
      }
    }
  }

  return false;
}
 
Example 13
@Override
public void addImport(String packageName, String object) {
  Name name = new Name();
  name.setQualifier(new Name(packageName));
  name.setIdentifier(object);

  if (!getPackageName().equalsIgnoreCase(packageName)
      && !CompilationUnitUtils.isImported(getCompilationUnit(), name)) {
    getCompilationUnit().addImport(new ImportDeclaration(name, false, false));
  }
}
 
Example 14
@Override
public void addImport(String packageName, String object) {
  Name name = new Name();
  name.setQualifier(new Name(packageName));
  name.setIdentifier(object);

  if (!getPackageName().equalsIgnoreCase(packageName)
      && !CompilationUnitUtils.isImported(getCompilationUnit(), name)) {
    getCompilationUnit().addImport(new ImportDeclaration(name, false, false));
  }
}
 
Example 15
Source Project: apigcc   Source File: ClassHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 寻找import行,组装完整的类名称
 * @param name
 * @param compilationUnit
 * @return
 */
private static String getNameFromImport(String name, CompilationUnit compilationUnit){
    int dotPos = name.indexOf('.');
    String prefix = null;
    if (dotPos > -1) {
        prefix = name.substring(0, dotPos);
    }
    for (ImportDeclaration importDecl : compilationUnit.getImports()) {
        if (!importDecl.isAsterisk()) {
            String qName = importDecl.getNameAsString();
            boolean defaultPackage = !importDecl.getName().getQualifier().isPresent();

            boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name);
            if (!found) {
                if (prefix != null) {
                    found = qName.endsWith("." + prefix);
                    if (found) {
                        qName = qName + name.substring(dotPos);
                    }
                }
            }
            if (found) {
                return qName;
            }
        }
    }
    return name;
}
 
Example 16
Source Project: butterfly   Source File: AbstractTypeCheck.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean isImported(CompilationUnit compilationUnit, String typeSimpleName) {
    if (StringUtils.isBlank(typeSimpleName) || typeSimpleName.contains(".")) {
        throw new IllegalArgumentException("Invalid type simple name");
    }

    // If the specified type is part of the JDK,
    // then it won't need need an explicit import statement
    if (specifiedTypePackageName.startsWith("java.lang")) {
        return true;
    }

    // Check if the compilation unit has an explicit import declaration whose
    // type name matches the specified type simple name
    String importClass;
    for (ImportDeclaration importDeclaration : compilationUnit.getImports()) {
        importClass = importDeclaration.getName().getIdentifier();
        if (importClass.equals(typeSimpleName)) {
            return true;
        }
    }

    // Check if the annotation is declared
    // at the same package where the class is
    if (compilationUnit.getPackageDeclaration().get().getNameAsString().equals(specifiedTypePackageName)) {
        return true;
    }

    return false;
}
 
Example 17
Source Project: impsort-maven-plugin   Source File: ImpSort.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<Import> convertImportSection(List<Node> importSectionNodes, String eol) {
  List<Comment> recentComments = new ArrayList<>();
  LinkedHashSet<Import> allImports = new LinkedHashSet<>(importSectionNodes.size() / 2);
  for (Node node : importSectionNodes) {
    if (node instanceof Comment) {
      recentComments.add((Comment) node);
    } else if (node instanceof ImportDeclaration) {
      List<Node> thisImport = new ArrayList<>(2);
      ImportDeclaration impDecl = (ImportDeclaration) node;
      thisImport.addAll(recentComments);

      Optional<Comment> impComment = impDecl.getComment();
      if (impComment.isPresent()) {
        Comment c = impComment.get();
        if (c.getBegin().get().isBefore(impDecl.getBegin().get())) {
          thisImport.add(c);
          thisImport.add(impDecl);
        } else {
          thisImport.add(impDecl);
          thisImport.add(c);
        }
      } else {
        thisImport.add(impDecl);
      }

      recentComments.clear();
      convertAndAddImport(allImports, thisImport, eol);
    } else {
      throw new IllegalStateException("Unknown node: " + node);
    }
  }
  if (!recentComments.isEmpty()) {
    throw new IllegalStateException(
        "Unexpectedly found more orphaned comments: " + recentComments);
  }
  return allImports;
}
 
Example 18
Source Project: impsort-maven-plugin   Source File: ImpSort.java    License: Apache License 2.0 5 votes vote down vote up
private static void convertAndAddImport(LinkedHashSet<Import> allImports, List<Node> thisImport,
    String eol) {
  boolean isStatic = false;
  String importItem = null;
  String prefix = "";
  String suffix = "";
  for (Node n : thisImport) {
    if (n instanceof Comment) {
      if (importItem == null) {
        prefix += n.toString();
      } else {
        suffix += n.toString();
      }
    }
    if (n instanceof ImportDeclaration) {
      ImportDeclaration i = (ImportDeclaration) n;
      isStatic = i.isStatic();
      importItem = i.getName().asString() + (i.isAsterisk() ? ".*" : "");
    }
  }
  suffix = suffix.trim();
  if (!suffix.isEmpty()) {
    suffix = " " + suffix;
  }
  Import imp = new Import(isStatic, importItem, prefix.trim(), suffix, eol);
  Iterator<Import> iter = allImports.iterator();
  // this de-duplication can probably be made more efficient by doing it all at the end
  while (iter.hasNext()) {
    Import candidate = iter.next(); // potential duplicate
    if (candidate.isDuplicatedBy(imp)) {
      iter.remove();
      imp = candidate.combineWith(imp);
    }
  }
  allImports.add(imp);
}
 
Example 19
Source Project: enkan   Source File: ScaffoldCommandRegister.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Generator configureApplicationFactory(Generator gen, String tableName, EnkanSystem system) {
    String path = findApplicationFactoryPath(system);
    return gen.writing("app", g -> g.task(new RewriteJavaSourceTask("src/main/java/" + path, cu -> {
        String controllerClassName = CaseConverter.pascalCase(tableName) + "Controller";
        String pkgName = BasePackageDetector.detect();

        cu.getImports().add(
                new ImportDeclaration(
                        ASTHelper.createNameExpr(pkgName + "controller." + controllerClassName),
                        false, false));
        cu.accept(new AppendRoutingVisitor(controllerClassName),
                new RoutingDefineContext());
    })));
}
 
Example 20
Source Project: groovy   Source File: GroovydocJavaVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ImportDeclaration n, Object arg) {
    Optional<Name> qualPath = n.getName().getQualifier();
    String qual = qualPath.map(value -> value.asString().replace('.', '/') + "/").orElse("");
    String id = n.getName().getIdentifier();
    String name = qual + id;
    imports.add(name);
    aliases.put(id, name);
    super.visit(n, arg);
}
 
Example 21
Source Project: dolphin   Source File: ImportDeclarationMerger.java    License: Apache License 2.0 5 votes vote down vote up
@Override public ImportDeclaration doMerge(ImportDeclaration first, ImportDeclaration second) {
  ImportDeclaration id = new ImportDeclaration();
  id.setName(mergeSingle(first.getName(),second.getName()));
  id.setAsterisk(first.isAsterisk());
  id.setStatic(first.isStatic());
  return id;
}
 
Example 22
Source Project: jeddict   Source File: AttributeSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void syncExistingSnippet(String name, MethodDeclaration method, Map<String, ImportDeclaration> imports) {
    String methodName = method.getNameAsString();
    if (isBeanMethod(methodName)) {
        boolean getterMethod = isGetterMethod(methodName);
        syncJavadoc(method.getComment(), getterMethod ? GETTER_JAVADOC : SETTER_JAVADOC);
        syncAnnotation(method.getAnnotations(), getterMethod ? AttributeAnnotationLocationType.GETTER : AttributeAnnotationLocationType.SETTER, imports);
        syncThrows(method, getterMethod, imports);
        syncMethodBody(name, method, getterMethod, imports);
    } else if (isHelperMethod(methodName)) {
        syncHelperMethodBody(name, method, isAddMethod(methodName), imports);
    }
}
 
Example 23
Source Project: jeddict   Source File: AttributeSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncThrows(MethodDeclaration method, boolean getterMethod, Map<String, ImportDeclaration> imports) {
    if (attribute.getSnippets(getterMethod ? GETTER_THROWS : SETTER_THROWS).isEmpty()) {
        for (ReferenceType thrownException : method.getThrownExceptions()) {
            String value = thrownException.toString();
            AttributeSnippet attributeSnippet = new AttributeSnippet(value, getterMethod ? GETTER_THROWS : SETTER_THROWS);
            attribute.addRuntimeSnippet(attributeSnippet);
            addImportSnippet(value, imports);
        }
    }
}
 
Example 24
Source Project: jeddict   Source File: AttributeSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncAnnotation(List<AnnotationExpr> annotationExprs, AttributeAnnotationLocationType locationType, Map<String, ImportDeclaration> imports) {
    for (AnnotationExpr annotationExpr : annotationExprs) {
        String annotationExprName = annotationExpr.getNameAsString();
        String annotationName;
        String annotationFQN;
        if (isFQN(annotationExprName)) {
            annotationFQN = annotationExprName;
            annotationName = unqualify(annotationExprName);
        } else {
            annotationFQN = imports.containsKey(annotationExprName)
                    ? imports.get(annotationExprName).getNameAsString() : annotationExprName;
            annotationName = annotationExprName;
        }

        if (!annotationFQN.startsWith(PERSISTENCE_PACKAGE)
                && !annotationFQN.startsWith(NOSQL_PACKAGE)
                && !annotationFQN.startsWith(BV_CONSTRAINTS_PACKAGE)
                && !annotationFQN.startsWith(JSONB_PACKAGE)
                && !annotationFQN.startsWith(JAXB_PACKAGE)
                && !JPA_ANNOTATIONS.contains(annotationFQN)
                && !JNOSQL_ANNOTATIONS.contains(annotationFQN)
                && !BV_ANNOTATIONS.contains(annotationFQN)
                && !JSONB_ANNOTATIONS.contains(annotationFQN)
                && !JAXB_ANNOTATIONS.contains(annotationFQN)) {
            String value = annotationExpr.toString();
            if (!attribute.getAnnotation()
                    .stream()
                    .filter(anot -> anot.getLocationType() == locationType)
                    .filter(anot -> anot.getName().contains(annotationName))
                    .findAny()
                    .isPresent()) {
                attribute.addRuntimeAnnotation(new AttributeAnnotation(value, locationType));
                addImportSnippet(value, imports);
            }
        }

    }
}
 
Example 25
Source Project: jeddict   Source File: AttributeSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncHelperMethodBody(String name, MethodDeclaration method, boolean addMethod, Map<String, ImportDeclaration> imports) {
    if (!method.getBody().isPresent()) {
        return;
    }
    List<AttributeSnippet> preSnippets = attribute.getSnippets(addMethod ? PRE_ADD_HELPER : PRE_REMOVE_HELPER);
    List<AttributeSnippet> bodySnippets = attribute.getSnippets(addMethod ? ADD_HELPER : REMOVE_HELPER);
    if (!preSnippets.isEmpty() || !bodySnippets.isEmpty()) {
        return;
    }

    boolean bodyMatched = false;
    BlockStmt block = method.getBody().get();
    AttributeSnippetLocationType locationType = addMethod ? PRE_ADD_HELPER : PRE_REMOVE_HELPER;

    String bridgeLine = deleteWhitespace(String.format("%s().%s(%s);",
            getMethodName(getIntrospectionPrefix(isBoolean(attribute.getDataTypeLabel())), name),
            addMethod ? "add" : "remove",
            StringHelper.singularize(name)
    ));

    for (Node node : block.getChildNodes()) {
        String[] statements = node.toString().split("\n");
        for (String statement : statements) {
            if (bridgeLine.equals(deleteWhitespace(statement))) {
                locationType = null;
                bodyMatched = true;
            } else if (locationType != null) {
                attribute.addRuntimeSnippet(new AttributeSnippet(statement, locationType));
                addImportSnippet(statement, imports);
            }
        }
    }
    if(!bodyMatched) {
        attribute.addRuntimeSnippet(new AttributeSnippet(null, addMethod ? ADD_HELPER : REMOVE_HELPER));
    }
}
 
Example 26
Source Project: jeddict   Source File: AttributeSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void addImportSnippet(String snippet, Map<String, ImportDeclaration> imports) {
    imports.keySet()
            .stream()
            .filter(snippet::contains)
            .map(imports::get)
            .map(importClass -> new AttributeSnippet(importClass.getNameAsString(), IMPORT))
            .forEach(attribute::addRuntimeSnippet);
}
 
Example 27
Source Project: jeddict   Source File: JavaClassSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncTypeParameters(List<TypeParameter> typeParameters, Map<String, ImportDeclaration> imports) {
    for (TypeParameter typeParameter : typeParameters) {
        String value = typeParameter.toString();
        javaClass.addRuntimeTypeParameter(value);
        syncImportSnippet(value, imports);
    }
}
 
Example 28
Source Project: jeddict   Source File: JavaClassSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncExtendedTypes(List<ClassOrInterfaceType> extendedTypes, Map<String, ImportDeclaration> imports) {
    if (extendedTypes.size() != 1) {
        return; // single extends is valid for entity
    }
    ClassOrInterfaceType extendedType = extendedTypes.get(0);
    String value = extendedType.toString();
    if (javaClass.getSuperclassRef() == null && javaClass.getSuperclass() == null) {
        javaClass.setRuntimeSuperclassRef(new ReferenceClass(value));
        syncImportSnippet(value, imports);;
    }
}
 
Example 29
Source Project: jeddict   Source File: JavaClassSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncAnnotations(List<AnnotationExpr> annotationExprs, ClassAnnotationLocationType locationType, Map<String, ImportDeclaration> imports) {
    for (AnnotationExpr annotationExpr : annotationExprs) {
        String annotationExprName = annotationExpr.getNameAsString();
        String annotationName;
        String annotationFQN;
        //TODO calculate using resolve type or find solution for static import ??
        if (isFQN(annotationExprName)) {
            annotationFQN = annotationExprName;
            annotationName = unqualify(annotationExprName);
        } else {
            annotationFQN = imports.containsKey(annotationExprName)
                    ? imports.get(annotationExprName).getNameAsString() : annotationExprName;
            annotationName = annotationExprName;
        }

        if (!annotationFQN.startsWith(PERSISTENCE_PACKAGE)
                && !annotationFQN.startsWith(NOSQL_PACKAGE)
                && !annotationFQN.startsWith(BV_CONSTRAINTS_PACKAGE)
                && !annotationFQN.startsWith(JSONB_PACKAGE)
                && !annotationFQN.startsWith(JAXB_PACKAGE)
                && !JPA_ANNOTATIONS.contains(annotationFQN)
                && !JNOSQL_ANNOTATIONS.contains(annotationFQN)
                && !BV_ANNOTATIONS.contains(annotationFQN)
                && !JSONB_ANNOTATIONS.contains(annotationFQN)
                && !JAXB_ANNOTATIONS.contains(annotationFQN)) {

            String value = annotationExpr.toString();
            if (!javaClass.getAnnotation()
                    .stream()
                    .filter(anot -> anot.getLocationType() == locationType)
                    .filter(anot -> anot.getName().contains(annotationName))
                    .findAny()
                    .isPresent()) {
                javaClass.addRuntimeAnnotation(new ClassAnnotation(value, locationType));
                syncImportSnippet(value, imports);;
            }
        }

    }
}
 
Example 30
Source Project: jeddict   Source File: JavaClassSyncHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void syncFieldSnippet(BodyDeclaration<?> lastScannedMember, Attribute lastScannedAttribute, FieldDeclaration field, Map<String, ImportDeclaration> imports) {
    if (lastScannedAttribute == null) {
        syncFieldSnippet(field, imports);
    } else {
        if (lastScannedMember instanceof MethodDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_METHOD, field.toString(), imports);
        } else if (lastScannedMember instanceof FieldDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_FIELD, field.toString(), imports);
        } else {
            syncFieldSnippet(field, imports);
        }
    }
}