Java Code Examples for org.netbeans.api.java.classpath.ClassPath#findOwnerRoot()

The following examples show how to use org.netbeans.api.java.classpath.ClassPath#findOwnerRoot() . 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: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ClassPath getSourceClassPathFor(FileObject file) {
    Pair<FileObject,Reference<ClassPath>> ce = rootCache;
    ClassPath cp;
    if (ce != null &&
        (cp = ce.second().get()) != null &&
        ce.first().equals(cp.findOwnerRoot(file))) {
        return cp;
    }
    for (String sourceCP : PathRecognizerRegistry.getDefault().getSourceIds()) {
        cp = ClassPath.getClassPath(file, sourceCP);
        if (cp != null) {
            final FileObject root = cp.findOwnerRoot(file);
            if (root != null) {
                rootCache = Pair.<FileObject,Reference<ClassPath>>of(
                    root,
                    new WeakReference<ClassPath>(cp));
            }
            return cp;
        }
    }
    return null;
}
 
Example 2
Source File: GroovyLineBreakpointFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String getGroovyPath(String url) {
    FileObject fo = getFileObjectFromUrl(url);
    String relativePath = url;

    if (fo != null) {
        ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
        if (cp == null) {
            LOGGER.log(Level.FINE, "No classpath for {0}", url);
            return null;
        }
        FileObject root = cp.findOwnerRoot(fo);
        if (root == null) {
            return null;
        }
        relativePath = FileUtil.getRelativePath(root, fo);
    }

    return relativePath;
}
 
Example 3
Source File: ProjectRunnerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@CheckForNull
private static FileObject findOwnerRoot(
    @NonNull final String className,
    @NonNull final String[] extensions,
    @NonNull final ClassPath... binCps) {
    final String binaryResource = FileObjects.convertPackage2Folder(className);
    final ClassPath merged = ClassPathSupport.createProxyClassPath(binCps);
    for (String ext : extensions) {
        final FileObject res = merged.findResource(String.format(
                "%s.%s",    //NOI18N
                binaryResource,
                ext));
        if (res != null) {
            return merged.findOwnerRoot(res);
        }
    }
    return null;
}
 
Example 4
Source File: IdentifiersUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the new refactored name for the given <code>file</code>.
 *
 * @param file the file object for the class being renamed. Excepts that
 * the target class is the public top level class in the file.
 * @param rename the refactoring, must represent either package or folder rename.
 *
 * @return the new fully qualified name for the class being refactored.
 */
public static String constructNewName(FileObject file, RenameRefactoring rename){
    Parameters.notNull("file", file); // NOI18N
    Parameters.notNull("rename", rename); // NOI18N

    String fqn = getQualifiedName(file);

    if (isPackageRename(rename)){
        return rename.getNewName() + "." + unqualify(fqn);
    }

    final FileObject folder = rename.getRefactoringSource().lookup(FileObject.class);
    final ClassPath classPath = ClassPath.getClassPath(folder, ClassPath.SOURCE);
    if (classPath == null) {
        return "Cannot construct new name!"; //NOI18N
    }

    final FileObject root = classPath.findOwnerRoot(folder);

    String prefix = FileUtil.getRelativePath(root, folder.getParent()).replace('/','.'); // NOI18N
    String oldName = buildName(prefix, folder.getName());
    String newName = buildName(prefix, rename.getNewName());
    int oldNameIndex = fqn.lastIndexOf(oldName) + oldName.length();
    return newName + fqn.substring(oldNameIndex, fqn.length());

}
 
Example 5
Source File: DebugFixHooks.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String classToSourceURL(FileObject fo, PrintWriter logger) {
    ClassPath cp = ClassPath.getClassPath(fo, ClassPath.EXECUTE);
    if (cp == null) {
        return null;
    }
    FileObject root = cp.findOwnerRoot(fo);
    String resourceName = cp.getResourceName(fo, '/', false);
    if (resourceName == null || root == null) {
        logger.println("Can not find classpath resource for " + fo + ", skipping...");
        return null;
    }
    int i = resourceName.indexOf('$');
    if (i > 0) {
        resourceName = resourceName.substring(0, i);
    }
    FileObject[] sRoots = SourceForBinaryQuery.findSourceRoots(root.toURL()).getRoots();
    ClassPath sourcePath = ClassPathSupport.createClassPath(sRoots);
    FileObject rfo = sourcePath.findResource(resourceName + ".java");
    if (rfo == null) {
        return null;
    }
    return rfo.toURL().toExternalForm();
}
 
