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

The following are Jave code examples for showing how to use lock() 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.
+ Save this method
Example 1
Project: incubator-netbeans   File: ReferencesCountTest.java   View Source Code Vote up 6 votes
private FileObject createSource(
        @NonNull final FileObject root,
        @NonNull final String fqn,
        @NonNull final String content) throws IOException {
    final FileObject file = FileUtil.createData(root, fqn.replace('.', '/')+"."+JavaDataLoader.JAVA_EXTENSION);   //NOI18N
    final FileLock lck = file.lock();
    try {
        final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck),"UTF-8"));    //NOI18N
        try {
            out.print(content);
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    return file;
}
 
Example 2
Project: incubator-netbeans   File: J2SEProjectFactory.java   View Source Code 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
 */
private static void createManifest(final FileObject dir, final String manifestFile) throws IOException {

    FileObject manifest = dir.createData(manifestFile);
    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 3
Project: Pogamut3   File: DefaultServersManager.java   View Source Code Vote up 6 votes
@Override
public void serialize() {
    try {
        FileObject writeTo = getServerListFile();
        FileLock lock = writeTo.lock();
        try {
            ObjectOutputStream str = new ObjectOutputStream(writeTo.getOutputStream(lock));
            try {
                str.writeObject(servers.getList());
            } finally {
                str.close();
            }
        } finally {
            lock.releaseLock();
        }

    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
}
 
Example 4
Project: incubator-netbeans   File: CopyResourcesOnSave.java   View Source Code Vote up 6 votes
private static void copySrcToDest( FileObject srcFile, FileObject destFile) throws IOException {
    if (destFile != null && !srcFile.isFolder()) {
        InputStream is = null;
        OutputStream os = null;
        FileLock fl = null;
        try {
            is = srcFile.getInputStream();
            fl = destFile.lock();
            os = destFile.getOutputStream(fl);
            FileUtil.copy(is, os);
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (fl != null) {
                fl.releaseLock();
            }
        }
    }
}
 
Example 5
Project: incubator-netbeans   File: SourceTest.java   View Source Code Vote up 6 votes
public void testMimeTypeChange() throws IOException {
    clearWorkDir();
    final FileObject file = createFileObject("empty.foo", "", "\n");
    final Source source = Source.create(file);
    assertNotNull("No Source for " + file, source);
    assertSame("Wrong FileObject", file, source.getFileObject());
    assertSame("Inconsistent Source.create(FileObject)", source, Source.create(file));
    final FileLock lock = file.lock();
    try {
        file.rename(lock, "empty", "txt");  //NOI18N
    } finally {
        lock.releaseLock();
    }
    final Source source2 = Source.create(file);
    assertNotNull("No Source for " + file, source2);
    assertSame("Wrong FileObject", file, source2.getFileObject());
    assertNotSame("Inconsistent Source.create(FileObject)", source, source2);
}
 
Example 6
Project: incubator-netbeans   File: ProvidedExtensionsTest.java   View Source Code Vote up 6 votes
public void testImplsCaseOnlyRename() throws IOException {
    FileObject fo = FileUtil.toFileObject(getWorkDir());
    assertNotNull(fo);
    assertNotNull(iListener);
    FileObject toRename = fo.createData("aa");
    assertNotNull(toRename);
    
    iListener.clear();
    FileLock lock = toRename.lock();
    iListener.setLock(lock);
    try {
        assertEquals(0,iListener.implsRenameCalls);
        assertEquals(0,iListener.renameImplCalls);
        iListener.setImplsRenameRetVal(true);
        assertTrue(toRename.isValid());
        assertNull(toRename.getParent().getFileObject(toRename.getExt(), toRename.getName()));
        toRename.rename(lock,toRename.getName().toUpperCase(), toRename.getExt().toUpperCase());
        assertEquals(1,iListener.implsRenameCalls);
        assertEquals(1,iListener.renameImplCalls);
    } finally {
        if (lock != null) {
            iListener.setLock(null);
            lock.releaseLock();
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: SuspiciousNamesCombinationTest.java   View Source Code Vote up 5 votes
private void writeIntoFile(FileObject file, String what) throws Exception {
    FileLock lock = file.lock();
    OutputStream out = file.getOutputStream(lock);
    
    try {
        out.write(what.getBytes());
    } finally {
        out.close();
        lock.releaseLock();
    }
}
 
Example 8
Project: incubator-netbeans   File: FileEntityResolverDeadlock54971Test.java   View Source Code Vote up 5 votes
static FileObject createSettings (FileObject root, String name) throws IOException {
    FileObject set = FileUtil.createData (root, name);

    FileLock lock = set.lock ();
    java.io.PrintStream os = new java.io.PrintStream (set.getOutputStream (lock));
    
    os.println ("<?xml version=\"1.0\"?>");
    os.println ("<!DOCTYPE settings PUBLIC \"-//NetBeans//Test//EN\" \"http://www.netbeans.org/dtds/sessionsettings-1_0.dtd\">");
    os.println ("<lkp version=\"1.0\">");
    os.println ("</lkp>");
    
    os.close ();
    lock.releaseLock();
    return set;
}
 
Example 9
Project: incubator-netbeans   File: SourcePrefetcherTest.java   View Source Code Vote up 5 votes
public void testDeadlock208663() throws Exception {
    CompileTuple ct = files.iterator().next();
    final FileObject fo = URLMapper.findFileObject(ct.indexable.getURL());
    final FileLock lck = fo.lock();
    try {
        final OutputStream out = new BufferedOutputStream(fo.getOutputStream(lck));
        try {
            for (int i = 0; i<101; i++) {
                out.write('a');
            }
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    
    JavaIndexerWorker.TEST_DO_PREFETCH = true;
    JavaIndexerWorker.BUFFER_SIZE = 100;
    final LogHandler handler = new LogHandler();
    handler.expect("Using concurrent iterator, {0} workers");    //NOI18N
    final Logger log = Logger.getLogger(JavaIndexerWorker.class.getName());
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SourcePrefetcher pf = SourcePrefetcher.create(files, SuspendSupport.NOP);
        assertTrue(handler.isFound());
        final Deque<CompileTuple> got = new ArrayDeque<CompileTuple>(FILE_COUNT);
        while (pf.hasNext()) {
            ct = pf.next();
            assertNotNull(getCache(ct.jfo));
            got.offer(ct);
            pf.remove();
            assertNull(getCache(ct.jfo));
        }
        assertCollectionsEqual(files,got);
    } finally {
        log.removeHandler(handler);
    }
}
 
Example 10
Project: incubator-netbeans   File: APIIsSelfContainedTest.java   View Source Code Vote up 5 votes
private void writeIntoFile(FileObject file, String what) throws Exception {
    FileLock lock = file.lock();
    OutputStream out = file.getOutputStream(lock);
    
    try {
        out.write(what.getBytes());
    } finally {
        out.close();
        lock.releaseLock();
    }
}
 
Example 11
Project: incubator-netbeans   File: LanguagesDataObject.java   View Source Code Vote up 5 votes
static void createFileWithSubstitutions(
        final FileObject sourceFO,
        final FileObject targetFO,
        final Map<String,String> tokens) throws IOException {
    FileLock lock = targetFO.lock();
    try {
        copyAndSubstituteTokens(sourceFO.getURL(), lock, targetFO, tokens);
    } finally {
        lock.releaseLock();
    }
}
 
Example 12
Project: incubator-netbeans   File: ModeParser.java   View Source Code Vote up 5 votes
/** Writes data from asociated mode to the xml representation */
void writeData (ModeConfig mc, InternalConfig ic) throws IOException {
    final StringBuffer buff = fillBuffer(mc, ic);
    synchronized (RW_LOCK) {
        FileObject cfgFOOutput = getConfigFOOutput();
        FileLock lock = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        try {
            lock = cfgFOOutput.lock();
            os = cfgFOOutput.getOutputStream(lock);
            osw = new OutputStreamWriter(os, "UTF-8"); // NOI18N
            osw.write(buff.toString());
            /*log("-- DUMP Mode:");
            log(buff.toString());*/
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (IOException exc) {
                Logger.getLogger(ModeParser.class.getName()).log(Level.INFO, null, exc);
            }
            if (lock != null) {
                lock.releaseLock();
            }
        }
    }
}
 
Example 13
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 5 votes
public void testCannotLockReadOnlyFile() throws Exception {
    clearWorkDir();
    final File wDir = getWorkDir();
    final File data = new File(wDir,"c.data");
    data.createNewFile();
    data.setReadOnly();
    FileObject fd = FileUtil.toFileObject(data);
    try {
        FileLock lock = fd.lock();
        fail("Shall not be possible to create a lock: " + lock);
    } catch (IOException ex) {
    }
}
 
Example 14
Project: incubator-netbeans   File: ToolbarPoolTest.java   View Source Code Vote up 5 votes
private static Object writeInstance (final FileObject folder, final String name, final Object inst) throws IOException {
    class W implements FileSystem.AtomicAction {
        public Object create;
        
        public void run () throws IOException {
            FileObject fo = FileUtil.createData (folder, name);
            FileLock lock = fo.lock ();
            ObjectOutputStream oos = new ObjectOutputStream (fo.getOutputStream (lock));
            oos.writeObject (inst);
            oos.close ();
            lock.releaseLock ();
            
            DataObject obj = DataObject.find (fo);
            InstanceCookie ic = obj.getCookie(InstanceCookie.class);
            
            assertNotNull ("Cookie created", ic);
            try {
                create = ic.instanceCreate ();
                assertEquals ("The same instance class", inst.getClass(), create.getClass ());
            } catch (ClassNotFoundException ex) {
                fail (ex.getMessage ());
            }
        }
    }
    W w = new W ();
    folder.getFileSystem ().runAtomicAction (w);
    return w.create;
}
 
Example 15
Project: incubator-netbeans   File: InterceptorTest.java   View Source Code Vote up 5 votes
private void deleteFO (File toDelete) throws DataObjectNotFoundException, IOException {
    FileObject fo = FileUtil.toFileObject(toDelete);
    assertNotNull(fo);
    FileLock lock = fo.lock();
    try {
        fo.delete(lock);
    } finally {
        lock.releaseLock();
    }
}
 
Example 16
Project: incubator-netbeans   File: FileStateManager.java   View Source Code Vote up 5 votes
private void deleteImpl (FileObject mfo, FileSystem fsLayer) throws IOException {
    FileObject fo = fsLayer.findResource (mfo.getPath());
    if (fo != null) {
        FileLock lock = null;
        try {
            lock = fo.lock ();
            fo.delete (lock);
        } finally {
            if (lock != null)
                lock.releaseLock ();
        }
    }
}
 
Example 17
Project: incubator-netbeans   File: IndentFileEntry.java   View Source Code Vote up 4 votes
/** Creates a new Java source from the template. Unlike the standard FileEntry.Format,
       this indents the resulting text using an indentation engine.
   */
   @Override
   public FileObject createFromTemplate (FileObject f, String name) throws IOException {
       String ext = getFile ().getExt ();

       if (name == null) {
           name = FileUtil.findFreeFileName(f, getFile ().getName (), ext);
       }
       FileObject fo = f.createData (name, ext);
       java.text.Format frm = createFormat (f, name, ext);
       InputStream is=getFile ().getInputStream ();
       Charset encoding = FileEncodingQuery.getEncoding(getFile());
       Reader reader = new InputStreamReader(is,encoding);
       BufferedReader r = new BufferedReader (reader);
       StyledDocument doc = createDocument(createEditorKit(fo.getMIMEType()));
       IndentEngine eng = (IndentEngine)indentEngine.get();
       if (eng == null) eng = IndentEngine.find(doc);
       Object attr = getFile().getAttribute(EA_PREFORMATTED);
       boolean preformatted = false;
       
       if (attr != null && attr instanceof Boolean) {
           preformatted = ((Boolean)attr).booleanValue();
       }

       try {
           FileLock lock = fo.lock ();
           try {
               encoding = FileEncodingQuery.getEncoding(fo);
               OutputStream os=fo.getOutputStream(lock);
               OutputStreamWriter w = new OutputStreamWriter(os, encoding);
               try {
                   String line = null;
                   String current;
                   int offset = 0;

                   while ((current = r.readLine ()) != null) {
                       if (line != null) {
                           // newline between lines
                           doc.insertString(offset, NEWLINE, null);
                           offset++;
                       }
                       line = frm.format (current);

                       // partial indentation used only for pre-formatted sources
                       // see #19178 etc.
                       if (!preformatted || !line.equals(current)) {
                           line = fixupGuardedBlocks(safeIndent(eng, line, doc, offset));
                       }
                       doc.insertString(offset, line, null);
                           offset += line.length();
                   }
                   doc.insertString(doc.getLength(), NEWLINE, null);
                   w.write(doc.getText(0, doc.getLength()));
               } catch (javax.swing.text.BadLocationException e) {
               } finally {
                   w.close ();
               }
           } finally {
               lock.releaseLock ();
           }
       } finally {
           r.close ();
       }
       // copy attributes
       FileUtil.copyAttributes (getFile (), fo);
// hack to overcome package-private modifier in setTemplate(fo, boolean)
       fo.setAttribute(DataObject.PROP_TEMPLATE, null);
       return fo;
   }
 
Example 18
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 4 votes
public void testMoveKeepsLastModifiedDate() throws Exception {
    FileObjectFactory fs = FileObjectFactory.getInstance(getWorkDir());
    assertNotNull(fs);
    FileObject root1 = fs.getValidFileObject(getWorkDir(),
            FileObjectFactory.Caller.Others);

    FileObject where = root1.createFolder("else").createFolder("sub").createFolder(
            "subsub");
    FileObject fo = root1.createFolder("something");
    FileObject nestedTxt = fo.createData("nested.txt");
    FileObject simpleTxt = root1.createData("simple.txt");
    File nestedTxtFile = FileUtil.toFile(nestedTxt);
    File simpleTxtFile = FileUtil.toFile(simpleTxt);

    long origLastModifiedNested = nestedTxtFile.lastModified();
    long origLastModifiedSimple = simpleTxtFile.lastModified();

    Thread.sleep(1100);

    FileLock folderLock = fo.lock();
    try {
        fo.move(folderLock, where, fo.getNameExt(), null);
    } finally {
        folderLock.releaseLock();
    }
    FileLock simpleLock = simpleTxt.lock();
    try {
        simpleTxt.move(simpleLock, where, simpleTxt.getNameExt(), null);
    } finally {
        simpleLock.releaseLock();
    }

    FileObject nestedTarget = root1.getFileObject(
            "else/sub/subsub/something/nested.txt");
    FileObject simpleTarget = root1.getFileObject(
            "else/sub/subsub/simple.txt");

    assertEquals("LastModified date should be kept", origLastModifiedNested,
            FileUtil.toFile(nestedTarget).lastModified());
    assertEquals("LastModified date should be kept", origLastModifiedSimple,
            FileUtil.toFile(simpleTarget).lastModified());
}
 
Example 19
Project: incubator-netbeans   File: ShortcutWizardTestBase.java   View Source Code Vote up 4 votes
@Override
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    scratchF = getWorkDir();
    mkdir("system/Menu/&File");
    mkdir("system/Menu/&Edit");
    mkdir("system/Menu/&Build");
    mkdir("system/Menu/&Build/Other");
    mkdir("system/Menu/Help");
    mkdir("system/Toolbars/Build");
    mkdir("system/Toolbars/Help");
    mkdir("system/Shortcuts");
    System.setProperty("SYSTEMDIR", new File(scratchF, "system").getAbsolutePath());
    FileObject scratch = FileUtil.toFileObject(scratchF);
    assertNotNull("have a scratch dir", scratch);
    MockServices.setServices(Repo.class);
    FileObject menuFolder = FileUtil.getConfigFile("Menu");
    assertNotNull("have Menu", menuFolder);
    menuFolder.getFileObject("&File").setAttribute("position", 100);
    menuFolder.getFileObject("&Edit").setAttribute("position", 200);
    menuFolder.getFileObject("&Build").setAttribute("position", 300);
    menuFolder.getFileObject("Help").setAttribute("position", 400);
    FileObject toolbarsFolder = FileUtil.getConfigFile("Toolbars");
    assertNotNull("have Toolbars", toolbarsFolder);
    toolbarsFolder.getFileObject("Build").setAttribute("position", 100);
    toolbarsFolder.getFileObject("Help").setAttribute("position", 200);
    assertNotNull("have Shortcuts", FileUtil.getConfigFile("Shortcuts"));
    FileObject buildXml = scratch.createData("build.xml");
    FileLock lock = buildXml.lock();
    OutputStream os = buildXml.getOutputStream(lock);
    PrintWriter pw = new PrintWriter(os);
    pw.println("<project name='my proj' default='whatever' basedir='.'>");
    pw.println(" <target name='targ1'>");
    pw.println("  <echo>hello #1</echo>");
    pw.println(" </target>");
    pw.println(" <target name='targ2'>");
    pw.println("  <echo>hello #2</echo>");
    pw.println(" </target>");
    pw.println("</project>");
    pw.flush();
    os.close();
    lock.releaseLock();
    project = new AntProjectSupport(buildXml);
    Document doc = project.getDocument();
    assertNotNull("parsed " + buildXml, doc);
    Element docEl = doc.getDocumentElement();
    NodeList nl = docEl.getElementsByTagName("target");
    target1 = (Element)nl.item(0);
    assertEquals("target #1", "targ1", target1.getAttribute("name"));
    iter = new ShortcutIterator();
    wiz = new ShortcutWizard(project, target1, iter);
}
 
Example 20
Project: incubator-netbeans   File: ClasspathsTest.java   View Source Code Vote up 4 votes
public void testCompileClasspathChanges() throws Exception {
    clearWorkDir();
    FreeformProject simple2 = copyProject(simple);
    FileObject myAppJava2 = simple2.getProjectDirectory().getFileObject("src/org/foo/myapp/MyApp.java");
    assertNotNull("found MyApp.java", myAppJava2);
    ClassPath cp = ClassPath.getClassPath(myAppJava2, ClassPath.COMPILE);
    assertNotNull("have some COMPILE classpath for src/", cp);
    assertEquals("have two entries in " + cp, 2, cp.entries().size());
    assertEquals("have two roots in " + cp, 2, cp.getRoots().length);
    assertNotNull("found WeakSet in " + cp, cp.findResource("org/openide/util/WeakSet.class"));
    assertNotNull("found NullInputStream", cp.findResource("org/openide/util/io/NullInputStream.class"));
    TestPCL l = new TestPCL();
    cp.addPropertyChangeListener(l);
    EditableProperties props = new EditableProperties();
    FileObject buildProperties = simple2.getProjectDirectory().getFileObject("build.properties");
    assertNotNull("have build.properties", buildProperties);
    InputStream is = buildProperties.getInputStream();
    try {
        props.load(is);
    } finally {
        is.close();
    }
    assertEquals("right original src.cp", "${lib.dir}/lib1.jar:${lib.dir}/lib2.jar", props.getProperty("src.cp"));
    props.setProperty("src.cp", "${lib.dir}/lib1.jar");
    FileLock lock = buildProperties.lock();
    try {
        final OutputStream os = buildProperties.getOutputStream(lock);
        try {
            props.store(os);
        } finally {
            // close file under ProjectManager.readAccess so that events are fired synchronously
            ProjectManager.mutex().readAccess(new Mutex.ExceptionAction<Void>() {
                public Void run() throws Exception {
                    os.close();
                    return null;
                }
            });
        }
    } finally {
        lock.releaseLock();
    }
    /* XXX failing: #137767
    assertEquals("ROOTS fired", new HashSet<String>(Arrays.asList(ClassPath.PROP_ENTRIES, ClassPath.PROP_ROOTS)), l.changed);
    assertEquals("have one entry in " + cp, 1, cp.entries().size());
    assertEquals("have one root in " + cp, 1, cp.getRoots().length);
    assertNotNull("found WeakSet in " + cp, cp.findResource("org/openide/util/WeakSet.class"));
    assertNull("did not find NullInputStream", cp.findResource("org/openide/util/io/NullInputStream.class"));
     */
}