Java Code Examples for org.openide.filesystems.FileObject.createData()

The following are Jave code examples for showing how to use createData() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: MatchingObjectTest.java   Source Code and License Vote up 6 votes
/**
 * Create an in-memory file with simple string content.
 *
 * @param content Content of the file.
 */
public FileObject createTestFile(String content) throws IOException {

    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = root.createData(TEST_FILE_NAME);

    OutputStream os = fo.getOutputStream();
    try {
        OutputStreamWriter osw = new OutputStreamWriter(os, TEST_FILE_ENC);
        try {
            osw.write(content);
        } finally {
            osw.flush();
            osw.close();
        }
    } finally {
        os.close();
    }
    return fo;
}
 
Example 2
Project: incubator-netbeans   File: VCSInterceptorTestCase.java   Source Code and License Vote up 6 votes
private void deleteFolderTree(FileObject deleteFolder, final VCSFileProxy deleteProxy) throws IOException {
    FileObject folder1 = deleteFolder.createFolder("folder1");
    FileObject folder2 = folder1.createFolder("folder2");
    FileObject folder3 = folder2.createFolder("folder3");
    
    FileObject fo3 = folder3.createData("file");
    FileObject fo2 = folder2.createData("file");
    FileObject fo1 = folder1.createData("file");
    FileObject fo0 = deleteFolder.createData("file");
    logHandler.clear();
    
    deleteFolder.delete();
    
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(folder1)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(folder2)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(folder3)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(fo1)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(fo2)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(fo3)));
    assertTrue(!inteceptor.getBeforeDeleteFiles().contains(VCSFileProxy.createFileProxy(fo0)));
    assertFalse(deleteFolder.isValid());
}
 
Example 3
Project: incubator-netbeans   File: JavaFXProjectWizardIterator.java   Source Code and License Vote up 6 votes
/**
 * Create a new application manifest file with minimal initial contents.
 * @param dir the directory to create it in
 * @throws IOException in case of problems
 */
static void createManifest(final FileObject dir, final boolean skeepIfExists) throws IOException {
    if (!skeepIfExists || dir.getFileObject(MANIFEST_FILE) == null) {
        FileObject manifest = dir.createData(MANIFEST_FILE);
        FileLock lock = manifest.lock();
        try {
            OutputStream os = manifest.getOutputStream(lock);
            try {
                PrintWriter pw = new PrintWriter(os);
                pw.println("Manifest-Version: 1.0"); // NOI18N
                pw.println("X-COMMENT: Main-Class will be added automatically by build"); // NOI18N
                pw.println(); // safest to end in \n\n due to JRE parsing bug
                pw.flush();
            } finally {
                os.close();
            }
        } finally {
            lock.releaseLock();
        }
    }
}
 
Example 4
Project: incubator-netbeans   File: TriggeredTakeSnapshotProfilingPoint.java   Source Code and License Vote up 6 votes
private String takeSnapshotHit() {        
    LoadedSnapshot loadedSnapshot = null;
    String snapshotFilename = null;
    loadedSnapshot = takeSnapshot();

    if (loadedSnapshot != null) {
        try {
            FileObject snapshotDirectory = getSnapshotDirectory();
            FileObject profFile = snapshotDirectory.createData(ResultsManager.getDefault()
                                                                             .getDefaultSnapshotFileName(loadedSnapshot),
                                                               ResultsManager.SNAPSHOT_EXTENSION);
            ResultsManager.getDefault().saveSnapshot(loadedSnapshot, profFile); // Also updates list of snapshots in ProfilerControlPanel2
            snapshotFilename = FileUtil.toFile(profFile).toURI().toURL().toExternalForm();
        } catch (IOException e) {
            ErrorManager.getDefault().notify(ErrorManager.ERROR, e);
        }
    }

    return (snapshotFilename == null) ? Bundle.TriggeredTakeSnapshotProfilingPoint_NoDataAvailableMsg() : snapshotFilename;
}
 
Example 5
Project: incubator-netbeans   File: DefaultClassPathProviderTest.java   Source Code and License Vote up 6 votes
private synchronized FileObject getClassFile () throws IOException {
    FileObject fo = this.execTestDir.getFileObject("test/Test.class");
    if (fo == null) {
        fo = execTestDir.createFolder("test");
        fo = fo.createData("Test","class");
        FileLock lock = fo.lock();
        try {
            DataOutputStream out = new DataOutputStream (fo.getOutputStream(lock));
            try {
                out.write(CLASS_FILE_DATA);
                out.flush();
            } finally {
                out.close();
            }
        } finally {
            lock.releaseLock();
        }
    }
    return fo;
}
 