Example 6
Source File: SpringUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String getLibraryVersion(Library library, String className) {
    List<URL> urls = library.getContent("classpath"); // NOI18N
    ClassPath cp = createClassPath(urls);
    try {
        FileObject resource = cp.findResource(className.replace('.', '/') + ".class");  //NOI18N
        if (resource==null) {
            return null;
        }
        FileObject ownerRoot = cp.findOwnerRoot(resource);

        if (ownerRoot !=null) { //NOI18N
            if (ownerRoot.getFileSystem() instanceof JarFileSystem) {
                JarFileSystem jarFileSystem = (JarFileSystem) ownerRoot.getFileSystem();
                return getImplementationVersion(jarFileSystem);
            }
        }
    } catch (FileStateInvalidException e) {
        Exceptions.printStackTrace(e);
    }
    return null;
}
 
Example 7
Source File: SourceUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NonNull
private static List<Pair<FileObject, ClassPath>> findAllResources(
        @NonNull final String resourceName,
        @NonNull final Predicate<? super FileObject> rootsFilter,
        @NonNull final ClassPath... cps) {
    final List<Pair<FileObject,ClassPath>> result = new ArrayList<>();
    for (ClassPath cp : cps) {
        for (FileObject fo : cp.findAllResources(resourceName)) {
            final FileObject root = cp.findOwnerRoot(fo);
            if (root != null && rootsFilter.test(root)) {
                result.add(Pair.<FileObject,ClassPath>of(fo, cp));
            }
        }
    }
    return result;
}
 
Example 8
Source File: GoToOppositeAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether this action should be enabled for &quot;Go To Test&quot;
 * or for &quot;Go To Tested Class&quot or whether it should be disabled.
 * 
 * @return  {@code Boolean.TRUE} if this action should be enabled for
 *          &quot;Go To Test&quot;,<br />
 *          {@code Boolean.FALSE} if this action should be enabled for
 *          &quot;Go To Tested Class&quot;,<br />
 *          {@code null} if this action should be disabled
 */
private Boolean checkDirection(FileObject fileObj) {
    ClassPath srcCP;
    FileObject fileObjRoot;
    
    boolean isJavaFile = false;
    boolean sourceToTest = true;
    boolean enabled = (fileObj != null)
      && (fileObj.isFolder() || (isJavaFile = JUnitTestUtil.isJavaFile(fileObj)))
      && ((srcCP = ClassPath.getClassPath(fileObj, ClassPath.SOURCE)) != null)
      && ((fileObjRoot = srcCP.findOwnerRoot(fileObj)) != null)
      && ((UnitTestForSourceQuery.findUnitTests(fileObjRoot).length != 0)
          || (sourceToTest = false)         //side effect - assignment
          || isJavaFile && (UnitTestForSourceQuery.findSources(fileObjRoot).length != 0));
    
    return enabled ? Boolean.valueOf(sourceToTest)
                   : null;
}
 
Example 9
Source File: CallHierarchyTasks.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Iterable<? extends List<FileObject>> groupByRoot (Iterable<? extends FileObject> data) {
    Map<FileObject,List<FileObject>> result = new HashMap<FileObject,List<FileObject>> ();
    for (FileObject file : data) {
        if (isCanceled()) {
            return Collections.emptyList();
        }
        
        ClassPath cp = ClassPath.getClassPath(file, ClassPath.SOURCE);
        if (cp != null) {
            FileObject root = cp.findOwnerRoot(file);
            if (root != null) {
                if (!includeTest && UnitTestForSourceQuery.findSources(root).length > 0) {
                    continue;
                }
                List<FileObject> subr = result.get (root);
                if (subr == null) {
                    subr = new LinkedList<FileObject>();
                    result.put (root,subr);
                }
                subr.add(file);
            }
        }
    }
    return result.values();
}
 
