Java Code Examples for org.netbeans.api.project.Project#getProjectDirectory()

The following examples show how to use org.netbeans.api.project.Project#getProjectDirectory() . 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: FastDeploy.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private File getProjectDir(J2eeModule app) {
    try {
        FileObject fo = app.getContentDirectory();
        Project p = FileOwnerQuery.getOwner(fo);
        if (null != p) {
            fo = p.getProjectDirectory();
            return FileUtil.toFile(fo);
        }
    } catch (IOException ex) {
        Logger.getLogger("glassfish-javaee").log(Level.FINER,    // NOI18N
                null,ex);
    }
    java.io.File tmp = app.getResourceDirectory();

    if (tmp != null) {
        return tmp.getParentFile();
    }
    return null;
}
 
Example 2
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Iterable<? extends FileObject> findIndexedRootsUnderDirectory(Project p, FileObject bigRoot) {
    List<FileObject> result = new LinkedList<FileObject>();
    try {
        Iterable<? extends FileObject> roots = CacheFolder.findRootsWithCacheUnderFolder(bigRoot);

        for (FileObject root : roots) {
            Project curr = FileOwnerQuery.getOwner(root);

            if (   curr != null
                && curr.getProjectDirectory() == p.getProjectDirectory()
                && PathRegistry.getDefault().getSources().contains(root.toURL())) {
                result.add(root);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Utilities.class.getName()).log(Level.FINE, null, ex);
    }
    return result;
}
 
Example 3
Source File: PHPTypeSearcher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void initProjectInfo() {
    FileObject fo = element.getFileObject();
    if (fo != null) {
        Project p = ProjectConvertors.getNonConvertorOwner(fo);
        if (p != null) {
            if (PhpProjectUtils.isPhpProject(p)) {
                projectDirectory = p.getProjectDirectory();
            }
            ProjectInformation pi = ProjectUtils.getInformation(p);
            projectName = pi.getDisplayName();
            projectIcon = pi.getIcon();
        }
    }

    if (projectName == null) {
        projectName = "";
    }
}
 
Example 4
Source File: MMDGraphEditor.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
public FileObject getProjectFolderAsFileObject() {
  final Project proj = this.editorSupport.getProject();
  FileObject result = null;
  if (proj != null) {
    result = proj.getProjectDirectory();
  }
  return result;
}
 
Example 5
Source File: ProjectServicesImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public FileObject[] getOpenProjectsDirectories() {
    Project[] openProjects = OpenProjects.getDefault().getOpenProjects();
    if (openProjects.length == 0) {
        return null;
    }
    FileObject[] directories = new FileObject[openProjects.length];
    for (int i = 0; i < openProjects.length; i++) {
        Project project = openProjects[i];
        directories[i] = project.getProjectDirectory();
    }
    return directories;
}
 
Example 6
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
static FileObject copyBuildScript (@NonNull final Project project) throws IOException {
    final FileObject projDir = project.getProjectDirectory();
    FileObject rpBuildScript = projDir.getFileObject(BUILD_SCRIPT_PATH);
    if (rpBuildScript != null && !isBuildScriptUpToDate(project)) {
        // try to close the file just in case the file is already opened in editor
        DataObject dobj = DataObject.find(rpBuildScript);
        CloseCookie closeCookie = dobj.getLookup().lookup(CloseCookie.class);
        if (closeCookie != null) {
            closeCookie.close();
        }
        final FileObject nbproject = projDir.getFileObject("nbproject");                    //NOI18N
        final FileObject backupFile = nbproject.getFileObject(BUILD_SCRIPT_BACK_UP, "xml"); //NOI18N
        if (backupFile != null) {
            backupFile.delete();
        }
        FileUtil.moveFile(rpBuildScript, nbproject, BUILD_SCRIPT_BACK_UP);
        rpBuildScript = null;
    }
    if (rpBuildScript == null) {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.log(
                Level.FINE,
                "Updating remote build script in project {0} ({1})", //NOI18N
                new Object[]{
                    ProjectUtils.getInformation(project).getDisplayName(),
                    FileUtil.getFileDisplayName(projDir)
                });
        }
        rpBuildScript = FileUtil.createData(project.getProjectDirectory(), BUILD_SCRIPT_PATH);
        try(
            final InputStream in = new BufferedInputStream(RemotePlatformProjectSaver.class.getResourceAsStream(BUILD_SCRIPT_PROTOTYPE));
            final OutputStream out = new BufferedOutputStream(rpBuildScript.getOutputStream())) {
            FileUtil.copy(in, out);
        }
    }
    return rpBuildScript;
}
 
