com.github.javaparser.ast.ImportDeclaration Java Examples

The following examples show how to use com.github.javaparser.ast.ImportDeclaration. 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 File: ReferenceToConstantsAnalyzer.java    From deadcode4j with 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 #2
Source File: MemberExplorer.java    From jeddict with 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 #3
Source File: ASTHelper.java    From stategen with 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 #4
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: JavaSourceUtils.java    From dolphin with 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 #6
Source File: JavaParsingAtomicArrayQueueGenerator.java    From JCTools with Apache License 2.0 6 votes vote down vote up
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 File: JavaClassSyncHandler.java    From jeddict with 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 #8
Source File: JavaClassSyncHandler.java    From jeddict with 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 #9
Source File: JavaClassBuilderImpl.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncInitializationBlockSnippet(BodyDeclaration<?> lastScannedMember, Attribute lastScannedAttribute, InitializerDeclaration initializationBlock, Map<String, ImportDeclaration> imports) {
    if (lastScannedAttribute == null) {
        syncInitializationBlockSnippet(initializationBlock, imports);
    } else {
        if (lastScannedMember instanceof MethodDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_METHOD, initializationBlock.toString(), imports);
        } else if (lastScannedMember instanceof FieldDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_FIELD, initializationBlock.toString(), imports);
        } else {
            syncInitializationBlockSnippet(initializationBlock, imports);
        }
    }
}
 
Example #11
Source File: JavaClassSyncHandler.java    From jeddict with 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);
        }
    }
}
 
Example #12
Source File: JavaClassSyncHandler.java    From jeddict with 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 #13
Source File: JavaClassSyncHandler.java    From jeddict with 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 #14
Source File: JavaClassSyncHandler.java    From jeddict with 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 #15
Source File: AttributeSyncHandler.java    From jeddict with 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 #16
Source File: AttributeSyncHandler.java    From jeddict with 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 #17
Source File: AbstractTypeCheck.java    From butterfly with 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 #18
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void removeImport(String s) {
  Iterator<ImportDeclaration> it = cu.getImports().iterator();
  while (it.hasNext()) { 
    ImportDeclaration impDcl = it.next();
    if (impDcl.getNameAsString().equals(s)) {
      it.remove();
      break;
    }
  } 
}
 
Example #19
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncMethodSnippet(BodyDeclaration<?> lastScannedMember, Attribute lastScannedAttribute, MethodDeclaration method, Map<String, ImportDeclaration> imports) {
    if (lastScannedAttribute == null) {
        syncMethodSnippet(method, imports);
    } else {
        if (lastScannedMember instanceof MethodDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_METHOD, method.toString(), imports);
        } else if (lastScannedMember instanceof FieldDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_FIELD, method.toString(), imports);
        } else {
            syncMethodSnippet(method, imports);
        }
    }
}
 
Example #20
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncInnerClassOrInterfaceOrEnumSnippet(BodyDeclaration<?> lastScannedMember, Attribute lastScannedAttribute, BodyDeclaration<?> member, Map<String, ImportDeclaration> imports) {
    if (lastScannedAttribute == null) {
        syncInnerClassOrInterfaceOrEnumSnippet(member, imports);
    } else {
        if (lastScannedMember instanceof MethodDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_METHOD, member.toString(), imports);
        } else if (lastScannedMember instanceof FieldDeclaration) {
            syncAttributeSnippet(lastScannedAttribute, AttributeSnippetLocationType.AFTER_FIELD, member.toString(), imports);
        } else {
            syncInnerClassOrInterfaceOrEnumSnippet(member, imports);
        }
    }
}
 
Example #21
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncImportSnippet(String snippet, Map<String, ImportDeclaration> imports) {
    imports.keySet()
            .stream()
            .filter(snippet::contains)
            .map(imports::get)
            .map(importClass -> new ClassSnippet(importClass.getNameAsString(), IMPORT))
            .forEach(javaClass::addRuntimeSnippet);
}
 
Example #22
Source File: Sources.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public String apply(Node node) {
    if (node instanceof NamedNode) {
        String name = ((NamedNode)node).getName();
        Node current = node;
        while (!(current instanceof CompilationUnit)) {
            current = current.getParentNode();
        }

        CompilationUnit compilationUnit = (CompilationUnit) current;

        for (ImportDeclaration importDecl : compilationUnit.getImports()) {
            NameExpr importExpr = importDecl.getName();
            if (importExpr instanceof QualifiedNameExpr) {
                QualifiedNameExpr qualifiedNameExpr = (QualifiedNameExpr) importExpr;
                String className = qualifiedNameExpr.getName();
                if (name.equals(className)) {
                    return qualifiedNameExpr.getQualifier().toString();
                }
            } else if (importDecl.getName().getName().endsWith(SEPARATOR + name)) {
                String importName = importDecl.getName().getName();
                return  importName.substring(0, importName.length() - name.length() -1);
            }
        }

       try {
           Class.forName(JAVA_LANG + "." + name);
           return JAVA_LANG;
       } catch (ClassNotFoundException ex) {
           return compilationUnit.getPackage().getPackageName();
       }
    }
    return null;
}
 