Example 6
Project: incubator-netbeans   File: DBSchemaManager.java   Source Code and License Vote up 6 votes
/**
 * Overwrites <code>dbschemaFile</code> with the contents of
 * <code>schemaElement</code>.
 */
private static void overwriteDBSchema(SchemaElement schemaElement, FileObject dbschemaFile, DBIdentifier dbschemaName) throws IOException {
    try {
        schemaElement.setName(dbschemaName);
    } catch (DBException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.initCause(e);
        throw ioe;
    }

    // cannot just overwrite the file, DBSchemaDataObject would not
    // notice the file has changed.
    FileObject parent = dbschemaFile.getParent();
    String fileName = dbschemaFile.getName();
    String fileExt = dbschemaFile.getExt();
    dbschemaFile.delete();
    FileObject newDBSchemaFile = parent.createData(fileName, fileExt);

    writeSchemaElement(schemaElement, newDBSchemaFile);
}
 
Example 7
Project: incubator-netbeans   File: MavenSourcesImplTest.java   Source Code and License Vote up 6 votes
public void testGeneratedSources() throws Exception { // #187595
    TestFileUtils.writeFile(d,
            "pom.xml",
            "<project xmlns='http://maven.apache.org/POM/4.0.0'>" +
            "<modelVersion>4.0.0</modelVersion>" +
            "<groupId>grp</groupId>" +
            "<artifactId>art</artifactId>" +
            "<packaging>jar</packaging>" +
            "<version>0</version>" +
            "</project>");
    FileObject src = FileUtil.createFolder(d, "src/main/java");
    FileObject gsrc = FileUtil.createFolder(d, "target/generated-sources/xjc");
    gsrc.createData("Whatever.class");
    FileObject tsrc = FileUtil.createFolder(d, "src/test/java");
    FileObject gtsrc = FileUtil.createFolder(d, "target/generated-test-sources/jaxb");
    gtsrc.createData("Whatever.class");
    SourceGroup[] grps = ProjectUtils.getSources(ProjectManager.getDefault().findProject(d)).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    assertEquals(2, grps.length);
    assertEquals(src, grps[0].getRootFolder());
    assertEquals(tsrc, grps[1].getRootFolder());
    grps = ProjectUtils.getSources(ProjectManager.getDefault().findProject(d)).getSourceGroups(MavenSourcesImpl.TYPE_GEN_SOURCES);
    assertEquals(2, grps.length);
    assertEquals(gsrc, grps[0].getRootFolder());
    assertEquals(gtsrc, grps[1].getRootFolder());
}
 
Example 8
Project: incubator-netbeans   File: TestBase.java   Source Code and License Vote up 5 votes
protected Document[] createDocuments(String... fileName) {
    try {
        List<Document> docs = new ArrayList<>();
        FileSystem memFS = FileUtil.createMemoryFileSystem();
        for (String fName : fileName) {

            //we may also create folders
            StringTokenizer items = new StringTokenizer(fName, "/");
            FileObject fo = memFS.getRoot();
            while(items.hasMoreTokens()) {
                String item = items.nextToken();
                if(items.hasMoreTokens()) {
                    //folder
                    fo = fo.createFolder(item);
                } else {
                    //last, create file
                    fo = fo.createData(item);
                }
                assertNotNull(fo);
            }
            
            DataObject dobj = DataObject.find(fo);
            assertNotNull(dobj);

            EditorCookie cookie = dobj.getCookie(EditorCookie.class);
            assertNotNull(cookie);

            Document document = (Document) cookie.openDocument();
            assertEquals(0, document.getLength());

            docs.add(document);

        }
        return docs.toArray(new Document[]{});
    } catch (Exception ex) {
        throw new IllegalStateException("Error setting up tests", ex);
    }
}
 