Example 7
Source File: AbstractPlugin.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
protected boolean doesMindMapContainFileLink(final Project project, final FileObject mindMap, final MMapURI fileToCheck) throws IOException {
  final FileObject baseFolder = project.getProjectDirectory();
  try {
    final MindMap parsedMap = new MindMap(new StringReader(mindMap.asText("UTF-8"))); //NOI18N
    return parsedMap.doesContainFileLink(FileUtil.toFile(baseFolder), fileToCheck);
  }
  catch (IllegalArgumentException ex) {
    // not mind map
    return false;
  }
}
 
Example 8
Source File: ExistingProjectWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private FileObject findMainJsFile(Project project, FileObject sourceRoot) {
    FileObject projectDir = project.getProjectDirectory();
    // first, try package.json
    String main = NodeJsSupport.forProject(project)
            .getPackageJson()
            .getContentValue(String.class, PackageJson.FIELD_MAIN);
    FileObject mainFile = getFileObject(projectDir, main);
    if (mainFile != null) {
        return mainFile;
    }
    // project name
    String projectName = ProjectUtils.getInformation(project).getName();
    mainFile = getFileObject(projectDir, projectName + ".js"); // NOI18N
    if (mainFile != null) {
        return mainFile;
    }
    mainFile = getFileObject(projectDir, projectName.toLowerCase() + ".js"); // NOI18N
    if (mainFile != null) {
        return mainFile;
    }
    // children
    HashSet<String> names = new HashSet<>(Arrays.asList(MAIN_JS_FILE_NAMES));
    FileObject first = null;
    for (FileObject child : sourceRoot.getChildren()) {
        if (!FileUtils.isJavaScriptFile(child)) {
            continue;
        }
        if (first == null) {
            first = child;
        }
        if (names.contains(child.getNameExt())) {
            return child;
        }
    }
    return first;
}
 
Example 9
Source File: ProjectTreeElement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ProjectTreeElement(Project project) {
    ProjectInformation projectInformation = ProjectUtils.getInformation(project);
    name = projectInformation.getDisplayName();
    icon = projectInformation.getIcon();
    projectReference = new WeakReference<>(project);
    projectDirectory = project.getProjectDirectory();
}
 
Example 10
Source File: ProjectHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static FileObject getFOForProjectBuildFile(Project prj) {
    FileObject buildFileFo = null;
    if (prj != null) {
        FileObject fo = prj.getProjectDirectory();
        buildFileFo = fo.getFileObject("build.xml"); //NOI18N
    }
    return buildFileFo;
}
 
Example 11
Source File: ResourceLibraryIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getNearestContractsParent(Project project) {
    WebModule wm = WebModule.getWebModule(project.getProjectDirectory());
    if (wm != null) {
        // web application
        projectType = ProjectType.WEB;
        if (wm.getDocumentBase() != null) {
            return wm.getDocumentBase();
        }
    } else {
        // j2se library
        projectType = ProjectType.J2SE;
        Sources sources = ProjectUtils.getSources(project);
        SourceGroup[] sourceGroups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        for (SourceGroup sourceGroup : sourceGroups) {
            FileObject metaInf = sourceGroup.getRootFolder().getFileObject(META_INF);
            if (metaInf != null) {
                return metaInf;
            }
        }
        if (sourceGroups.length > 0) {
            return sourceGroups[0].getRootFolder();
        }
    }

    // fallback
    return project.getProjectDirectory();
}
 
