org.netbeans.api.java.source.ClassIndex Java Examples

The following examples show how to use org.netbeans.api.java.source.ClassIndex. 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: JavaSourceTestCase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void startAndBlockClassPathScan() throws IOException, InterruptedException {
    if (blockLatch != null) {
        resumeClassPathScan();
    }
    FileObject workDir = FileUtil.toFileObject(getWorkDir());
    FileObject blockFO = FileUtil.createFolder(workDir, FileUtil.findFreeFolderName(workDir, "cp-scan-block-root"));
    MockLookup.setInstances(cpProvider, new SimpleClassPathProvider(blockFO));
    System.out.println(System.identityHashCode(ClassPath.getClassPath(blockFO, ClassPath.SOURCE)));
    IndexingManager.getDefault().refreshIndexAndWait(blockFO.getURL(), null);
    final CountDownLatch waitLatch = new CountDownLatch(1);
    blockLatch = new CountDownLatch(1);
    ClassIndex index = ClasspathInfo.create(blockFO).getClassIndex();
    index.addClassIndexListener(new ClassIndexAdapter() {
        public void typesAdded(TypesEvent event) {
            waitLatch.countDown();
            try {
                blockLatch.await();
            } catch (InterruptedException e) {
                throw new Error(e);
            }
        }
    });
    TestUtilities.copyStringToFileObject(blockFO, "Dummy.java", "public class Dummy {}");
    waitLatch.await();
}
 
Example #2
Source File: JavacPackageInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<SourcePackageInfo> getSubpackages() {
    final ClassIndex index = cpInfo.getClassIndex();
    final List<SourcePackageInfo> pkgs = new ArrayList<SourcePackageInfo>();

    ParsingUtils.invokeScanSensitiveTask(cpInfo, new ScanSensitiveTask<CompilationController>(true) {
        @Override
        public void run(CompilationController cc) {
            for (String pkgName : index.getPackageNames(getBinaryName() + ".", true, sScope)) { // NOI18N
                pkgs.add(new JavacPackageInfo(cpInfo, indexInfo, pkgName, pkgName, getScope()));
            }
        }
    });

    return pkgs;
}
 
Example #3
Source File: JavaPackageCompletor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void doPackageCompletion(JavaSource js, final String typedPrefix, final int substitutionOffset) throws IOException {
    js.runUserActionTask(new Task<CompilationController>() {

        @Override
        public void run(CompilationController cc) throws Exception {
            if (isCancelled()) {
                return;
            }

            cc.toPhase(Phase.ELEMENTS_RESOLVED);
            ClassIndex ci = cc.getClasspathInfo().getClassIndex();
            int index = substitutionOffset;
            int dotIndex = typedPrefix.lastIndexOf('.'); // NOI18N
            if (dotIndex != -1) {
                index += (dotIndex + 1);  // NOI18N
            }

            addPackages(ci,  typedPrefix, index, CompletionProvider.COMPLETION_ALL_QUERY_TYPE);
        }
    }, true);
}
 
Example #4
Source File: JavacPackageInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public JavacPackageInfo(ClasspathInfo cpInfo, ClasspathInfo indexInfo, String simpleName, String fqn, Scope scope) {
    super(simpleName, fqn, scope);
    this.cpInfo = cpInfo;
    this.indexInfo = indexInfo;
    
    switch (scope) {
        case SOURCE: {
            sScope= EnumSet.of(ClassIndex.SearchScope.SOURCE);
            break;
        }
        case DEPENDENCIES: {
            sScope = EnumSet.of(ClassIndex.SearchScope.DEPENDENCIES);
            break;
        }
        default: {
            sScope = Collections.EMPTY_SET;
        }
    }
    
}
 