Example 10
Source File: RefactoringUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isClasspathRoot(FileObject fo) {
    ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    if (cp != null) {
        FileObject f = cp.findOwnerRoot(fo);
        if (f != null) {
            return fo.equals(f);
        }
    }

    return false;
}
 
Example 11
Source File: JavaFixUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject findRootForFile(final FileObject file, final ClasspathInfo cpInfo) {
    ClassPath cp = ClassPathSupport.createProxyClassPath(
        new ClassPath[] {
            cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE),
            cpInfo.getClassPath(ClasspathInfo.PathKind.BOOT),
            cpInfo.getClassPath(ClasspathInfo.PathKind.COMPILE),
        });

    FileObject root = cp.findOwnerRoot(file);

    if (root != null) {
        return root;
    }

    for (ClassPath.Entry e : cp.entries()) {
        FileObject[] sourceRoots = SourceForBinaryQuery.findSourceRoots(e.getURL()).getRoots();

        if (sourceRoots.length == 0) continue;

        ClassPath sourcePath = ClassPathSupport.createClassPath(sourceRoots);

        root = sourcePath.findOwnerRoot(file);

        if (root != null) {
            return root;
        }
    }
    return null;
}
 
Example 12
Source File: SourcesModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static File getCurrentSourceRoot() {
    FileObject fo = EditorContextDispatcher.getDefault().getMostRecentFile();
    if (fo == null) {
        return null;
    }
    ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    if (cp == null) {
        return null;
    }
    fo = cp.findOwnerRoot(fo);
    if (fo == null) {
        return null;
    }
    return FileUtil.toFile(fo);
}
 