Example 12
Source File: JsTestingProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public FileObject fromServer(Project project, URL serverUrl) {
    String serverU = WebUtils.urlToString(serverUrl);
    String prefix = JsTestDriver.getServerURL();
    if (!prefix.endsWith("/")) { // NOI18N
        prefix += "/"; // NOI18N
    }
    prefix += "test/"; // NOI18N
    if (!serverU.startsWith(prefix)) {
        return null;
    }
    String projectRelativePath = serverU.substring(prefix.length());
    if (projectRelativePath.isEmpty()) {
        return null;
    }
    try {
        projectRelativePath = URLDecoder.decode(projectRelativePath, "UTF-8"); // NOI18N
    } catch (UnsupportedEncodingException ex) {
        LOGGER.log(Level.WARNING, null, ex);
    }
    // try relative project path
    FileObject projectDirectory = project.getProjectDirectory();
    FileObject fileObject = projectDirectory.getFileObject(projectRelativePath);
    if (fileObject != null) {
        return fileObject;
    }
    // try absolute url for tests outside project folder
    FileObject testsFolder = getTestsFolder(project);
    if (testsFolder != null
            && !isUnderneath(projectDirectory, testsFolder)) {
        File file = new File(projectRelativePath);
        if (file.isFile()) {
            return FileUtil.toFileObject(file);
        }
    }
    return null;
}
 
Example 13
Source File: NewJetModuleWizardIterator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private FileObject getWebRoot(Project project) {
    Collection<FileObject> webRoots = ProjectWebRootQuery.getWebRoots(project);
    if (webRoots.isEmpty()) {
        return project.getProjectDirectory();
    }
    return webRoots.iterator().next();
}
 
Example 14
Source File: RetrieverImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public FileObject retrieveResource(FileObject destinationDir, 
        URI relativePathToCatalogFile, URI resourceToRetrieve, 
        boolean save2singleFolder) 
        throws UnknownHostException, URISyntaxException, IOException {
    Project prj = FileOwnerQuery.getOwner(destinationDir);
    if(relativePathToCatalogFile == null){
        assert(prj != null);
        //check if this project has XMLCatalogProvider in its lookup
        XMLCatalogProvider catProvider = (XMLCatalogProvider) prj.getLookup().
                lookup(XMLCatalogProvider.class);
        if(catProvider == null){
            //there is no catalog provider so just use the legacy projectwide catalog approach
            return retrieveResourceImpl(destinationDir, resourceToRetrieve, null, save2singleFolder);
        }
        relativePathToCatalogFile = catProvider.getProjectWideCatalog();
        if(relativePathToCatalogFile == null){
            //somehow this provider does not give me this info. So follow legacy.
            return retrieveResourceImpl(destinationDir, resourceToRetrieve, null, save2singleFolder);
        }
        //use this relativePathToCatalogFile for the new catalog file.
    }
    URI cfuri = null;
    if(!relativePathToCatalogFile.isAbsolute()){
        if (prj != null) {
            FileObject prjRtFO = prj.getProjectDirectory();
            cfuri = FileUtil.toFile(prjRtFO).toURI().resolve(relativePathToCatalogFile);
        } else {
            // For Maven based projects the project directory doesn't contain cached catalogs. 
            //  In these cases should be used catalog.xml within destination directory.
            cfuri = destinationDir.getParent().getURL().toURI().resolve(Utilities.PRIVATE_CATALOG_URI_STR);
        }
    }else{
        cfuri = relativePathToCatalogFile;
    }
    File cffile = new File(cfuri);
    if(!cffile.isFile())
        cffile.createNewFile();
    FileObject catalogFileObject = FileUtil.toFileObject(FileUtil.normalizeFile(cffile));
    return retrieveResourceImpl(destinationDir, resourceToRetrieve, catalogFileObject, save2singleFolder);
}
 
Example 15
Source File: ClasspathInfoFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a {@linkplain ClasspathInfo} instance for the given project
 * @param prj The project to create {@linkplain ClasspathInfo} instance for
 * @param includeSubprojects Should the subprojects be included
 * @param includeSources Should the source be included
 * @param includeLibraries Should the binaries be included
 * @return Returns a {@linkplain ClasspathInfo} instance for the given project
 */