Example #5
Source File: VanillaCompileWorkerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testIndexEnumConstants() throws Exception {
    ParsingOutput result = runIndexing(Arrays.asList(compileTuple("test/Test.java", "package test; public enum Test implements Runnable { A() { public void run() {} }; }")),
                                       Arrays.asList());

    assertFalse(result.lowMemory);
    assertTrue(result.success);

    Set<String> createdFiles = new HashSet<String>();

    for (File created : result.createdFiles) {
        createdFiles.add(getWorkDir().toURI().relativize(created.toURI()).getPath());
    }

    assertEquals(new HashSet<String>(Arrays.asList("cache/s1/java/15/classes/test/Test.sig",
                                                        "cache/s1/java/15/classes/test/Test$1.sig")),
                 createdFiles);
    ClasspathInfo cpInfo = ClasspathInfo.create(ClassPath.EMPTY, ClassPath.EMPTY, ClassPathSupport.createClassPath(getRoot()));
    Set<ElementHandle<TypeElement>> classIndexResult = cpInfo.getClassIndex().getElements(ElementHandle.createTypeElementHandle(ElementKind.ENUM, "test.Test"), EnumSet.of(SearchKind.IMPLEMENTORS), EnumSet.of(ClassIndex.SearchScope.SOURCE));
    assertEquals(1, classIndexResult.size());
}
 
Example #6
Source File: ElementUtilitiesEx.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Set<ElementHandle<TypeElement>> findImplementors(final ClasspathInfo cpInfo, final ElementHandle<TypeElement> baseType) {
    final Set<ClassIndex.SearchKind> kind = EnumSet.of(ClassIndex.SearchKind.IMPLEMENTORS);
    final Set<ClassIndex.SearchScope> scope = EnumSet.allOf(ClassIndex.SearchScope.class);
    
    final Set<ElementHandle<TypeElement>> allImplementors = new HashSet<ElementHandle<TypeElement>>();

    ParsingUtils.invokeScanSensitiveTask(cpInfo, new ScanSensitiveTask<CompilationController>(true) {
        @Override
        public void run(CompilationController cc) {
            Set<ElementHandle<TypeElement>> implementors = cpInfo.getClassIndex().getElements(baseType, kind, scope);
            do {
                Set<ElementHandle<TypeElement>> tmpImplementors = new HashSet<ElementHandle<TypeElement>>();
                allImplementors.addAll(implementors);

                for (ElementHandle<TypeElement> element : implementors) {
                    tmpImplementors.addAll(cpInfo.getClassIndex().getElements(element, kind, scope));
                }

                implementors = tmpImplementors;
            } while (!implementors.isEmpty());
        }
    });
    
    return allImplementors;
}
 
Example #7
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ElementHandle<TypeElement> getHandleClassName(String qualifiedClassName, 
        Project project) throws IOException 
{
    FileObject root = MiscUtilities.findSourceRoot(project);
    ClassPathProvider provider = project.getLookup().lookup( 
            ClassPathProvider.class);
    ClassPath sourceCp = provider.findClassPath(root, ClassPath.SOURCE);
    ClassPath compileCp = provider.findClassPath(root, ClassPath.COMPILE);
    ClassPath bootCp = provider.findClassPath(root, ClassPath.BOOT);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootCp, compileCp, sourceCp);
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = qualifiedClassName.lastIndexOf('.')+1;
    String simple = qualifiedClassName.substring(beginIndex);
    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME, 
            EnumSet.of(ClassIndex.SearchScope.SOURCE, 
            ClassIndex.SearchScope.DEPENDENCIES));
    for (final ElementHandle<TypeElement> handle : handles) {
        if (qualifiedClassName.equals(handle.getQualifiedName())) {
            return handle;
        }
    }
    return null;
}
 