Example 13
Source File: SafeDeleteUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void deletePackage(FileObject source) {
    ClassPath classPath = ClassPath.getClassPath(source, ClassPath.SOURCE);
    FileObject root = classPath != null ? classPath.findOwnerRoot(source) : null;

    DataFolder dataFolder = DataFolder.findFolder(source);

    FileObject parent = dataFolder.getPrimaryFile().getParent();
    // First; delete all files except packages

    try {
        DataObject ch[] = dataFolder.getChildren();
        boolean empty = true;
        for (int i = 0; ch != null && i < ch.length; i++) {
            if (!ch[i].getPrimaryFile().isFolder()) {
                ch[i].delete();
            }
            else if (empty && VisibilityQuery.getDefault().isVisible(ch[i].getPrimaryFile())) {
                // 156529: hidden folders should be considered as empty content
                empty = false;
            }
        }

        // If empty delete itself
        if ( empty ) {
            dataFolder.delete();
        }

        // Second; delete empty super packages, or empty folders when there is not root
        while (!parent.equals(root) && parent.getChildren().length == 0) {
            FileObject newParent = parent.getParent();
            parent.delete();
            parent = newParent;
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

}
 
Example 14
Source File: ProjectUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Will find
 * Copied from JUnit module implementation in 4.1 and modified
 */
public static FileObject findTestForFile(final FileObject selectedFO) {
    if ((selectedFO == null) || !selectedFO.getExt().equalsIgnoreCase("java")) {
        return null; // NOI18N
    }

    ClassPath cp = ClassPath.getClassPath(selectedFO, ClassPath.SOURCE);

    if (cp == null) {
        return null;
    }

    FileObject packageRoot = cp.findOwnerRoot(selectedFO);

    if (packageRoot == null) {
        return null; // not a file in the source dirs - e.g. generated class in web app
    }

    URL[] testRoots = UnitTestForSourceQuery.findUnitTests(packageRoot);
    FileObject fileToOpen = null;

    for (int j = 0; j < testRoots.length; j++) {
        fileToOpen = findUnitTestInTestRoot(cp, selectedFO, testRoots[j]);

        if (fileToOpen != null) {
            return fileToOpen;
        }
    }

    return null;
}
 
Example 15
Source File: ElementJavadoc.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String noJavadocFound() {
    if (handle != null) {
        final List<ClassPath> cps = new ArrayList<>(2);
        ClassPath cp = cpInfo.getClassPath(ClasspathInfo.PathKind.BOOT);
        if (cp != null) {
            cps.add(cp);
        }
        cp = cpInfo.getClassPath(ClasspathInfo.PathKind.COMPILE);
        if (cp != null) {
            cps.add(cp);
        }
        cp = ClassPathSupport.createProxyClassPath(cps.toArray(new ClassPath[cps.size()]));
        String toSearch = SourceUtils.getJVMSignature(handle)[0].replace('.', '/');
        if (handle.getKind() != ElementKind.PACKAGE) {
            toSearch += ".class"; //NOI18N
        }
        final FileObject resource = cp.findResource(toSearch);
        if (resource != null) {
            final FileObject root = cp.findOwnerRoot(resource);
            try {
                final URL rootURL = root.getURL();
                if (JavadocForBinaryQuery.findJavadoc(rootURL).getRoots().length == 0) {
                    FileObject userRoot = FileUtil.getArchiveFile(root);
                    if (userRoot == null) {
                        userRoot = root;
                    }
                    return NbBundle.getMessage(
                            ElementJavadoc.class,
                            "javadoc_content_not_found_attach",
                            rootURL.toExternalForm(),
                            FileUtil.getFileDisplayName(userRoot));
                }
            } catch (FileStateInvalidException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return NbBundle.getMessage(ElementJavadoc.class, "javadoc_content_not_found"); //NOI18N
}
 
Example 16
Source File: PlatformClassPathProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private static FileObject getArtefactOwner(
        @NonNull final FileObject file,
        @NonNull final ClassPath... cps) {
    for (ClassPath cp : cps) {
        FileObject root;
        if (cp != null && (root = cp.findOwnerRoot (file)) != null) {
            return root;
        }
    }
    return null;
}
 
Example 17
Source File: RefactoringUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param url
 * @return
 * @throws IOException
 */
public static FileObject getClassPathRoot(URL url) throws IOException {
    FileObject result = getRootFileObject(url);
    if(result == null) {
        return null;
    }
    ClassPath classPath = ClassPath.getClassPath(result, ClassPath.SOURCE);
    if(classPath == null) {
        return null;
    }
    return classPath.findOwnerRoot(result);
}
 
Example 18
Source File: SmartSteppingImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * This method is called during stepping through debugged application.
 * The execution is stopped when all registered SmartSteppingListeners
 * returns true.
 *
 * @param thread contains all available information about current position
 *        in debugged application
 * @param f a filter
 * @return true if execution should be stopped on the current position
 */
public boolean stopHere (
    ContextProvider lookupProvider, 
    JPDAThread thread, 
    SmartSteppingFilter f
) {
    String className = thread.getClassName ();
    if (className == null) return false;

    SourcePath ectx = getEngineContext (lookupProvider);
    boolean b = ectx.sourceAvailable (thread, null, false);
    if (b) return true;

    try {
        String sourcePath = thread.getSourcePath(null);
        sourcePath = sourcePath.replace(java.io.File.pathSeparatorChar, '/');
        FileObject sourceFO = GlobalPathRegistry.getDefault().findResource(sourcePath);
        if (sourceFO != null) {
            Set<ClassPath> cpaths = GlobalPathRegistry.getDefault().getPaths(ClassPath.SOURCE);
            FileObject rootFO = null;
            for (ClassPath cp : cpaths) {
                FileObject fo = cp.findOwnerRoot(sourceFO);
                if (fo != null) {
                    if (rootFO == null) {
                        rootFO = fo;
                    } else {
                        // More than one source root
                        rootFO = null;
                        break;
                    }
                }
            }
            if (rootFO != null) {
                java.io.File file = FileUtil.toFile(rootFO);
                String sourceRoot = file.getAbsolutePath();

                String[] additionalSourceRoots = ectx.getAdditionalSourceRoots();
                String[] originalSourceRoots = ectx.getOriginalSourceRoots();
                if (Arrays.asList(additionalSourceRoots).contains(sourceRoot)) {
                    // Source root is known, but disabled.
                    return false;
                }
                if (Arrays.asList(originalSourceRoots).contains(sourceRoot)) {
                    // Source root is known, but disabled.
                    return false;
                }
                String[] sourceRoots = ectx.getSourceRoots();
                String[] new_additionalSourceRoots = new String[additionalSourceRoots.length + 1];
                String[] new_sourceRoots = new String[sourceRoots.length + 1];
                System.arraycopy(additionalSourceRoots, 0, new_additionalSourceRoots, 0, additionalSourceRoots.length);
                System.arraycopy(sourceRoots, 0, new_sourceRoots, 0, sourceRoots.length);
                new_additionalSourceRoots[additionalSourceRoots.length] = sourceRoot;
                new_sourceRoots[sourceRoots.length] = sourceRoot;
                ectx.setSourceRoots(new_sourceRoots, new_additionalSourceRoots);
                return true;
            }
        }
    } catch (AbsentInformationException ex) {
    }
    
    
    // find pattern
    String name, n1 = className.replace ('.', '/');
    /*
    do {
        name = n1;
        int i = name.lastIndexOf ('/');
        if (i < 0) break;
        n1 = name.substring (0, i);
    } while (!ectx.sourceAvailable (n1, false));
           */
    name = n1;
    int i = name.lastIndexOf ('/');
    if (i > 0) {
        n1 = name.substring (0, i);
        if (!ectx.sourceAvailable (n1, false)) {
            name = n1;
        }
    }
        
    HashSet s = new HashSet ();
    s.add (name.replace ('/', '.') + ".*");
    addExclusionPatterns (s);
    return false;
}
 
Example 19
Source File: OpenTestAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected void performAction (Node[] nodes) {
    FileObject selectedFO;
    
    for (int i = 0; i < nodes.length; i++) {
        // get test class or suite class file, if it was not such one pointed by the node
        selectedFO = org.netbeans.modules.gsf.testrunner.ui.api.UICommonUtils.getFileObjectFromNode(nodes[i]);
        if (selectedFO == null) {
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class, "MSG_file_from_node_failed"));
            continue;
        }
        ClassPath cp = ClassPath.getClassPath(selectedFO, ClassPath.SOURCE);
        if (cp == null) {
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class, 
                "MSG_no_project", selectedFO));
            continue;
        }
 
        FileObject packageRoot = cp.findOwnerRoot(selectedFO);            
        URL[] testRoots = UnitTestForSourceQuery.findUnitTests(packageRoot);
        FileObject fileToOpen = null;
        for (int j = 0 ; j < testRoots.length; j++) {
            fileToOpen = findUnitTestInTestRoot(cp, selectedFO, testRoots[j]);
            if (fileToOpen != null) break;
        }
        
        if (fileToOpen != null) {
            openFile(fileToOpen);
        } else {                
            String testClsName = getTestName(cp, selectedFO).replace('/','.');                                                
            String pkgName = cp.getResourceName(selectedFO, '.', false);                
            boolean isPackage = selectedFO.isFolder();
            boolean isDefPkg = isPackage && (pkgName.length() == 0);
            String msgPattern = !isPackage
                   ? "MSG_test_class_not_found"                     //NOI18N
                   : isDefPkg
                     ? "MSG_testsuite_class_not_found_def_pkg"      //NOI18N
                     : "MSG_testsuite_class_not_found";             //NOI18N
                            
            String[] params = isDefPkg ? new String[] { testClsName }
                                       : new String[] { testClsName,
                                                        pkgName };                                                                             
                             
            JUnitTestUtil.notifyUser(NbBundle.getMessage(OpenTestAction.class,
                                                    msgPattern, params),
                                ErrorManager.INFORMATIONAL);
            continue;
        }
    }
}
 
Example 20
Source File: ProfilesAnalyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
private static FileObject findOwnerRoot(@NonNull final FileObject file) {
    final ClassPath sourcePath = ClassPath.getClassPath(file, ClassPath.SOURCE);
    return sourcePath == null ? null : sourcePath.findOwnerRoot(file);
}