public static ClasspathInfo infoFor(Project prj, final boolean includeSubprojects,
                                    final boolean includeSources, final boolean includeLibraries) {
    FileObject[] sourceRoots = ProjectUtilities.getSourceRoots(prj, includeSubprojects);

    if (((sourceRoots == null) || (sourceRoots.length == 0)) && !includeSubprojects) {
        sourceRoots = ProjectUtilities.getSourceRoots(prj, true);
    }

    final ClassPath cpEmpty = ClassPathSupport.createClassPath(new FileObject[0]);

    ClassPath cpSource = cpEmpty;
    if (includeSources) {
        if (sourceRoots.length == 0) {
            return null; // fail early
        }

        cpSource = ClassPathSupport.createClassPath(sourceRoots);
    }
    
    FileObject someFile = sourceRoots.length>0 ? sourceRoots[0] : prj.getProjectDirectory();
    ClassPath cpCompile = cpEmpty;
    if (includeLibraries) {
        java.util.List<URL> urlList = new ArrayList<URL>();
        cpCompile = ClassPath.getClassPath(someFile, ClassPath.COMPILE);
        cpCompile = cpCompile != null ? cpCompile : cpEmpty;
        
        // cleaning up compile classpatth; we need to get rid off all project's class file references in the classpath
        for (ClassPath.Entry entry : cpCompile.entries()) {
            SourceForBinaryQuery.Result rslt = SourceForBinaryQuery.findSourceRoots(entry.getURL());
            FileObject[] roots = rslt.getRoots();

            if ((roots == null) || (roots.length == 0)) {
                urlList.add(entry.getURL());
            }
            cpCompile = ClassPathSupport.createClassPath(urlList.toArray(new URL[0]));
        }
    }

    ClassPath cpBoot = includeLibraries ? ClassPath.getClassPath(someFile, ClassPath.BOOT) : cpEmpty;
    cpBoot = cpBoot != null ? cpBoot : cpEmpty;
    
    return ClasspathInfo.create(cpBoot, cpCompile, cpSource);
}
 
Example 16
Source File: WebProjectWebRootProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public WebProjectWebRootProvider(Project project) {
    this.project = project;
    this.projectDir = project.getProjectDirectory();
}
 
Example 17
Source File: GeneratedSourceRootTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testMiscellaneousQueries() throws Exception {
    final Project p = createTestProject(true);
    ProjectManager.mutex().writeAccess(() -> {
        try {
            final UpdateHelper h = p.getLookup().lookup(TestProject.class).getUpdateHelper();
            final EditableProperties ep = h.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
            ep.setProperty("encoding", "ISO-8859-2");   //NOI18N
            h.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
            ProjectManager.getDefault().saveProject(p);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    FileObject d = p.getProjectDirectory();
    FileObject src = d.getFileObject("src");
    FileObject test = d.getFileObject("test");
    FileObject stuff = d.getFileObject("build/generated-sources/stuff");
    URL classes = new URL(d.toURL(), "build/classes/");
    URL testClasses = new URL(d.toURL(), "build/test/classes/");
    URL distJar = FileUtil.getArchiveRoot(BaseUtilities.toURI(FileUtil.normalizeFile(
            new File(FileUtil.toFile(d), "dist/x.jar".replace('/', File.separatorChar)))).toURL()); //NOI18N
    FileObject xgen = stuff.getFileObject("net/nowhere/XGen.java");
    assertEquals(Arrays.asList(src, stuff), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
    assertEquals(Arrays.asList(test), Arrays.asList(SourceForBinaryQuery.findSourceRoots(testClasses).getRoots()));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(src.toURL()).getRoots()));
    assertEquals(Collections.singletonList(testClasses), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(test.toURL()).getRoots()));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(stuff.toURL()).getRoots()));
    assertEquals(Collections.singletonList(src.toURL()), Arrays.asList(UnitTestForSourceQuery.findSources(test)));
    assertEquals(Collections.singletonList(test.toURL()), Arrays.asList(UnitTestForSourceQuery.findUnitTests(src)));
    assertEquals("1.6", SourceLevelQuery.getSourceLevel(stuff));
    FileBuiltQuery.Status status = FileBuiltQuery.getStatus(xgen);
    assertNotNull(status);
    assertFalse(status.isBuilt());
    FileUtil.createData(d, "build/classes/net/nowhere/XGen.class");
    assertTrue(status.isBuilt());
    assertEquals("ISO-8859-2", FileEncodingQuery.getEncoding(xgen).name());
    // check also dynamic changes in set of gensrc roots:
    FileObject moreStuff = FileUtil.createFolder(d, "build/generated-sources/morestuff");
    FileObject ygen = FileUtil.createData(moreStuff, "net/nowhere/YGen.java");
    assertEquals(new HashSet<FileObject>(Arrays.asList(src, stuff, moreStuff)),
            new HashSet<FileObject>(Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots())));
    assertEquals(Arrays.asList(classes, distJar), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(moreStuff.toURL()).getRoots()));
    // XXX should previously created Result objects fire changes? ideally yes, but probably unnecessary
    assertEquals("1.6", SourceLevelQuery.getSourceLevel(moreStuff));
    status = FileBuiltQuery.getStatus(ygen);
    assertNotNull(status);
    assertFalse(status.isBuilt());
    FileUtil.createData(d, "build/classes/net/nowhere/YGen.class");
    assertTrue(status.isBuilt());
    assertEquals("ISO-8859-2", FileEncodingQuery.getEncoding(ygen).name());
    d.getFileObject("build").delete();
    assertEquals(Arrays.asList(src), Arrays.asList(SourceForBinaryQuery.findSourceRoots(classes).getRoots()));
}
 