Example #8
Source File: MiscPrivateUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static FileObject getFileObjectFromClassName(Project p, String qualifiedClassName)
        throws IOException
{
    FileObject root = MiscUtilities.findSourceRoot(p);
    ClasspathInfo cpInfo = ClasspathInfo.create(root);
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = qualifiedClassName.lastIndexOf('.')+1;
    String simple = qualifiedClassName.substring(beginIndex);
    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME,
            Collections.singleton(ClassIndex.SearchScope.SOURCE));
    if ( handles == null ){
        return null;
    }
    for (ElementHandle<TypeElement> handle : handles) {
        if (qualifiedClassName.equals(handle.getQualifiedName())) {
            return SourceUtils.getFile(handle, cpInfo);
        }
    }
    return null;
}
 
Example #9
Source File: BaseProfilerTypeUtilsImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Set<ClassIndex.SearchScope> toSearchScope(Set<Scope> scope) {
    Set<ClassIndex.SearchScope> sScope = EnumSet.noneOf(ClassIndex.SearchScope.class);
    for(Scope s : scope) {
        switch (s) {
            case DEPENDENCIES: {
                sScope.add(ClassIndex.SearchScope.DEPENDENCIES);
                break;
            }
            case SOURCE: {
                sScope.add(ClassIndex.SearchScope.SOURCE);
                break;
            }
        }
    }
    return sScope;
}
 
Example #10
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static FileObject getFileObjectFromClassName(String qualifiedClassName, Project project) throws IOException {
    FileObject root = findSourceRoot(project);
    ClasspathInfo cpInfo = ClasspathInfo.create(root);
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = qualifiedClassName.lastIndexOf('.')+1;
    String simple = qualifiedClassName.substring(beginIndex);
    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME, 
            Collections.singleton(ClassIndex.SearchScope.SOURCE));
    for (ElementHandle<TypeElement> handle : handles) {
        if (qualifiedClassName.equals(handle.getQualifiedName())) {
            return SourceUtils.getFile(handle, cpInfo);
        }
    }
    return null;
}
 
Example #11
Source File: DocumentUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private static Convertor<String,String> createNameFactory(@NonNull final ClassIndex.ResourceType type) {
    switch (type) {
        case SOURCE:
            return new Convertor<String,String>() {
                @Override
                public String convert(String p) {
                    final int index = p.indexOf('$');                              //NOI18N
                    if (index > 0) {
                        p = p.substring(0, index);
                    }
                    return p;
                }
            };
        case BINARY:
            return Convertors.<String>identity();
        default:
            throw new IllegalArgumentException(String.valueOf(type));
    }
}
 
Example #12
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addAllTypes(JavadocContext env, EnumSet<ElementKind> kinds, Set<? extends Element> toExclude, String prefix, int substitutionOffset) {
//        String prefix = env.getPrefix();
        CompilationInfo controller = env.javac;
        boolean isCaseSensitive = false;
        ClassIndex.NameKind kind = 
            isCaseSensitive? ClassIndex.NameKind.PREFIX : ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
//        ClassIndex.NameKind kind = env.isCamelCasePrefix() ?
//            Utilities.isCaseSensitive() ? ClassIndex.NameKind.CAMEL_CASE : ClassIndex.NameKind.CAMEL_CASE_INSENSITIVE :
//            Utilities.isCaseSensitive() ? ClassIndex.NameKind.PREFIX : ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
        Set<ElementHandle<Element>> excludeHandles = null;
        if (toExclude != null) {
            excludeHandles = new HashSet<ElementHandle<Element>>(toExclude.size());
            for (Element el : toExclude) {
                excludeHandles.add(ElementHandle.create(el));
            }
        }
        for(ElementHandle<TypeElement> name : controller.getClasspathInfo().getClassIndex().getDeclaredTypes(prefix, kind, EnumSet.allOf(ClassIndex.SearchScope.class))) {
            if ((excludeHandles == null || !excludeHandles.contains(name)) && !isAnnonInner(name)) {
                items.add(LazyJavaCompletionItem.createTypeItem(name, kinds, substitutionOffset, env.getReferencesCount(), controller.getSnapshot().getSource(), false, false, false, null));
            }
        }
    }
 
