Java Code Examples for org.netbeans.api.project.SourceGroup#getRootFolder()

The following examples show how to use org.netbeans.api.project.SourceGroup#getRootFolder() . 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: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<JavaSource> getJavaSources(Project project) {
    List<JavaSource> result = new ArrayList<JavaSource>();
    SourceGroup[] groups = SourceGroupSupport.getJavaSourceGroups(project);

    for (SourceGroup group : groups) {
        FileObject root = group.getRootFolder();
        Enumeration<? extends FileObject> files = root.getData(true);

        while (files.hasMoreElements()) {
            FileObject fobj = files.nextElement();

            if (fobj.getExt().equals(JAVA_EXT)) {
                JavaSource source = JavaSource.forFileObject(fobj);
                result.add(source);
            }
        }
    }

    return result;
}
 
Example 2
Source File: FreeformTemplateAttributesProviderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAttributesFor() throws Exception {
    FileObject projdir = egdirFO.getFileObject("simplewithlicense");
    Project simpleWithLicense = ProjectManager.getDefault().findProject(projdir);
    CreateFromTemplateAttributesProvider provider = simpleWithLicense.getLookup().lookup(CreateFromTemplateAttributesProvider.class);
    SourceGroup[] groups = ProjectUtils.getSources(simpleWithLicense).getSourceGroups("java"); // JavaProjectConstants.SOURCES_TYPE_JAVA
    for (SourceGroup group : groups) {
        FileObject root = group.getRootFolder();
        Map result = provider.attributesFor(null, DataFolder.findFolder(root), null);
        assertEquals(1, result.size());
        Map values = (Map)result.get("project");
        if (root.getName().equals("src")) {
            Map<String, String> expected = new HashMap<String, String>();
            expected.put("license", "cddl-netbeans-sun");
            expected.put("encoding", "UTF-8");
            assertEquals(expected, values);
        } else {
            assertEquals(Collections.singletonMap("license", "cddl-netbeans-sun"), values);
        }
    }
}
 
Example 3
Source File: PackageRootNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private PackageRootNode( SourceGroup group, Children ch) {
    super(ch, new ProxyLookup(createLookup(group), Lookups.singleton(
            SearchInfoDefinitionFactory.createSearchInfoBySubnodes(ch))));
    this.group = group;
    file = group.getRootFolder();
    files = Collections.singleton(file);
    try {
        FileSystem fs = file.getFileSystem();
        fileSystemListener = FileUtil.weakFileStatusListener(this, fs);
        fs.addFileStatusListener(fileSystemListener);
    } catch (FileStateInvalidException e) {            
        Exceptions.printStackTrace(Exceptions.attachMessage(e,"Can not get " + file + " filesystem, ignoring...")); //NOI18N
    }
    setName( group.getName() );
    setDisplayName( group.getDisplayName() );        
    // setIconBase("org/netbeans/modules/java/j2seproject/ui/resources/packageRoot");
}
 
Example 4
Source File: SelectorUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** 
  * Prepare node structure showing sources 
  * @param prj the project to select from
  * @param filter NodeFilter used to filter only relevant information
  * @return root Node of source files from <code>prj</code> filtered
  * by <code>filter</code>
  **/
 static public Node sourcesNode(Project prj, FilteredNode.NodeFilter filter) {
     Sources src = ProjectUtils.getSources(prj);
     SourceGroup[] srcgrps = src.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
     java.util.List<Node> nodes = new ArrayList<Node>();      
     for (SourceGroup srcGrp : srcgrps) {
try {
  FileObject rfo = srcGrp.getRootFolder();
  FilteredNode node = new FilteredNode(DataObject.find(rfo).getNodeDelegate(),
				       filter);
  //	  node.setName(srcGrp.getName());
  node.setDisplayName(srcGrp.getDisplayName());
  //	node.setIcon(srcGrp.getIcon());
				     
  nodes.add(node);
} catch (org.openide.loaders.DataObjectNotFoundException ex) {}
     }

     return createRootFor(nodes, prj);
 }
 
Example 5
Source File: DefaultPlugin.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a Java source group the given file belongs to.
 * 
 * @param  file  {@literal FileObject} to find a {@literal SourceGroup} for
 * @return  the found {@literal SourceGroup}, or {@literal null} if the given
 *          file does not belong to any Java source group
 */