Example 18
Source File: MMKnowledgeSources.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
public static FileObject findProjectKnowledgeFolder(final Project project){
  if (project == null) return null;
  final FileObject projectFolder = project.getProjectDirectory();
  return projectFolder.getFileObject(KNOWLEDGE_FOLDER_NAME);
}
 
Example 19
Source File: AbstractPlugin.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
private Problem _processFileObject(final Project project, int level, final FileObject fileObject) {
  final Project theProject;
  if (project == null) {
    theProject = FileOwnerQuery.getOwner(fileObject);
  }
  else {
    theProject = project;
  }
  
  if (theProject == null){
    LOGGER.warn("Request process file object without a project as the owner : "+fileObject);
    return null;
  }
  
  final FileObject projectDirectory = theProject.getProjectDirectory();
  
  if (projectDirectory == null){
    LOGGER.warn("Request process file object in a project which doesn't have folder : " + fileObject+", project : "+project);
    return null;
  }
  
  final File projectFolder = FileUtil.toFile(projectDirectory);

  Problem result = processFile(theProject, level, projectFolder, fileObject);
  level++;
  if (fileObject.isFolder()) {
    for (final FileObject fo : fileObject.getChildren()) {
      if (result != null) {
        break;
      }

      if (fo.isFolder()) {
        result = _processFileObject(theProject, level, fo);
      }
      else {
        result = processFile(theProject, level, projectFolder, fo);
      }
    }
  }

  return result;
}
 
Example 20
Source File: BeansXmlIterator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileObject getTargetFolder(Project project) {
    WebModule wm = WebModule.getWebModule(project.getProjectDirectory());
    if (wm != null) {
        FileObject webInf = wm.getWebInf();
        if (webInf == null && wm.getDocumentBase() != null) {
            try {
                webInf = FileUtil.createFolder(wm.getDocumentBase(), WEB_INF); 
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        type = J2eeProjectType.WAR;
        return webInf;
    } 
    else {
        EjbJar ejbs[] = EjbJar.getEjbJars(project);
        if (ejbs.length > 0) {
            type = J2eeProjectType.JAR;
            return ejbs[0].getMetaInf();
        } else {
            Car cars[] = Car.getCars(project);
            if (cars.length > 0) {
                type = J2eeProjectType.CAR;
                return cars[0].getMetaInf();
            } 
        }
    }
    Sources sources = project.getLookup().lookup(Sources.class);
    SourceGroup[] sourceGroups = sources.getSourceGroups(
            JavaProjectConstants.SOURCES_TYPE_JAVA);
    if ( sourceGroups.length >0 ){
        FileObject metaInf = sourceGroups[0].getRootFolder().getFileObject( 
                META_INF );
        if ( metaInf == null ){
            try {
                metaInf = FileUtil.createFolder(
                    sourceGroups[0].getRootFolder(), META_INF);
            }
            catch( IOException e ){
                Exceptions.printStackTrace(e);
            }
        }
        if ( metaInf != null ){
            return metaInf;
        }
    }
    return project.getProjectDirectory();
}