Example 9
Project: incubator-netbeans   File: ProjectUtilitiesTest.java   Source Code and License Vote up 5 votes
public void testCanUseFileName() throws Exception {
    FileObject d = FileUtil.toFileObject(getWorkDir());
    FileObject p1 = d.getFileObject("project1");
    assertNotNull(p1);
    assertNull("normal file addition", ProjectUtilities.canUseFileName(p1, null, "foo", "java", false, false));
    assertNull("normal file addition with no extension is OK", ProjectUtilities.canUseFileName(p1, null, "foo", null, false, false));
    assertNull("normal file addition in an existing subdir", ProjectUtilities.canUseFileName(d, "project1", "foo", "java", false, false));
    assertNull("normal file addition in a new subdir", ProjectUtilities.canUseFileName(d, "dir", "foo", "java", false, false));
    //assertNotNull("no target name", ProjectUtilities.canUseFileName(d, "dir", null, "java"));
    assertNotNull("no target folder", ProjectUtilities.canUseFileName(null, "dir", "foo", "java", false, false));
    assertNotNull("file already exists", ProjectUtilities.canUseFileName(p1, null, "f1_1", "java", false, false));
    assertNotNull("file already exists in subdir", ProjectUtilities.canUseFileName(d, "project1", "f1_1", "java", false, false));
    assertNull("similar file already exists in subdir", ProjectUtilities.canUseFileName(d, "project1", "f1_1", "properties", false, false));
    assertNull("similar file already exists in subdir", ProjectUtilities.canUseFileName(d, "project1", "f1_1", null, false, false));
    d = new XMLFileSystem().getRoot();
    assertNotNull("FS is r/o", ProjectUtilities.canUseFileName(d, null, "foo", "java", false, false));
    // #59876: deal with non-disk-based filesystems sensibly
    d = FileUtil.createMemoryFileSystem().getRoot();
    d.createData("bar.java");
    FileUtil.createData(d, "sub/dir/foo.java");
    assertNull("can create file in non-disk FS", ProjectUtilities.canUseFileName(d, null, "foo", "java", false, false));
    assertNotNull("file already exists", ProjectUtilities.canUseFileName(d, null, "bar", "java", false, false));
    assertNotNull("file already exists in subsubdir", ProjectUtilities.canUseFileName(d, "sub/dir", "foo", "java", false, false));
    assertNull("can otherwise create file in subsubdir", ProjectUtilities.canUseFileName(d, "sub/dir", "bar", "java", false, false));
    //#66792: allow to create whole directory tree at once using Folder Template:
    assertNull("can create directory subtree", ProjectUtilities.canUseFileName(d, null, "a/b/c", null, true, false));
    //#59654: do not allow slash and backslash for common templates:
    assertNotNull("cannot create file with slashes", ProjectUtilities.canUseFileName(d, null, "a/b/c", "txt", false, false));
    assertNotNull("cannot create file with backslashes", ProjectUtilities.canUseFileName(d, null, "a\\b\\c", "txt", false, false));
    // Check freeFileExtension mode:
    assertNull(ProjectUtilities.canUseFileName(d, null, "foo", "java", false, true));
    assertNotNull(ProjectUtilities.canUseFileName(d, null, "bar", "java", false, true));
    assertNotNull(ProjectUtilities.canUseFileName(d, null, "bar.java", "java", false, true));
    assertNull(ProjectUtilities.canUseFileName(d, null, "bar.java", "java", false, false));
    String err = ProjectUtilities.canUseFileName(d, null, "<a href='whatever'>HTML\njunk!</a>", "html", false, false);
    assertNotNull(err);
    assertTrue(err, err.contains("&lt;a href='whatever'>HTML junk!&lt;…"));
}
 
Example 10
Project: incubator-netbeans   File: PDFOpenSupport.java   Source Code and License Vote up 5 votes
/**
 * Store custom command to System Filesystem.
 *
 * @param customCommand Command to store.
 */
private void storeCustomCommand(String customCommand) throws IOException {
    FileObject root = FileUtil.getConfigRoot();
    FileObject folder = root.getFileObject(DATA_FOLDER);
    if (folder == null) {
        folder = root.createFolder(DATA_FOLDER);
    }
    FileObject data = folder.getFileObject(DATA_FILE);
    if (data == null) {
        data = folder.createData(DATA_FILE);
    }
    data.setAttribute(CMD_ATTR, customCommand);
}
 
Example 11
Project: incubator-netbeans   File: Util.java   Source Code and License Vote up 5 votes
public static FileObject getProjectCatalogFileObject(Project prj, boolean create) throws IOException {
    if(prj == null)
        return null;
    
    FileObject result = null;
    FileObject myProjectRootFileObject = prj.getProjectDirectory();
    
    //see if this prj has XMLCatalogProvider. If yes use it.
    XMLCatalogProvider catProv =  prj.getLookup().lookup(org.netbeans.modules.xml.retriever.XMLCatalogProvider.class);
    if(catProv != null){
        URI caturi = catProv.getProjectWideCatalog();
        if(caturi != null){
            caturi = FileUtil.toFile(myProjectRootFileObject).toURI().resolve(caturi);
            File catFile = new File(caturi);
            if(!catFile.isFile()){
                catFile.createNewFile();
            }
            result = FileUtil.toFileObject(FileUtil.normalizeFile(catFile));
        }
    }
    
    if(result == null){
        String fileName = CatalogWriteModel.PUBLIC_CATALOG_FILE_NAME+CatalogWriteModel.CATALOG_FILE_EXTENSION;
        result = myProjectRootFileObject.getFileObject(fileName);
        if(result == null && create){
            result = myProjectRootFileObject.createData(fileName);
        }
    }
    return result;
}
 