Example #13
Source File: JShellOptions2.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void btnBrowseClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseClassActionPerformed
    final ClasspathInfo cpi = getClasspathInfo();
    String current = this.source.getText();
    ElementHandle<TypeElement> handle = TypeElementFinder.find(cpi, current, new TypeElementFinder.Customizer() {

        @Override
        public Set<ElementHandle<TypeElement>> query(ClasspathInfo classpathInfo, String textForQuery, ClassIndex.NameKind nameKind, Set<ClassIndex.SearchScope> searchScopes) {
            searchScopes.retainAll(Arrays.asList(ClassIndex.SearchScope.SOURCE));
            return cpi.getClassIndex().getDeclaredTypes(textForQuery, nameKind, searchScopes);
        }

        @Override
        public boolean accept(ElementHandle<TypeElement> typeHandle) {
            return true;
        }
    });
    if (handle == null) {
        return;
    }
    targetClass = handle;
    source.setText(handle.getQualifiedName());
    classNameChanged(null);
}
 
Example #14
Source File: AddPropertyPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Set<ElementHandle<TypeElement>> getImplementorsAsHandles(ClassIndex idx, TypeElement el) {
    LinkedList<ElementHandle<TypeElement>> elements = new LinkedList<ElementHandle<TypeElement>>(
            implementorsQuery(idx, ElementHandle.create(el)));
    Set<ElementHandle<TypeElement>> result = new HashSet<ElementHandle<TypeElement>>();
    while (!elements.isEmpty()) {
        if (canceled) {
            return Collections.emptySet();
        }
        ElementHandle<TypeElement> next = elements.removeFirst();
        if (!result.add(next)) {
            // it is a duplicate; do not query again
            continue;
        }
        Set<ElementHandle<TypeElement>> foundElements = implementorsQuery(idx, next);
        elements.addAll(foundElements);
    }
    return result;
}
 
Example #15
Source File: WsitPojectOpenedHook.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public FileObject getFileObjectFromClassName(String fqn) {
    SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups(
            JavaProjectConstants.SOURCES_TYPE_JAVA);
    if (sourceGroups == null || sourceGroups.length == 0) {
        return null;
    }
    ClasspathInfo cpInfo = ClasspathInfo.create(sourceGroups[0].getRootFolder());
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = fqn.lastIndexOf('.')+1;
    String simple = fqn.substring(beginIndex);
    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME, 
            Collections.singleton(ClassIndex.SearchScope.SOURCE));
    for (ElementHandle<TypeElement> handle : handles) {
        if (fqn.equals(handle.getQualifiedName())) {
            return SourceUtils.getFile(handle, cpInfo);
        }
    }
    return null;
}
 
Example #16
Source File: ProjectHelper.java    From jeddict with Apache License 2.0 6 votes vote down vote up
public static ElementHandle<TypeElement> getHandleClassName(String qualifiedClassName,
        Project project) throws IOException {
    FileObject root = findSourceRoot(project);
    ClassPathProvider provider = project.getLookup().lookup(
            ClassPathProvider.class);
    ClassPath sourceCp = provider.findClassPath(root, ClassPath.SOURCE);
    ClassPath compileCp = provider.findClassPath(root, ClassPath.COMPILE);
    ClassPath bootCp = provider.findClassPath(root, ClassPath.BOOT);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootCp, compileCp, sourceCp);
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = qualifiedClassName.lastIndexOf('.') + 1;
    String simple = qualifiedClassName.substring(beginIndex);
    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME,
            EnumSet.of(ClassIndex.SearchScope.SOURCE,
                    ClassIndex.SearchScope.DEPENDENCIES));
    for (final ElementHandle<TypeElement> handle : handles) {
        if (qualifiedClassName.equals(handle.getQualifiedName())) {
            return handle;
        }
    }
    return null;
}
 