private static SourceGroup findSourceGroup(FileObject file) {
    final Project project = FileOwnerQuery.getOwner(file);
    if (project == null) {
        return null;
    }

    Sources src = ProjectUtils.getSources(project);
    SourceGroup[] srcGrps = src.getSourceGroups(SOURCES_TYPE_JAVA);
    for (SourceGroup srcGrp : srcGrps) {
        FileObject rootFolder = srcGrp.getRootFolder();
        if (((file == rootFolder) || FileUtil.isParentOf(rootFolder, file)) 
                && srcGrp.contains(file)) {
            return srcGrp;
        }
    }
    return null;
}
 
Example 6
Source File: MainProjectManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("DMI_COLLECTION_OF_URLS")
private static Set<URL> getProjectRoots(Project p) {
    Set<URL> projectRoots = new HashSet<URL>(); // roots
    Sources sources = ProjectUtils.getSources(p);
    SourceGroup[] sgs = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (SourceGroup sg : sgs) {
        URL root;
        try {
            root = sg.getRootFolder().toURL();
            projectRoots.add(root);
        } catch (NullPointerException npe) {
            // http://www.netbeans.org/issues/show_bug.cgi?id=148076
            if (sg == null) {
                npe = Exceptions.attachMessage(npe, "Null source group returned from "+sources+" of class "+sources.getClass());
            } else if (sg.getRootFolder() == null) {
                npe = Exceptions.attachMessage(npe, "Null root folder returned from "+sg+" of class "+sg.getClass());
            }
            Exceptions.printStackTrace(npe);
        }
    }
    return projectRoots;
}
 
Example 7
Source File: SourceMapsScanner.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void init(Project p) {
    Sources sources = ProjectUtils.getSources(p);
    sources.addChangeListener(this);
    SourceGroup[] groups = sources.getSourceGroups(Sources.TYPE_GENERIC);
    roots = new FileObject[groups.length];
    for (int i = 0; i < groups.length; i++) {
        SourceGroup group = groups[i];
        FileObject rootFolder = group.getRootFolder();
        roots[i] = rootFolder;
        rootFolder.addRecursiveListener(this);
        //scan(rootFolder);
        rootsToScan.add(rootFolder);
    }
    scanningTask = RP.post(this);
    DependencyProjectProvider prov = p.getLookup().lookup(DependencyProjectProvider.class);
    if (prov != null) {
        projectDependencyManager = new ProjectDependencyManager(prov);
    }
}
 
Example 8
Source File: JavaUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a Java source group the given file belongs to.
 * 
 * @param  file  {@literal FileObject} to find a {@literal SourceGroup} for
 * @return  the found {@literal SourceGroup}, or {@literal null} if the given
 *          file does not belong to any Java source group
 */
private static SourceGroup findSourceGroup(FileObject file) {
    final Project project = FileOwnerQuery.getOwner(file);
    if (project == null) {
        return null;
    }

    Sources src = ProjectUtils.getSources(project);
    SourceGroup[] srcGrps = src.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (SourceGroup srcGrp : srcGrps) {
        FileObject rootFolder = srcGrp.getRootFolder();
        if (((file == rootFolder) || FileUtil.isParentOf(rootFolder, file)) 
                && srcGrp.contains(file)) {
            return srcGrp;
        }
    }
    return null;
}
 
Example 9
Source File: NbUtils.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public static boolean isFileInProjectScope (@Nonnull final Project project, @Nonnull final FileObject file) {
  final FileObject projectFolder = project.getProjectDirectory();

  if (FileUtil.isParentOf(projectFolder, file)) {
    for (final SourceGroup srcGroup : findAllSourceGroups(project)) {
      final FileObject root = srcGroup.getRootFolder();
      if (root != null) {
        if (FileUtil.isParentOf(root, file)) {
          return true;
        }
      }
    }
    return false;
  }
  else {
    return false;
  }
}
 
Example 10
Source File: PhysicalView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@CheckForNull
static Node createNodeForSourceGroup(
        @NonNull final SourceGroup group,
        @NonNull final Project project) {
    if ("sharedlibraries".equals(group.getName())) { //NOI18N
        //HACK - ignore shared libs group in UI, it's only useful for version control commits.
        return null;
    }
    final FileObject rootFolder = group.getRootFolder();
    if (!rootFolder.isValid() || !rootFolder.isFolder()) {
        return null;
    }
    final FileObject projectDirectory = project.getProjectDirectory();
    return new ProjectIconNode(new GroupNode(
            project,
            group,
            projectDirectory.equals(rootFolder) || FileUtil.isParentOf(rootFolder, projectDirectory),
            DataFolder.findFolder(rootFolder)),
            true);
}
 