Example 12
Project: Pogamut3   File: DefaultServersManager.java   Source Code and License Vote up 5 votes
protected FileObject getServerListFile() throws IOException {
    FileObject root = Repository.getDefault().getDefaultFileSystem().getRoot();
    FileObject folder = root.getFileObject(serverType);
    if (folder == null) {
        folder = root.createFolder(serverType);
    }

    FileObject serversFile = folder.getFileObject(serversListFileName);
    if (serversFile == null) {
        serversFile = folder.createData(serversListFileName);
    }

    return serversFile;
}
 
Example 13
Project: incubator-netbeans   File: RemoveWritablesTest.java   Source Code and License Vote up 5 votes
public void testAddedFile() throws Exception {
    FileObject folder = FileUtil.getConfigFile( "foo" );
    FileObject newFile = folder.createData( "newFile", "ext" );
    
    File writableFile = new File( new File( configDir, "foo"), "newFile.ext" );
    assertTrue( writableFile.exists() );

    assertTrue(newFile.canRevert());
    newFile.revert();
    
    assertFalse( "local file removed", writableFile.exists() );
    assertNull( "FileObject does not exist", FileUtil.getConfigFile( "foo/newFile.ext" ) );
}
 
Example 14
Project: incubator-netbeans   File: AbstractHgTestCase.java   Source Code and License Vote up 4 votes
protected File createFile(String name) throws IOException {
    FileObject wd = FileUtil.toFileObject(getWorkTreeDir());
    FileObject fo = wd.createData(name);
    return FileUtil.toFile(fo);
}
 
Example 15
Project: incubator-netbeans   File: ClassPathTest.java   Source Code and License Vote up 4 votes
/**
 * Tests ClassPath.findAllResources(), ClassPath.findResoruce(), 
 * ClassPath.contains (), ClassPath.findOwnerRoot(),
 * ClassPath.isResourceVisible ()
 */
public void testGetResource () throws Exception {
    File root_1 = new File (getBaseDir(),"root_1");
    root_1.mkdir();
    File root_2 = new File (getBaseDir(),"root_2");
    root_2.mkdir();
    FileObject[] roots = new FileObject [] {
        FileUtil.toFileObject(root_1),
        FileUtil.toFileObject(root_2),
    };
    
    FileObject tmp = roots[0].createFolder("org");
    tmp = tmp.createFolder("me");
    FileObject testFo_1 = tmp.createData("Foo","txt");
    tmp = roots[1].createFolder("org");
    tmp = tmp.createFolder("me");
    FileObject testFo_2 = tmp.createData("Foo","txt");        
    ClassPath cp = ClassPathSupport.createClassPath(roots);        
    
    //findResource
    assertTrue(cp.findResource ("org/me/Foo.txt")==testFo_1);
    assertTrue (cp.findResource("org/me/None.txt")==null);
    
    //findAllResources
    List res = cp.findAllResources ("org/me/Foo.txt");
    assertTrue (res.size() == 2);
    assertTrue (res.contains(testFo_1));
    assertTrue (res.contains(testFo_2));
    
    //contains
    assertTrue (cp.contains (testFo_1));
    assertTrue (cp.contains (testFo_2));
    assertFalse (cp.contains (roots[0].getParent()));
    
    //findOwnerRoot
    assertTrue (cp.findOwnerRoot(testFo_1)==roots[0]);
    assertTrue (cp.findOwnerRoot(testFo_2)==roots[1]);

    /*
    //isResourceVisible
    assertTrue (cp.isResourceVisible(testFo_1));
    assertFalse (cp.isResourceVisible(testFo_2));
     */
    
    cp = null;
    roots[0].delete();
    roots[1].delete();
}
 