Example #17
Source File: ProjectHelper.java    From jeddict with Apache License 2.0 6 votes vote down vote up
public static ElementHandle<TypeElement> getHandleClassName(String qualifiedClassName,
        SourceGroup sourceGroup) throws IOException {
    ClassPath rcp = ClassPathSupport.createClassPath(sourceGroup.getRootFolder());
    ClasspathInfo cpInfo = ClasspathInfo.create(ClassPath.EMPTY, ClassPath.EMPTY, rcp);
    ClassIndex ci = cpInfo.getClassIndex();
    int beginIndex = qualifiedClassName.lastIndexOf('.') + 1;
    String simple = qualifiedClassName.substring(beginIndex);

    Set<ElementHandle<TypeElement>> handles = ci.getDeclaredTypes(
            simple, ClassIndex.NameKind.SIMPLE_NAME,
            EnumSet.of(ClassIndex.SearchScope.SOURCE));
    for (final ElementHandle<TypeElement> handle : handles) {
        if (qualifiedClassName.equals(handle.getQualifiedName())) {
            return handle;
        }
    }

    return null;
}
 
Example #18
Source File: JavaTypeProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public  boolean collectDeclaredTypes(
    @NullAllowed final Pattern packageName,
    @NonNull final String typeName,
    @NonNull NameKind kind,
    @NonNull Collection<? super JavaTypeDescription> collector) throws IOException, InterruptedException {
    if (!initIndex()) {
        return false;
    }
    final SearchScope baseSearchScope = isBinary ? ClassIndex.SearchScope.DEPENDENCIES : ClassIndex.SearchScope.SOURCE;
    SearchScopeType searchScope;
    if (packageName != null) {
        //FQN
        final Set<String> allPackages = new HashSet<>();
        index.getPackageNames("", false, allPackages);  //NOI18N
        final Set<? extends String> packages = filterPackages(packageName, allPackages);
        searchScope = ClassIndex.createPackageSearchScope(baseSearchScope, packages.toArray(new String[packages.size()]));
        kind = translateSearchType(typeName, kind);
    } else {
        //simple name
        searchScope = baseSearchScope;
    }
    try {
        index.getDeclaredElements(
            typeName,
            kind,
            Collections.unmodifiableSet(Collections.<SearchScopeType>singleton(searchScope)),
            DocumentUtil.declaredTypesFieldSelector(true, true),
            new JavaTypeDescriptionConvertor(this),
            collector);
    } catch (Index.IndexClosedException ice) {
        //Closed after put into rootCache, ignore
    }
    return true;
}
 
Example #19
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void completeClassOrPkg(String fqn, String prefix, int substitutionOffset, JavadocContext jdctx) {
    String pkgPrefix;
    if (fqn == null) {
        pkgPrefix = prefix;
        addTypes(EnumSet.<ElementKind>of(CLASS, INTERFACE, ENUM, ANNOTATION_TYPE),
                null, null, prefix, substitutionOffset, jdctx);
        
    } else {
        pkgPrefix = fqn + '.' + prefix;
        PackageElement pkgElm = jdctx.javac.getElements().getPackageElement(fqn);
        if (pkgElm != null) {
            addPackageContent(pkgElm,
                    EnumSet.<ElementKind>of(CLASS, INTERFACE, ENUM, ANNOTATION_TYPE),
                    null, null, prefix, substitutionOffset, jdctx);
        }
        
        TypeElement typeElm = jdctx.javac.getElements().getTypeElement(fqn);
        if (typeElm != null) {
            // inner classes
            addInnerClasses(typeElm,
                    EnumSet.<ElementKind>of(CLASS, INTERFACE, ENUM, ANNOTATION_TYPE),
                    null, null, prefix, substitutionOffset, jdctx);
        }
    }
    
    for (String pkgName : jdctx.javac.getClasspathInfo().getClassIndex().getPackageNames(pkgPrefix, true, EnumSet.allOf(ClassIndex.SearchScope.class)))
        if (pkgName.length() > 0 && !Utilities.isExcluded(pkgName + "."))
            items.add(JavaCompletionItem.createPackageItem(pkgName, substitutionOffset, false));
}
 