Example 11
Source File: JaxWsServiceCreator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ClassPath getClassPathForFile(Project project, FileObject file) {
    SourceGroup[] srcGroups = ProjectUtils.getSources(project).
        getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (SourceGroup srcGroup: srcGroups) {
        FileObject srcRoot = srcGroup.getRootFolder();
        if (FileUtil.isParentOf(srcRoot, file)) {
            return ClassPath.getClassPath(srcRoot, ClassPath.SOURCE);
        }
    }
    return null;
}
 
Example 12
Source File: LibrariesNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static SourceGroup findSourceGroup(FileObject fo, ClassPathModifier modifierImpl) {
    SourceGroup[]sgs = modifierImpl.getExtensibleSourceGroups();
    for (SourceGroup sg : sgs) {
        if ((fo == sg.getRootFolder() || FileUtil.isParentOf(sg.getRootFolder(),fo)) && sg.contains(fo)) {
            return sg;
        }
    }
    throw new AssertionError("Cannot find source group for '"+fo+"' in "+Arrays.asList(sgs)); // NOI18N
}
 
Example 13
Source File: DefaultPlugin.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 
 */
@Override
protected boolean canCreateTests(FileObject... fileObjects) {
    if (fileObjects.length == 0) {
        return false;
    }

    final FileObject firstFile = fileObjects[0];
    final SourceGroup sourceGroup = findSourceGroup(firstFile);
    if (sourceGroup == null) {
        return false;
    }
    final FileObject rootFolder = sourceGroup.getRootFolder();
    if (UnitTestForSourceQuery.findUnitTests(rootFolder).length == 0) {
        return false;
    }

    /*
     * Now we know that source folder of the first file has a corresponding
     * test folder (possible non-existent).
     */
    if (fileObjects.length == 1) {
        /* ... if there is just one file selected, it is all we need: */
        return true;
    }

    /*
     * ...for multiple files, we just check that all the selected files
     * have the same root folder:
     */
    for (int i = 1; i < fileObjects.length; i++) {
        FileObject fileObj = fileObjects[i];
        if (!FileUtil.isParentOf(rootFolder, fileObj)
                || !sourceGroup.contains(fileObj)) {
            return false;
        }
    }
    return true;
}
 
Example 14
Source File: AbstractProjectSearchScope.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Create default search info for a project.
 */
static SearchInfo createDefaultProjectSearchInfo(Project project) {
    Sources sources = ProjectUtils.getSources(project);
    SourceGroup[] sourceGroups = sources.getSourceGroups(
            Sources.TYPE_GENERIC);

    FileObject base = project.getProjectDirectory();
    List<FileObject> roots = new ArrayList<FileObject>();
    if (base != null) {
        roots.add(base);
    }
    for (SourceGroup sg : sourceGroups) {
        FileObject dir = sg.getRootFolder();
        if (dir != null && (base == null || !isUnderBase(base, dir))) {
            roots.add(dir);
        }
    }
    FileObject[] rootArray = new FileObject[roots.size()];
    for (int i = 0; i < roots.size(); i++) {
        rootArray[i] = roots.get(i);
    }
    SubTreeSearchOptions stso =
            project.getLookup().lookup(SubTreeSearchOptions.class);
    if (stso == null) {
        return SearchInfoUtils.createSearchInfoForRoots(rootArray);
    } else {
        return SearchInfoUtils.createSearchInfoForRoots(rootArray, false,
                SearchInfoHelper.subTreeFilters(stso));
    }
}
 