Example 16
Project: incubator-netbeans   File: ProjectsRootNodeFindTest.java   Source Code and License Vote up 4 votes
public void testFindNode() throws Exception{
    
     //compute project root node children in sync mode
    System.setProperty("test.projectnode.sync", "true");
    
    //prepearing project
    MockLookup.setInstances(new TestSupport.TestProjectFactory());
    CountDownLatch down = new CountDownLatch(1);
    clearWorkDir();
    FileObject workDir = FileUtil.toFileObject(getWorkDir());
    FileObject foMain = TestSupport.createTestProject(workDir, "prj_1");
    FileObject foChild = TestSupport.createTestProject(foMain, "prj_2");
    FileObject foData = foChild.createData("data", "txt");

    List<URL> list = new ArrayList<URL>();
    list.add(URLMapper.findURL(foMain, URLMapper.EXTERNAL));
    list.add(URLMapper.findURL(foChild, URLMapper.EXTERNAL));
    List<ExtIcon> icons = new ArrayList<ExtIcon>();
    icons.add(new ExtIcon());
    icons.add(new ExtIcon());
    List<String> names = new ArrayList<String>();
    names.add(list.get(0).toExternalForm());
    names.add(list.get(1).toExternalForm());
    TestSupport.TestProject prjMain = (TestSupport.TestProject) ProjectManager.getDefault().findProject(foMain);
    TestSupport.TestProject prjChild = (TestSupport.TestProject) ProjectManager.getDefault().findProject(foChild);
    prjMain.setLookup(Lookups.singleton(new TestProjectOpenedHookImpl(down)));
    prjChild.setLookup(Lookups.singleton(new TestProjectOpenedHookImpl(down)));
    
    OpenProjectListSettings.getInstance().setOpenProjectsURLs(list);
    OpenProjectListSettings.getInstance().setOpenProjectsDisplayNames(names);
    OpenProjectListSettings.getInstance().setOpenProjectsIcons(icons);

    Node logicalView = new ProjectsRootNode(ProjectsRootNode.LOGICAL_VIEW);
    assertEquals("2 children", 2, logicalView.getChildren().getNodesCount());

    // let project open code run
    down.countDown();
    TestProjectOpenedHookImpl.toOpen.await();
    
    OpenProjectList.waitProjectsFullyOpen();

    ProjectsRootNode phView = new ProjectsRootNode(ProjectsRootNode.PHYSICAL_VIEW);
    Node nodeMain = phView.findNode(foMain);
    assertNotNull(nodeMain);
    Node nodeChild = phView.findNode(foChild);
    assertNotNull(nodeChild);
    assertNotSame(nodeChild.getParentNode(), nodeMain);
    Node nodeData = phView.findNode(foData);
    assertNotNull(nodeData);
    assertEquals(nodeData.getParentNode(), nodeChild);
    assertNotSame(nodeData.getParentNode().getParentNode(), nodeMain);
}
 
Example 17
Project: incubator-netbeans   File: RepositoryUpdater2Test.java   Source Code and License Vote up 4 votes
public void testMarkingIndexesDirty() throws Exception {
    FileUtil.setMIMEType("txt", "text/plain");
    final FileObject root = workDir.createFolder("root");
    final FileObject file1 = root.createData("file1.txt");

    final RepositoryUpdaterTest.MutableClassPathImplementation mcpi = new RepositoryUpdaterTest.MutableClassPathImplementation();
    mcpi.addResource(root);
    ClassPath cp = ClassPathFactory.createClassPath(mcpi);

    Map<FileObject, Map<String, ClassPath>> allDeps = new HashMap<FileObject, Map<String, ClassPath>>();
    allDeps.put(root, Collections.singletonMap(testRootsWorkCancelling_PathRecognizer.SOURCEPATH, cp));
    
    dependencies.clear();
    dependencies.putAll(allDeps);

    final TestCustomIndexer indexer = new TestCustomIndexer();
    MockMimeLookup.setInstances(MimePath.parse("text/plain"), new FixedCustomIndexerFactory(indexer), new FixedParserFactory(new EmptyParser()));
    RepositoryUpdaterTest.setMimeTypes("text/plain");

    assertEquals("No roots should be indexed yet", 0, indexer.indexed.size());

    ruSync.reset(RepositoryUpdaterTest.TestHandler.Type.BATCH);
    globalPathRegistry_register(testRootsWorkCancelling_PathRecognizer.SOURCEPATH, new ClassPath[] { cp });
    ruSync.await();

    assertEquals("Wrong number of roots", 1, indexer.indexed.size());

    // the indexer does not store any data and so physically there is no lucene index on the disk
    // therefore we have to forcibly create one
    Context ctx = indexer.indexed.get(0).first();
    DocumentIndex ii = SPIAccessor.getInstance().getIndexFactory(ctx).createIndex(ctx);
    ii.markKeyDirty("file1.txt"); // marks index as dirty and adds file1.txt among stale files
    assertEquals("Wrong number of stale files", 1, ii.getDirtyKeys().size());
    assertEquals("file1.txt should be a stale file", "file1.txt", ii.getDirtyKeys().iterator().next());

    indexer.indexed.clear();
    ruSync.reset(RepositoryUpdaterTest.TestHandler.Type.FILELIST, 1);
    RepositoryUpdater.getDefault().addIndexingJob(root.getURL(), Collections.singleton(file1.getURL()), false, false, true, true, true, null);
    ruSync.await();

    assertEquals("Wrong number of roots", 1, indexer.indexed.size());
    assertEquals("Expecting root", root.getURL(), indexer.indexed.get(0).first().getRootURI());
    assertEquals("Wrong number of files under root", 1, indexer.indexed.get(0).second().size());
    assertEquals("Wrong file indexed", file1.getURL(), indexer.indexed.get(0).second().get(0).getURL());
    assertEquals("Expecting no stale files", 0, ii.getDirtyKeys().size());
}
 