Example #20
Source File: ProjectUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all types (classes) defined on the given source roots
 */
private static Set<ElementHandle<TypeElement>> getProjectTypes(FileObject[] roots, JavaSource js) {
    final Set<ClassIndex.SearchScope> scope = new HashSet<ClassIndex.SearchScope>();
    scope.add(ClassIndex.SearchScope.SOURCE);

    if (js != null) {
        return js.getClasspathInfo().getClassIndex().getDeclaredTypes("", ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX, scope); // NOI18N
    }

    return null;
}
 
Example #21
Source File: ImportHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Set<ImportCandidate> findJavaImportCandidates(FileObject fo, String packageName, String missingClass) {
    final Set<ImportCandidate> candidates = new HashSet<>();
    final ClasspathInfo pathInfo = createClasspathInfo(fo);

    Set<ElementHandle<TypeElement>> typeNames = pathInfo.getClassIndex().getDeclaredTypes(
            missingClass, NameKind.SIMPLE_NAME, EnumSet.allOf(ClassIndex.SearchScope.class));

    for (ElementHandle<TypeElement> typeName : typeNames) {
        ElementKind kind = typeName.getKind();

        // Skip classes within the same package
        String pkgName = GroovyUtils.stripClassName(typeName.getQualifiedName());
        if (packageName == null && pkgName == null) {
            // Probably both in default package
            continue;
        }

        if (packageName != null && packageName.equals(pkgName)) {
            continue;
        }

        if (kind == ElementKind.CLASS || kind == ElementKind.INTERFACE || kind == ElementKind.ANNOTATION_TYPE) {
            candidates.add(createImportCandidate(missingClass, typeName.getQualifiedName(), kind));
        }
    }
    return candidates;
}
 
Example #22
Source File: ELJavaCompletion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addPackages(CompilationController controler, String fqnPrefix, int offset, final List<CompletionProposal> proposals) {
    if (fqnPrefix == null || fqnPrefix.isEmpty()) {
        fqnPrefix = "java"; //NOI18N
    }
    for (String pkgName : controler.getClasspathInfo().getClassIndex().getPackageNames(
            fqnPrefix, true, EnumSet.allOf(ClassIndex.SearchScope.class))) {
        if (isImportedPackage(pkgName)) {
            proposals.add(new JavaPackageCompletionItem(pkgName, offset));
        }
    }
}
 
Example #23
Source File: JsfAttributesCompletionHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void addPackages(CompletionContext context, CompilationController controler, List<CompletionItem> items, String prefix) {
    int dotOffset = prefix.lastIndexOf('.');
    for (String pkgName : controler.getClasspathInfo().getClassIndex().getPackageNames(prefix, true, EnumSet.of(ClassIndex.SearchScope.SOURCE))) {
        items.add(HtmlCompletionItem.createAttributeValue(
                pkgName.substring(dotOffset == -1 ? 0 : dotOffset + 1),
                context.getCCItemStartOffset() + (dotOffset == -1 ? 0 : dotOffset + 1)));
    }
}
 
Example #24
Source File: ComponentMethodModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void registerListeners() {
    try {
        JavaSource javaSource = JavaSource.create(cpInfo);
        javaSource.runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                ClassIndex classIndex = controller.getClasspathInfo().getClassIndex();
                classIndex.addClassIndexListener(classIndexListener);
            }
        }, true);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
}
 
Example #25
Source File: ComponentMethodModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void removeListeners() {
    try {
        JavaSource javaSource = JavaSource.create(cpInfo);
        javaSource.runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                ClassIndex classIndex = controller.getClasspathInfo().getClassIndex();
                classIndex.removeClassIndexListener(classIndexListener);
            }
        }, true);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
}
 