Example #23
Source File: Sources.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public Set<ClassRef> apply(Node node) {
    Set<ClassRef> imports = new LinkedHashSet<ClassRef>();

    if (node instanceof NamedNode) {
        String name = ((NamedNode)node).getName();
        Node current = node;
        while (!(current instanceof CompilationUnit)) {
            current = current.getParentNode();
        }

        CompilationUnit compilationUnit = (CompilationUnit) current;

        for (ImportDeclaration importDecl : compilationUnit.getImports()) {
            String className = null;
            String packageName = null;

            NameExpr importExpr = importDecl.getName();
            if (importExpr instanceof QualifiedNameExpr) {
                QualifiedNameExpr qualifiedNameExpr = (QualifiedNameExpr) importExpr;
                className = qualifiedNameExpr.getName();
                packageName = qualifiedNameExpr.getQualifier().toString();
            } else if (importDecl.getName().getName().endsWith(SEPARATOR + name)) {
                String importName = importDecl.getName().getName();
                packageName = importName.substring(0, importName.length() - name.length() -1);
            }
            if (className != null && !className.isEmpty()) {
                imports.add(new ClassRefBuilder().withNewDefinition().withName(className).withPackageName(packageName).and().build());
            }
        }
    }
    return imports;
}
 
Example #24
Source File: CodeValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Set<String> extractImportStatements(CompilationUnit cu) {
        final PrettyPrinterConfiguration p = new PrettyPrinterConfiguration().setPrintComments( false );
        Set<String> result = new HashSet<>();
        for( ImportDeclaration id : cu.getImports() ){
            result.add( id.toString( p ) );
        }
        return result;
        // I have no idea on how to use stream with map and paramenters
//        return cu.getImports()
//                .stream()
//                .map(ImportDeclaration::toString(p))
//                .collect(Collectors.toSet());
    }
 
Example #25
Source File: JavaParsingAtomicLinkedQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
void organiseImports(CompilationUnit cu) {
    List<ImportDeclaration> importDecls = new ArrayList<>();
    for (ImportDeclaration importDeclaration : cu.getImports()) {
        String name = importDeclaration.getNameAsString();
        if (name.startsWith("org.jctools.util.Unsafe")) {
            continue;
        }

        if (name.startsWith("org.jctools.queues.LinkedArrayQueueUtil")) {
            continue;
        }

        importDecls.add(importDeclaration);
    }
    cu.getImports().clear();
    for (ImportDeclaration importDecl : importDecls) {
        cu.addImport(importDecl);
    }
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongFieldUpdater"));
    cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceArray"));

    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueue"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueue.Supplier"));
    cu.addImport(importDeclaration("org.jctools.queues.MessagePassingQueueUtil"));
    cu.addImport(importDeclaration("org.jctools.queues.QueueProgressIndicators"));
    cu.addImport(importDeclaration("org.jctools.queues.IndexedQueueSizeUtil"));
    cu.addImport(staticImportDeclaration("org.jctools.queues.atomic.AtomicQueueUtil.*"));
}
 
Example #26
Source File: ImportDeclarations.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>Predicate</code> that evaluates to <code>true</code> if the <code>ImportDeclaration</code> being
 * tested is an asterisk import.
 *
 * @since 2.0.0
 */
@Nonnull
public static Predicate<? super ImportDeclaration> isAsterisk() {
    return new Predicate<ImportDeclaration>() {
        @Override
        @SuppressWarnings("ConstantConditions")
        public boolean apply(@Nullable ImportDeclaration input) {
            return checkNotNull(input).isAsterisk();
        }
    };
}
 
Example #27
Source File: ImportDeclarations.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>Predicate</code> that evaluates to <code>true</code> if the <code>ImportDeclaration</code> being
 * tested is a static import.
 *
 * @since 2.0.0
 */
@Nonnull
public static Predicate<? super ImportDeclaration> isStatic() {
    return new Predicate<ImportDeclaration>() {
        @Override
        @SuppressWarnings("ConstantConditions")
        public boolean apply(@Nullable ImportDeclaration input) {
            return checkNotNull(input).isStatic();
        }
    };
}
 
Example #28
Source File: ImportDeclarations.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>Predicate</code> that evaluates to <code>true</code> if the last qualifier of the
 * <code>ImportDeclaration</code> being tested matches the given String.
 *
 * @since 2.0.0
 */
@Nonnull
public static Predicate<? super ImportDeclaration> refersTo(@Nonnull final String lastQualifier) {
    return new Predicate<ImportDeclaration>() {
        @Override
        @SuppressWarnings("ConstantConditions")
        public boolean apply(@Nullable ImportDeclaration input) {
            return lastQualifier.equals(checkNotNull(input).getName().getName());
        }
    };
}
 
Example #29
Source File: JavaFileAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected String calculatePrefix(@Nonnull Qualifier<?> topQualifier) {
    String firstQualifier = topQualifier.getFirstQualifier().getName();
    CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode());
    ImportDeclaration importDeclaration = getOnlyElement(emptyIfNull(compilationUnit.getImports()).filter(
            and(not(isAsterisk()), refersTo(firstQualifier))), null);
    if (importDeclaration == null) {
        return null;
    }
    StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder());
    int beginIndex = buffy.length() - firstQualifier.length();
    return beginIndex == 0 ? "" :
            buffy.replace(beginIndex - 1, buffy.length(), importDeclaration.isStatic() ? "$" : ".").toString();
}
 
Example #30
Source File: JavaFileAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected Iterable<String> calculatePrefixes(@Nonnull Qualifier<?> topQualifier) {
    ArrayList<String> asteriskImports = newArrayList();
    CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode());
    for (ImportDeclaration importDeclaration :
            emptyIfNull(compilationUnit.getImports()).filter(isAsterisk())) {
        StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder());
        buffy.append(importDeclaration.isStatic() ? '$' : '.');
        asteriskImports.add(buffy.toString());
    }
    return asteriskImports;
}