Example 18
Project: incubator-netbeans   File: TimesCollectorPeerTest.java   Source Code and License Vote up 4 votes
public void testHandleDelete() throws Exception {
    FileObject dir  = makeScratchDir(this);
    FileObject file = dir.createData("test.txt");
    
    TimesCollectorPeer.getDefault().reportTime(file, "test", "test", 0);
    
    file.delete();
    
    assertTrue(TimesCollectorPeer.getDefault().getFiles().isEmpty());
    
    JFrame f = new JFrame();
    
    f.add(new TimeComponentPanel());
    
    f.setVisible(true);
    
    file = dir.createData("test.txt");
    
    TimesCollectorPeer.getDefault().reportTime(file, "test", "test", 0);
    
    file.delete();
}
 
Example 19
Project: incubator-netbeans   File: AbstractHgTestCase.java   Source Code and License Vote up 4 votes
protected File createFile(File parent, String name) throws IOException {
    FileObject parentFO = FileUtil.toFileObject(parent);
    FileObject fo = parentFO.createData(name);
    return FileUtil.toFile(fo);
}
 
Example 20
Project: incubator-netbeans   File: DataShadowTranslateTest.java   Source Code and License Vote up 2 votes
/**
 * Checks that DataShadows to regular (non-SFS) files are not translated
 * even if a translation is defined for their path
 * 
 * @throws Exception 
 */
public void testNonSFSUriNotAffected() throws Exception {
    File wd = getWorkDir();
    
    clearWorkDir();
    
    FileObject origDir = FileUtil.toFileObject(wd);
    
    FileObject dirWithSpace = origDir.createFolder("Space Dir");
    FileObject newFile = dirWithSpace.createData("testFile.txt");
    

    File subDir = new File(wd, "translate");
    
    subDir.mkdirs();
    
    File metaTranslate = new File(subDir, "META-INF/netbeans");
    metaTranslate.mkdirs();
    
    String workPath = newFile.toURI().getRawPath();
    FileWriter wr = new FileWriter(new File(metaTranslate, "translate.names"));
    BufferedWriter bw = new BufferedWriter(wr);
    
    bw.write(workPath.substring(1) + "/testFile.txt=" + workPath.substring(1) + "/moved/testFile.txt");
    bw.close();
    
    
    FileObject fo = FileUtil.toFileObject(wd);
    
    ClassLoader orig = Lookup.getDefault().lookup(ClassLoader.class);
    
    ClassLoader my = new URLClassLoader(new URL[] {
        subDir.toURL()
    }, orig);
    
    MockLookup.setInstances(my);
    
    
    FileObject cfgRoot = FileUtil.getConfigRoot();
    
    
    OutputStream ostm = cfgRoot.createAndOpen("nonSFSFile.shadow");
    
    bw = new BufferedWriter(new OutputStreamWriter(ostm));
    
    bw.write(newFile.toURI().toString());
    bw.newLine();
    bw.newLine();
    
    newFile.delete();
    
    bw.close();
    
    FileObject fob = cfgRoot.getFileObject("nonSFSFile.shadow");
    DataObject dd = DataObject.find(fob);
    
    assertFalse("Shadow must be still broken", dd instanceof DataShadow);
}