Example #26
Source File: FieldInjectionPointLogic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Set<TypeElement> doGetImplementors( 
        WebBeansModelImplementation modelImpl, TypeElement typeElement, AtomicBoolean cancel )
{
    Set<TypeElement> result = new HashSet<TypeElement>();
    ElementHandle<TypeElement> handle = ElementHandle
            .create((TypeElement) typeElement);
    ClassIndex classIndex = modelImpl
            .getHelper().getClasspathInfo().getClassIndex();
    if(cancel.get()) {
        return Collections.emptySet();
    }
    final Set<ElementHandle<TypeElement>> handles = classIndex
            .getElements(
                    handle,
                    EnumSet.of(SearchKind.IMPLEMENTORS),
                    EnumSet.of(SearchScope.SOURCE,
                            SearchScope.DEPENDENCIES));
    if (handles == null) {
        LOGGER.log(Level.WARNING,
                "ClassIndex.getElements() was interrupted"); // NOI18N
        return Collections.emptySet();
    }
    for (ElementHandle<TypeElement> elementHandle : handles) {
        if(cancel.get()) {
            return Collections.emptySet();
        }
        LOGGER.log(Level.FINE, "found derived element {0}",
                elementHandle.getQualifiedName()); // NOI18N
        TypeElement derivedElement = elementHandle.resolve(modelImpl
                .getHelper().getCompilationController());
        if (derivedElement == null) {
            continue;
        }
        result.add(derivedElement);
    }
    return result;
}
 
Example #27
Source File: ImportCompleter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
    public List<CompletionItem> complete() {
        if (ctx.getType() == CompletionContext.Type.INSTRUCTION_TARGET || ctx.getType() == CompletionContext.Type.ROOT) {
            CompletionItem item = completeTarget();
            return item != null ? Collections.singletonList(completeTarget()) : null;
        }
        results = new ArrayList<CompletionItem>();
        
        Set<String> packages = ctx.getClasspathInfo().getClassIndex().getPackageNames(ctx.getPrefix(), true, 
                EnumSet.of(ClassIndex.SearchScope.SOURCE, ClassIndex.SearchScope.DEPENDENCIES));

        if (!"".equals(ctx.getPrefix())) {
            if (ctx.getPrefix().endsWith("*")) {
                return null;
            }
            if (ctx.getPrefix().endsWith(".")) {
                PackageElement pel = ctx.getCompilationInfo().getElements().getPackageElement(ctx.getPrefix().substring(0, ctx.getPrefix().length() - 1));
                if (pel != null) {
                    List<?> els = pel.getEnclosedElements();
                    if (!els.isEmpty()) {
                        results.add(new PackageItem(ctx, ctx.getPrefix() + "*"));
                    }
                }
            }
        }
        for (String s : packages) {
//            results.add(JavaCompletionItem.createPackageItem(s, ctx.getStartOffset(), true));
            results.add(new PackageItem(ctx, s));
        }
        
        return results;
    }
 
Example #28
Source File: ClassCompleter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
Set<ElementHandle<TypeElement>> loadDescenantsOfNode() {
    if (namePrefix.length() < PREFIX_TRESHOLD) {
        return loadDescenantsOfNode2();
    }
    TypeElement baseClass = getBaseClass();
    if (baseClass == null) {
        return Collections.emptySet();
    }
    Set<ElementHandle<TypeElement>> handles = new HashSet<ElementHandle<TypeElement>>();

    Set<ElementHandle<TypeElement>> els = ctx.getClasspathInfo().getClassIndex().
            getDeclaredTypes(namePrefix, ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX, 
            EnumSet.of(ClassIndex.SearchScope.DEPENDENCIES, ClassIndex.SearchScope.SOURCE));
    TypeMirror nodeType = baseClass.asType();
    for (Iterator<ElementHandle<TypeElement>> it = els.iterator(); it.hasNext(); ) {
        ElementHandle<TypeElement> h = it.next();
        TypeElement e = h.resolve(ctx.getCompilationInfo());
        if (e == null ||
            !acceptsQName(e.getQualifiedName(), e.getSimpleName()) ||
            e.getModifiers().contains(Modifier.ABSTRACT) ||
            !FxClassUtils.isFxmlAccessible(e) ||
            !ctx.getCompilationInfo().getTypes().isAssignable(e.asType(), nodeType)) {
                continue;
        }
        handles.add(h);
    }
    return handles;
}
 
