org.openide.filesystems.FileObject Java Examples
The following examples show how to use
org.openide.filesystems.FileObject.
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: CssEmbeddingProviderTest.java From netbeans with Apache License 2.0 | 6 votes |
private void checkVirtualSource(String file) throws Exception { FileObject fo = getTestFile(file); assertNotNull(fo); Source source = Source.create(fo); assertNotNull(source); Snapshot snapshot = source.createSnapshot(); assertNotNull(snapshot); CssEmbeddingProvider provider = new CssEmbeddingProvider(); List<Embedding> embeddings = provider.getEmbeddings(snapshot); assertNotNull(embeddings); assertEquals(1, embeddings.size()); Embedding embedding = embeddings.get(0); Snapshot virtualSource = embedding.getSnapshot(); String virtualSourceText = virtualSource.getText().toString(); assertDescriptionMatches(file, virtualSourceText, false, ".virtual"); }
Example #2
Source File: UnitUtilities.java From netbeans with Apache License 2.0 | 6 votes |
/**Copied from org.netbeans.api.project. * Create a scratch directory for tests. * Will be in /tmp or whatever, and will be empty. * If you just need a java.io.File use clearWorkDir + getWorkDir. */ public static FileObject makeScratchDir(NbTestCase test) throws IOException { test.clearWorkDir(); File root = test.getWorkDir(); assert root.isDirectory() && root.list().length == 0; FileObject fo = FileUtil.toFileObject(root); if (fo != null) { // Presumably using masterfs. return fo; } else { // For the benefit of those not using masterfs. LocalFileSystem lfs = new LocalFileSystem(); try { lfs.setRootDirectory(root); } catch (PropertyVetoException e) { assert false : e; } Repository.getDefault().addFileSystem(lfs); return lfs.getRoot(); } }
Example #3
Source File: MainMemoryPanel.java From BART with MIT License | 6 votes |
@Override public void actionPerformed(ActionEvent e) { File home = new File(System.getProperty("user.home")); File toLoad = new FileChooserBuilder(" 'Instance/Schema' XML File") .setTitle("Choose File") .setDefaultWorkingDirectory(home) .setApproveText("OK") .setAcceptAllFileFilterUsed(false) .addFileFilter(new FileNameExtensionFilter("XML import file", "xml","XML")) .showOpenDialog(); if(toLoad==null){ return; } FileObject fo = FileUtil.toFileObject(toLoad); if(fo.isFolder()){ DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Select 'file.xml' no folder", NotifyDescriptor.INFORMATION_MESSAGE)); return; } field.setText(fo.getPath()); }
Example #4
Source File: CIRepositories.java From nb-ci-plugin with GNU General Public License v2.0 | 6 votes |
public Set<CIFile> getFiles() { Set<CIFile> files = new HashSet<CIFile>(); StringBuilder sb = new StringBuilder(ROOT_PATH); sb.append("/").append(name); sb.append("/").append(branch.toLowerCase()); FileObject parent = FileUtil.getConfigFile(sb.toString()); for (FileObject child : parent.getChildren()) { String file = (String) child.getAttribute(ATTRIBUTE_FILE); String version = (String) child.getAttribute(ATTRIBUTE_VERSION); String fileUrl = (String) child.getAttribute(ATTRIBUTE_URL); String md5Sum = (String) child.getAttribute(ATTRIBUTE_MD5SUM); String sha1Sum = (String) child.getAttribute(ATTRIBUTE_SHA1SUM); files.add(new CIFileImpl(file, branch, version, fileUrl, md5Sum, sha1Sum)); } return files; }
Example #5
Source File: CreateArchetypeTest.java From netbeans with Apache License 2.0 | 6 votes |
private AssertContent assertFile(String msg, FileObject root, String... path) throws IOException { FileObject at = root; for (String element : path) { at.refresh(); FileObject next = at.getFileObject(element); if (next == null) { fail(msg + "\nCannot find " + Arrays.toString(path) + " found only " + at.getPath() + " and it contains:\n" + Arrays.toString(at.getChildren()) ); break; } at = next; } assertTrue("Expecting data " + at, at.isData()); return new AssertContent(at); }
Example #6
Source File: EnablePreviewAntProj.java From netbeans with Apache License 2.0 | 6 votes |
private static void storeEditableProperties(final Project prj, final String propertiesPath, final EditableProperties ep) throws IOException { try { ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() { @Override public Void run() throws IOException { FileObject propertiesFo = prj.getProjectDirectory().getFileObject(propertiesPath); if (propertiesFo != null) { OutputStream os = null; try { os = propertiesFo.getOutputStream(); ep.store(os); } finally { if (os != null) { os.close(); } } } return null; } }); } catch (MutexException ex) { } }
Example #7
Source File: NbMoveRefactoringPlugin.java From netbeans with Apache License 2.0 | 6 votes |
private void setup(Collection fileObjects, String postfix, boolean recursively) { for (Iterator i = fileObjects.iterator(); i.hasNext(); ) { FileObject fo = (FileObject) i.next(); if (RetoucheUtils.isJavaFile(fo)) { packagePostfix.put(fo, postfix.replace('/', '.')); filesToMove.add(fo); } else if (!(fo.isFolder())) { packagePostfix.put(fo, postfix.replace('/', '.')); } else if (VisibilityQuery.getDefault().isVisible(fo)) { //o instanceof DataFolder //CVS folders are ignored boolean addDot = !"".equals(postfix); Collection col = new ArrayList(); for (FileObject fo2: fo.getChildren()) { col.add(fo2); } if (recursively) setup(col, postfix +(addDot?".":"") +fo.getName(), true); // NOI18N } } }
Example #8
Source File: ObserversModel.java From netbeans with Apache License 2.0 | 6 votes |
private void update( List<ExecutableElement> methods , CompilationController controller) { DefaultMutableTreeNode root = new DefaultMutableTreeNode(); Map<Element, InjectableTreeNode<? extends Element>> methodsMap= new LinkedHashMap<Element, InjectableTreeNode<? extends Element>>(); for (ExecutableElement method : methods) { FileObject fileObject = SourceUtils.getFile(ElementHandle .create(method), controller.getClasspathInfo()); MethodTreeNode node = new MethodTreeNode(fileObject, method, (DeclaredType)controller.getElementUtilities(). enclosingTypeElement(method).asType(), false, controller); insertTreeNode( methodsMap , method , node , root , controller); } setRoot(root); }
Example #9
Source File: DBScriptPanel.java From netbeans with Apache License 2.0 | 6 votes |
public void initialize(Project project, FileObject targetFolder) { this.project = project; projectTextField.setText(ProjectUtils.getInformation(project).getDisplayName()); SourceGroup[] sourceGroups = SourceGroups.getJavaSourceGroups(project); SourceGroupUISupport.connect(locationComboBox, sourceGroups); packageComboBox.setRenderer(PackageView.listRenderer()); updatePackageComboBox(); if (targetFolder != null) { // set default source group and package cf. targetFolder SourceGroup targetSourceGroup = SourceGroups.getFolderSourceGroup(sourceGroups, targetFolder); if (targetSourceGroup != null) { locationComboBox.setSelectedItem(targetSourceGroup); String targetPackage = SourceGroups.getPackageForFolder(targetSourceGroup, targetFolder); if (targetPackage != null) { packageComboBoxEditor.setText(targetPackage); } } } createDropScriptCheckbox.setVisible(false);//isn't supported yet uniqueName(); }
Example #10
Source File: SelectFilePanel.java From netbeans with Apache License 2.0 | 6 votes |
private SelectFilePanel(List<FileObject> sourceRoots, List<FileObject> files) { assert EventQueue.isDispatchThread(); assert sourceRoots != null; assert !sourceRoots.isEmpty(); assert files.size() > 1; this.sourceRoots = sourceRoots; initComponents(); model = new DefaultListModel<>(); for (FileObject fo : files) { assert isParentOf(sourceRoots, fo) : fo + " not underneath " + sourceRoots; model.addElement(fo); } selectFileList.setCellRenderer(new FileListCellRenderer()); selectFileList.setModel(model); selectFileList.setSelectedIndex(0); selectFileList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { validateSelection(); } }); }
Example #11
Source File: SourceFoldersPanel.java From netbeans with Apache License 2.0 | 6 votes |
private List<SourceFolder> findPossibleSourceRoots() { List<SourceFolder> srcFolders = new ArrayList<SourceFolder>(); File baseFolder = model.getBaseFolder(); FileObject baseFolderFO = FileUtil.toFileObject(baseFolder); final Collection<? extends FileObject> sourceRoots = JavadocAndSourceRootDetection.findSourceRoots(baseFolderFO, null); for (FileObject possibleSrcRoot : sourceRoots) { JavaProjectGenerator.SourceFolder sf = new JavaProjectGenerator.SourceFolder(); File sourceLoc = FileUtil.normalizeFile(FileUtil.toFile(possibleSrcRoot)); sf.location = Util.relativizeLocation(model.getBaseFolder(), model.getNBProjectFolder(), sourceLoc); sf.type = ProjectModel.TYPE_JAVA; sf.style = JavaProjectNature.STYLE_PACKAGES; sf.label = getDefaultLabel(sf.location, false); sf.encoding = model.getEncoding(); srcFolders.add(sf); } return srcFolders; }
Example #12
Source File: _RetoucheUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Tries to find {@link FileObject} which contains class with given className.<br> * This method will enter javac context for referenceFileObject to find class by its className, * therefore don't call this method within other javac context. * * @param referenceFileObject helper file for entering javac context * @param className fully-qualified class name to resolve file for * @return resolved file or null if not found */ public static FileObject resolveFileObjectForClass(FileObject referenceFileObject, final String className) throws IOException { final FileObject[] result = new FileObject[1]; JavaSource javaSource = JavaSource.forFileObject(referenceFileObject); if (javaSource == null) { // Should not happen, at least some debug logging, see i.e. issue #202495. Logger.getLogger(_RetoucheUtil.class.getName()).log( Level.SEVERE, "JavaSource not created for FileObject: path={0}, valid={1}, mime-type={2}", new Object[]{ referenceFileObject.getPath(), referenceFileObject.isValid(), referenceFileObject.getMIMEType()}); } javaSource.runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement typeElement = controller.getElements().getTypeElement(className); if (typeElement != null) { result[0] = org.netbeans.api.java.source.SourceUtils.getFile(ElementHandle.create(typeElement), controller.getClasspathInfo()); } } }, true); return result[0]; }
Example #13
Source File: J2eePlatformSourceForBinaryQuery.java From netbeans with Apache License 2.0 | 6 votes |
private URL getNormalizedURL (URL url) { //URL is already nornalized, return it if (isNormalizedURL(url)) { return url; } //Todo: Should listen on the LibrariesManager and cleanup cache // in this case the search can use the cache onle and can be faster // from O(n) to O(ln(n)) URL normalizedURL = (URL) this.normalizedURLCache.get (url); if (normalizedURL == null) { FileObject fo = URLMapper.findFileObject(url); if (fo != null) { try { normalizedURL = fo.getURL(); this.normalizedURLCache.put (url, normalizedURL); } catch (FileStateInvalidException e) { Exceptions.printStackTrace(e); } } } return normalizedURL; }
Example #14
Source File: ResourceWizardPanel.java From netbeans with Apache License 2.0 | 5 votes |
/** Helper method. Gets user selected resource. */ private DataObject selectResource() { FileObject fo = null; DataObject source = null; for (DataObject dobj : sourceMap.keySet()) { fo = dobj.getPrimaryFile(); source = dobj; } // Get i18n support for this source. I18nSupport support = null; try { support = FactoryRegistry.getFactory(source.getClass()).create(source); } catch(IOException ioe) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe); } ResourceHolder rh = support != null ? support.getResourceHolder() : null; DataObject template = null; try { template = rh != null ? rh.getTemplate(rh.getResourceClasses()[0]) : null; } catch (IOException ex) { ErrorManager.getDefault().notify(ex); } return SelectorUtils.selectOrCreateBundle(fo, template, null); }
Example #15
Source File: ArchetypeWizardUtils.java From netbeans with Apache License 2.0 | 5 votes |
static Set<FileObject> openProjects(FileObject fDir, FileObject mainFO) throws IOException { List<FileObject> resultList = new ArrayList<>(); // the archetype generation didn't fail. resultList.add(fDir); processProjectFolder(fDir); collectProjects(fDir, mainFO, resultList); return new LinkedHashSet<>(resultList); }
Example #16
Source File: ProjectTemplateAttributesProviderTest.java From netbeans with Apache License 2.0 | 5 votes |
/** * Checks that the attribute providers execute in the correct order and see other provider's data. * Legacy providers should execute first. New providers should execute after that. Each new-style * provider should see all attributes defined by previous providers (legacy or new). * * @throws Exception */ public void testProjectAttributeProviders() throws Exception { Project prj = ProjectManager.getDefault().findProject(projdir); FileObject folder = projdir.getFileObject("nbproject"); FileObject template = FileUtil.toFileObject(getDataDir()).getFileObject("file.txt"); Map<String, Object> init = new HashMap(); init.put("mama", "se raduje"); FileObject result = FileBuilder.createFromTemplate(template, folder, "honza", init, FileBuilder.Mode.FORMAT); assertEquals( "Jedna, 2, Honza jde. Nese 2 pytle s brouky. Mama se raduje, ze bude pect vdolky.\n", result.asText()); }
Example #17
Source File: CopyClassesRefactoringPlugin.java From netbeans with Apache License 2.0 | 5 votes |
@Override public Problem prepare(RefactoringElementsBag refactoringElements) { for (FileObject fileobject : refactoring.getRefactoringSource().lookupAll(FileObject.class)) { refactoringElements.add(refactoring, new CopyClass(fileobject)); } return null; }
Example #18
Source File: TestUtil.java From netbeans with Apache License 2.0 | 5 votes |
public static EditableProperties loadProjectProperties( final FileObject projectDir) throws IOException { FileObject propsFO = projectDir.getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH); InputStream propsIS = propsFO.getInputStream(); EditableProperties props = new EditableProperties(true); try { props.load(propsIS); } finally { propsIS.close(); } return props; }
Example #19
Source File: ElementsTest.java From netbeans with Apache License 2.0 | 5 votes |
public void test175535() throws Exception { prepareTest(); FileObject otherFO = FileUtil.createData(sourceRoot, "test/A.java"); TestUtilities.copyStringToFile(FileUtil.toFile(otherFO), "package test;" + "public class A implements Runnable {" + " @Override" + " public void run() {}" + "}"); TestUtilities.copyStringToFile(FileUtil.toFile(testFO), "public class Test {" + "}"); SourceUtilsTestUtil.compileRecursively(sourceRoot); JavaSource javaSource = JavaSource.forFileObject(testFO); javaSource.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.RESOLVED); TypeElement typeElement = controller.getElements().getTypeElement("test.A"); assertNotNull(typeElement); Element el = typeElement.getEnclosedElements().get(1); assertNotNull(el); assertEquals("run", el.getSimpleName().toString()); TreePath mpath = controller.getTrees().getPath(el); MethodTree mtree = (MethodTree) mpath.getLeaf(); assertNotNull(mtree); List<? extends AnnotationTree> annotations = mtree.getModifiers().getAnnotations(); TypeMirror annotation = controller.getTrees().getTypeMirror(new TreePath(mpath, annotations.get(0))); assertNotNull(annotation); Element e = controller.getTrees().getElement(new TreePath(mpath, annotations.get(0))); assertNotNull(e); assertEquals(((DeclaredType)annotation).asElement(), e); } }, true); }
Example #20
Source File: RequireFileCodeCompletionTest.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected Map<String, ClassPath> createClassPathsForTest() { List<FileObject> cpRoots = new LinkedList<FileObject>(); cpRoots.add(FileUtil.toFileObject(new File(getDataDir(), "/TestProject1"))); return Collections.singletonMap( JS_SOURCE_ID, ClassPathSupport.createClassPath(cpRoots.toArray(new FileObject[cpRoots.size()])) ); }
Example #21
Source File: WLDeploymentFactoryTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testDeploymentManagerCleared() throws Exception { File dir = getWorkDir(); FileObject server = FileUtil.createFolder(new File(dir, "server")); FileObject domain = FileUtil.createFolder(new File(dir, "domain")); FileObject config = domain.createFolder("config"); config.createData("config", "xml"); String serverPath = FileUtil.toFile(server).getAbsolutePath(); String domainPath = FileUtil.toFile(domain).getAbsolutePath(); String url = WLDeploymentFactory.getUrl("localhost", 7001, serverPath, domainPath); Map<String, String> props = new HashMap<String, String>(); props.put(WLPluginProperties.SERVER_ROOT_ATTR, serverPath); props.put(WLPluginProperties.DOMAIN_ROOT_ATTR, domainPath); InstanceProperties ip = InstanceProperties.createInstancePropertiesNonPersistent( url, "test", "test", "test", props); WLDeploymentManager manager = (WLDeploymentManager) WLDeploymentFactory.getInstance().getDisconnectedDeploymentManager(url); assertEquals(ip, manager.getInstanceProperties()); InstanceProperties.removeInstance(url); WeakReference<InstanceProperties> ipRef = new WeakReference<InstanceProperties>(ip); ip = null; WeakReference<WLDeploymentManager> ref = new WeakReference<WLDeploymentManager>(manager); manager = null; assertGC("InstanceProperties leaking", ipRef); // lets indirectly touch the cache url = url + "_other"; InstanceProperties.createInstancePropertiesNonPersistent(url, "test", "test", "test", props); WLDeploymentManager managerOther = (WLDeploymentManager) WLDeploymentFactory.getInstance().getDisconnectedDeploymentManager(url); assertGC("WLDeploymentManager leaking", ref); }
Example #22
Source File: ElementNavigatorJavaSourceFactory.java From netbeans with Apache License 2.0 | 5 votes |
public FileObject getFile() { List<FileObject> result = super.getFileObjects(); if (result.size() == 1) return result.get(0); return null; }
Example #23
Source File: EcmaLevelRule.java From netbeans with Apache License 2.0 | 5 votes |
private static void reindexFile(final FileObject fo) { RP.post(new Runnable() { @Override public void run() { //refresh Action Items for this file IndexingManager.getDefault().refreshIndexAndWait(fo.getParent().toURL(), Collections.singleton(fo.toURL()), true, false); } }); }
Example #24
Source File: DefaultCssEditorModule.java From netbeans with Apache License 2.0 | 5 votes |
@Override public URL resolveLink(FileObject context, PropertyDefinition property, String link) { // return CssHelpResolver.getHelpZIPURLasString() == null ? null : // new ElementHandle.UrlHandle(CssHelpResolver.getHelpZIPURLasString() + // normalizeLink( elementHandle, link)); return null; }
Example #25
Source File: PUDataLoaderTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testPUWithoutProjectOwnerIsRecognized() throws Exception { String persistenceFile = getDataDir().getAbsolutePath() + "/persistence.xml"; FileObject puFO = FileUtil.toFileObject(new File(persistenceFile)); assertTrue("persistence unit without project owner is not recongnized." + " Project owner: " + FileOwnerQuery.getOwner(puFO), DataObject.find(puFO) instanceof PUDataObject); }
Example #26
Source File: ResourceLibraryIterator.java From netbeans with Apache License 2.0 | 5 votes |
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 #27
Source File: FileBasedFileSystem.java From netbeans with Apache License 2.0 | 5 votes |
@Override public FileObject getTempFolder() throws IOException { FileObject tmpDir = FileUtil.toFileObject(new File(System.getProperty("java.io.tmpdir"))); if (tmpDir != null && tmpDir.isFolder() && tmpDir.isValid()) { return tmpDir; } throw new IOException("Cannot find temporary folder"); // NOI18N }
Example #28
Source File: GenerateBeanInfoAction.java From netbeans with Apache License 2.0 | 5 votes |
protected boolean enable( Node[] activatedNodes ) { if (activatedNodes.length != 1) { return false; } else { FileObject fo = findFileObject(activatedNodes[0]); return fo != null && JavaSource.forFileObject(fo) != null && !fo.getName().endsWith("BeanInfo"); //NOI18N } }
Example #29
Source File: Issue239162Test.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected Map<String, ClassPath> createClassPathsForTest() { List<FileObject> cpRoots = new LinkedList<FileObject>(ClasspathProviderImplAccessor.getJsStubs()); cpRoots.add(FileUtil.toFileObject(new File(getDataDir(), "/testfiles/navigation/239162"))); return Collections.singletonMap( JS_SOURCE_ID, ClassPathSupport.createClassPath(cpRoots.toArray(new FileObject[cpRoots.size()])) ); }
Example #30
Source File: WadlSaasEx.java From netbeans with Apache License 2.0 | 5 votes |
public List<FileObject> getJaxbSourceJars() { if (jaxbSourceJars == null) { try { compileSchemas(); return Collections.unmodifiableList(jaxbSourceJars); } catch(IOException ex) { ex.printStackTrace(); } } return Collections.emptyList(); }