Example 15
Source File: DBScriptPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid() {
    SourceGroup sourceGroup = getComponent().getLocationValue();
    if (sourceGroup == null) {
        setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_SelectSourceGroup"));
        return false;
    }
    
    String packageName = getComponent().getPackageName();
    if (packageName.trim().equals("")) { // NOI18N
        setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_CantUseDefaultPackage"));
        return false;
    }
    
    if (!JavaIdentifiers.isValidPackageName(packageName)) {
        setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_InvalidPackage")); //NOI18N
        return false;
    }
    
    if (!SourceGroups.isFolderWritable(sourceGroup, packageName)) {
        setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_UnwritablePackage")); //NOI18N
        return false;
    }

    // issue 92192: need to check that we will have a persistence provider
    // available to add to the classpath while generating entity classes (unless
    // the classpath already contains one)
    ClassPath classPath = null;
    FileObject rPackageFO = null;
    try {
        FileObject packageFO = SourceGroups.getFolderForPackage(sourceGroup, packageName, false);
        rPackageFO = packageFO;
        if (packageFO == null) {
            packageFO = sourceGroup.getRootFolder();
        }
        classPath = ClassPath.getClassPath(packageFO, ClassPath.COMPILE);
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, null, e);
    }
    if (classPath != null) {
        if (classPath.findResource("javax/persistence/EntityManager.class") == null) { // NOI18N
            // initialize the provider list lazily
            if (providers == null) {
                providers = PersistenceLibrarySupport.getProvidersFromLibraries();
            }
            if (providers.isEmpty()) {
                setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_NoJavaPersistenceAPI")); // NOI18N
                return false;
            }
        }
    } else {
        LOGGER.log(Level.WARNING, "Cannot get a classpath for package {0} in {1}", new Object[]{packageName, sourceGroup}); // NOI18N
    }
    String name = getComponent().getScriptName().trim();
    if (name.length() == 0) {
        setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_InvalidNameLength0"));//NOI18N
        return false;
    }
    if (rPackageFO != null) {
        //check if file exist
        if (name.endsWith("." + EXTENSION)) {
            name = name.substring(0, name.length() - 4);
        }
        if (rPackageFO.getFileObject(name, EXTENSION) != null) {
            setErrorMessage(NbBundle.getMessage(DBScriptPanel.class, "ERR_JavaTargetChooser_InvalidNameExists", name));//NOI18N
            return false;
        }
    }
    if(deepVerify) {
        PersistenceEnvironment pe = project.getLookup().lookup(PersistenceEnvironment.class);
        List<String> problems = DBScriptWizard.run(project, null, pe, null, true);
        if(problems != null && !problems.isEmpty()){
            setErrorMessage(problems.get(0));
            return false;
        }
        deepVerify = false;
    }
    setErrorMessage(" "); // NOI18N
    return true;
}
 
Example 16
Source File: TemplatesImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public TemplatesImpl(GrailsProject project, SourceGroup sourceGroup) {
    FileObject projectDir = project.getProjectDirectory();
    FileObject rootFolder = sourceGroup.getRootFolder();

    sourceCategory = GrailsArtifacts.getCategoryTypeForFolder(projectDir, rootFolder, project.getSourceCategoriesFactory());
}
 
Example 17
Source File: SimpleTestStepLocation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 */
void setUp(final JUnitUtils utils) {
    final Project project = utils.getProject();
    
    if (project == this.project) {
        return;
    }
    
    this.project = project;
    this.sourcesToTestsMap = utils.getSourcesToTestsMap(true);
    
    int sourceGroupsCnt = sourcesToTestsMap.size();
    Set<Map.Entry<SourceGroup,Object[]>> mapEntries = sourcesToTestsMap.entrySet();
    List<SourceGroup> testGroups = new ArrayList<SourceGroup>(sourceGroupsCnt + 4);
    
    testableSourceGroups = new SourceGroup[sourceGroupsCnt];
    testableSourceGroupsRoots = new FileObject[sourceGroupsCnt];
    multipleSourceRoots = (sourceGroupsCnt > 1);
    
    Iterator<Map.Entry<SourceGroup,Object[]>> iterator = mapEntries.iterator();
    for (int i = 0; i < sourceGroupsCnt; i++) {
        Map.Entry<SourceGroup,Object[]> entry = iterator.next();
        SourceGroup srcGroup = entry.getKey();
        
        testableSourceGroups[i] = srcGroup;
        testableSourceGroupsRoots[i] = srcGroup.getRootFolder();
        
        Object[] testGroupsSubset = entry.getValue();
        for (int j = 0; j < testGroupsSubset.length; j++) {
            SourceGroup testGroup = (SourceGroup) testGroupsSubset[j];
            if (!testGroups.contains(testGroup)) {
                testGroups.add(testGroup);
            }
        }
    }
    allTestSourceGroups = testGroups.toArray(
                                        new SourceGroup[testGroups.size()]);
    
    tfProjectName.setText(
            ProjectUtils.getInformation(project).getDisplayName());
    try {
        programmaticChange = true;
        
        ignoreClsNameChanges = true;
        tfClassToTest.setText("");                                  //NOI18N
        ignoreClsNameChanges = false;
        
        classNameLength = 0;
        classNameChanged();
        srcGroupNameDisplayed = false;
        setNavigationFilterEnabled(false);
    } finally {
        ignoreClsNameChanges = false;
        programmaticChange = false;
    }
    if (checkClassNameValidity()) {
        checkSelectedClassExists();
    } else {
        classExists = false;
    }
    setErrorMsg(errMsg);
    setValidity();
    
    //PENDING - if possible, we should pre-set the test source group
    //          corresponding to the currently selected node
    updateLocationComboBox();
    updateTargetFolderData();           //sets also 'testRootFolder'
    updateCreatedFileName();
    
    srcFile = null;
    
    if (!multipleSourceRoots) {
        setInteractionRestrictionsEnabled(false);
    } else {
        AbstractDocument doc = (AbstractDocument)
                               tfClassToTest.getDocument();
        if (clsNameDocumentFilter == null) {
            clsNameDocumentFilter = new ClsNameDocumentFilter();
        }
        if (doc.getDocumentFilter() != clsNameDocumentFilter) {
            doc.setDocumentFilter(clsNameDocumentFilter);
        }
        setInteractionRestrictionsEnabled(true);
    }
}
 