Example #29
Source File: ClassCompleter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Set<ElementHandle<TypeElement>> loadFromAllTypes() {
    ClasspathInfo info = ctx.getClasspathInfo();
    Set<ElementHandle<TypeElement>> els = 
            new HashSet<ElementHandle<TypeElement>>(
                info.getClassIndex().getDeclaredTypes(namePrefix, ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX, 
                EnumSet.of(ClassIndex.SearchScope.DEPENDENCIES, ClassIndex.SearchScope.SOURCE)
            ));

    TypeMirror pt = getPropertyType();
    if (pt == null) {
        return els;
    }
    for (Iterator<ElementHandle<TypeElement>> it = els.iterator(); it.hasNext(); ) {
        ElementHandle<TypeElement> teh = it.next();
        String qn = teh.getQualifiedName();
        int lastDot = qn.lastIndexOf('.');
        String sn = lastDot == -1 ? qn : qn.substring(lastDot + 1);
        if (!acceptsQName(qn, sn)) {
            continue;
        }
        TypeElement t = teh.resolve(ctx.getCompilationInfo());
        if (t == null || 
            !acceptsType(t)) {
            it.remove();
        }
    }
    return els;
}
 
Example #30
Source File: ExceptionCompletionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<DeclaredType> fillSubTypes(CompilationController cc, DeclaredType dType) {
    List<DeclaredType> subtypes = new ArrayList<>();
    //Set<? extends SearchScopeType> scope = Collections.singleton(new ClassSearchScopeType(prefix));
    Types types = cc.getTypes();
    if (prefix != null && prefix.length() > 2 && lastPrefixDot < 0) {
        //Trees trees = cc.getTrees();
        ClassIndex.NameKind kind = ClassIndex.NameKind.CASE_INSENSITIVE_PREFIX;
        for (ElementHandle<TypeElement> handle : cpi.getClassIndex().getDeclaredTypes(prefix, kind, EnumSet.allOf(ClassIndex.SearchScope.class))) {
            TypeElement te = handle.resolve(cc);
            if (te != null && /*trees.isAccessible(scope, te) &&*/ types.isSubtype(types.getDeclaredType(te), dType)) {
                subtypes.add(types.getDeclaredType(te));
            }
        }
    } else {
        HashSet<TypeElement> elems = new HashSet<>();
        LinkedList<DeclaredType> bases = new LinkedList<>();
        bases.add(dType);
        ClassIndex index = cpi.getClassIndex();
        while (!bases.isEmpty()) {
            DeclaredType head = bases.remove();
            TypeElement elem = (TypeElement) head.asElement();
            if (!elems.add(elem)) {
                continue;
            }
            if (accept(elem)) {
                subtypes.add(head);
            }
            //List<? extends TypeMirror> tas = head.getTypeArguments();
            //boolean isRaw = !tas.iterator().hasNext();
            for (ElementHandle<TypeElement> eh : index.getElements(ElementHandle.create(elem), EnumSet.of(ClassIndex.SearchKind.IMPLEMENTORS), EnumSet.allOf(ClassIndex.SearchScope.class))) {
                TypeElement e = eh.resolve(cc);
                if (e != null) {
                    DeclaredType dt = types.getDeclaredType(e);
                    bases.add(dt);
                }
            }
        }
    }
    return subtypes;
}