Example 18
Source File: ResourceBundles.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Map<String, ResourceBundleInfo> createResourceBundleMapAndFileChangeListeners() {
    Map<String, ResourceBundleInfo> result = new HashMap<>();
    ClassPathProvider provider = project.getLookup().lookup(ClassPathProvider.class);
    if (provider == null) {
        return null;
    }

    Sources sources = ProjectUtils.getSources(project);
    if (sources == null) {
        return null;
    }

    SourceGroup[] sourceGroups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    for (ResourceBundle bundle : getBundles(new ResolverContext())) {
        String bundleFile = bundle.getBaseName();
        for (SourceGroup sourceGroup : sourceGroups) {
            FileObject rootFolder = sourceGroup.getRootFolder();

            for (String classPathType : new String[]{ClassPath.SOURCE, ClassPath.COMPILE}) {
                ClassPath classPath = ClassPath.getClassPath(rootFolder, classPathType);
                if (classPath == null) {
                    continue;
                }
                ClassLoader classLoader = classPath.getClassLoader(false);
                try {
                    // TODO - rewrite listening on all (localized) files
                    String resourceFileName = new StringBuilder()
                            .append(bundleFile.replace(".", "/"))
                            .append(".properties")
                            .toString(); //NOI18N
                    
                    URL url = classLoader.getResource(resourceFileName);
                    if(url != null) {
                        LOGGER.finer(String.format("Found %s URL for resource bundle %s", url, resourceFileName ));
                        FileObject fileObject = URLMapper.findFileObject(url);
                        if(fileObject != null) {
                            if (fileObject.canWrite()) {
                                fileObject.addFileChangeListener(
                                        WeakListeners.create(FileChangeListener.class, FILE_CHANGE_LISTENER, fileObject));
                                LOGGER.finer(String.format("Added FileChangeListener to file %s", fileObject ));
                            }
                        } else {
                            LOGGER.fine(String.format("Cannot map %s URL to FileObject!", url));
                        }
                    }
                    
                    java.util.ResourceBundle found = java.util.ResourceBundle.getBundle(bundleFile, Locale.getDefault(), classLoader);
                    result.put(bundleFile, new ResourceBundleInfo(bundle.getFiles(), found, bundle.getVar()));
                    break; // found the bundle in source cp, skip searching compile cp
                } catch (MissingResourceException exception) {
                    continue;
                }
            }

        }
    }
    return result;
}
 
Example 19
Source File: TargetChooserPanelGUI.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public LocationItem(SourceGroup group) {
    myFileObject=group.getRootFolder();
    myGroup=group;
}
 
Example 20
Source File: JavaSourceNodeFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
SourceGroupKey(SourceGroup group, boolean trueSource) {
    this.group = group;
    this.fileObject = group.getRootFolder();
    this.trueSource = trueSource;
}