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

The following examples show how to use org.openide.filesystems.FileObject#lock() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   File: ProvidedExtensionsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testImplsFileLock() throws IOException {
    FileObject fo = FileUtil.toFileObject(getWorkDir());
    assertNotNull(fo);
    assertNotNull(iListener);
    iListener.clear();
    FileObject toLock = fo.createData(getName());
    assertNotNull(toLock);
    assertEquals("Check on " + iListener, 0, iListener.implsFileLockCalls);
    FileLock fLock = toLock.lock();
    try {
        assertTrue(fLock.isValid());
        assertEquals(0, iListener.implsFileUnlockCalls);                        
        assertEquals(1, iListener.implsFileLockCalls);            
    } finally {
        fLock.releaseLock();
        assertEquals("Just one unlock " + iListener, 1, iListener.implsFileUnlockCalls);                                    
    }        
}
 
Example 2
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 3
Source Project: netbeans   File: FolderObjTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRenameWithAttributes() throws Exception {
    final FileObject workDirFo = FileBasedFileSystem.getFileObject(getWorkDir());
    FileObject folder = workDirFo.createFolder("a");
    folder.createData("non.empty");
    folder.setAttribute("name", "jmeno");
    assertEquals("jmeno", folder.getAttribute("name"));
    FileLock lock = folder.lock();
    folder.rename(lock, "b", null);
    lock.releaseLock();
    assertEquals("Name is not b", "b", folder.getNameExt());
    WeakReference<?> ref = new WeakReference<FileObject>(folder);
    folder = null;
    assertGC("Folder can disappear", ref);
    folder = workDirFo.getFileObject("b");
    assertNotNull("Folder b found", folder);
    assertEquals("The attribute remains even after rename", "jmeno", folder.getAttribute("name"));
    assertEquals("One children", 1, folder.getChildren().length);
}
 
Example 4
private static void replaceTokens(FileObject fO, Map<String, String> tokens) throws IOException {
    FileLock lock = fO.lock();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileUtil.toFile(fO)));
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            for(Map.Entry e:tokens.entrySet()) {
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                line = line.replaceAll(key, value);
            }
            sb.append(line+"\n");
        }
        OutputStreamWriter writer = new OutputStreamWriter(fO.getOutputStream(lock), "UTF-8");
        try {
            writer.write(sb.toString());
        } finally {
            writer.close();
        }
    } finally {
        lock.releaseLock();
    }
}
 
Example 5
Source Project: netbeans   File: PersistenceManager.java    License: Apache License 2.0 6 votes vote down vote up
/** Deletes specified file object */
public static void deleteOneFO (FileObject fo) {
    FileLock lock = null;
    if (fo.isValid()) {
        try {
            lock = fo.lock();
            fo.delete(lock);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            if (lock != null) {
                lock.releaseLock();
            }
        }
    }
}
 
Example 6
Source Project: netbeans   File: JavaSourceUtilImplTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void dump(
        final FileObject wd,
        final Map<String,byte[]> clzs) throws IOException {
    for (Map.Entry<String,byte[]> clz : clzs.entrySet()) {
        final String extName = FileObjects.convertPackage2Folder(clz.getKey());
        final FileObject data = FileUtil.createData(wd, String.format(
                "%s.class", //NOI18N
                extName));
        FileLock l = data.lock();
        try (final OutputStream out = data.getOutputStream(l)) {
            out.write(clz.getValue());
        }finally {
            l.releaseLock();
        }
    }
    System.out.printf("Dumped into: %s%n", FileUtil.getFileDisplayName(wd));
}
 
Example 7
Source Project: netbeans   File: BaseFileObjectTestHid.java    License: Apache License 2.0 6 votes vote down vote up
public void testCaseSensitiveFolderRename() throws Exception {
    FileObject parent = root.getFileObject("testdir/mountdir10");
    List<FileObject> arr = Arrays.asList(parent.getChildren());
    final String up = parent.getName().toUpperCase();
    FileLock lock = parent.lock();
    try {
        parent.rename(lock, up, null);
    } finally {
        lock.releaseLock();
    }
    assertEquals("Capital name", up, parent.getNameExt());
    File real = FileUtil.toFile(parent);
    assertNotNull("Real file exists", real);
    assertEquals("It is capitalized too", up, real.getName());
    
    List<FileObject> now = Arrays.asList(parent.getChildren());
    assertEquals("Same children: ", arr, now);
}
 
Example 8
@Override
public void store(URL key, Entry<BufferedImage> value) {
    if (value.getContent() == null) return;
    FileLock outputLock = null;
    try {
        String fileName = entryFileName(key);
        FileObject imageFile = storage.getFileObject(fileName);
        if (imageFile == null) {
            imageFile = storage.createData(fileName);
        }
        if (imageFile != null) {
            outputLock = imageFile.lock();
            ImageIO.write(value.getContent(), "png", imageFile.getOutputStream(outputLock));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (outputLock != null) {
            outputLock.releaseLock();
        }
    }
}
 
Example 9
Source Project: netbeans   File: InterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
private void moveFO (File from, File to) throws DataObjectNotFoundException, IOException {
    FileObject foFrom = FileUtil.toFileObject(from);
    assertNotNull(foFrom);
    FileObject foTarget = FileUtil.toFileObject(to.getParentFile());
    assertNotNull(foTarget);
    FileLock lock = foFrom.lock();
    try {
        foFrom.move(lock, foTarget, to.getName(), null);
    } finally {
        lock.releaseLock();
    }
}
 
Example 10
Source Project: netbeans   File: ModeParser.java    License: Apache License 2.0 5 votes vote down vote up
/** 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 11
Source Project: jeddict   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void createFile(FileObject target, String content, String encoding) throws IOException {
    FileLock lock = target.lock();
    try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(target.getOutputStream(lock), encoding))) {
        bw.write(content);
    } finally {
        lock.releaseLock();
    }
}
 
Example 12
Source Project: netbeans   File: J2SEDeployProperties.java    License: Apache License 2.0 5 votes vote down vote up
static FileObject copyBuildNativeTemplate(@NonNull final Project project) throws IOException {
    Parameters.notNull("project", project); //NOI18N
    final FileObject buildExFoBack = project.getProjectDirectory().getFileObject(String.format(
        "%s~",  //NOI18N
        EXTENSION_BUILD_SCRIPT_PATH));
    if (buildExFoBack != null) {
        closeInEditor(buildExFoBack);
        buildExFoBack.delete();
    }
    FileObject buildExFo = project.getProjectDirectory().getFileObject(EXTENSION_BUILD_SCRIPT_PATH);
    FileLock lock;
    if (buildExFo != null) {
        closeInEditor(buildExFo);
        lock = buildExFo.lock();
        try {
            buildExFo.rename(
                lock,
                buildExFo.getName(),
                String.format(
                    "%s~",  //NOI18N
                    buildExFo.getExt()));
        } finally {
            lock.releaseLock();
        }
    }
    buildExFo = FileUtil.createData(project.getProjectDirectory(), EXTENSION_BUILD_SCRIPT_PATH);
    lock = buildExFo.lock();
    try (final InputStream in = J2SEDeployProperties.class.getClassLoader().getResourceAsStream(BUILD_SCRIPT_PROTOTYPE);
         final OutputStream out = buildExFo.getOutputStream(lock)) {
        FileUtil.copy(in, out);
    } finally {
        lock.releaseLock();
    }
    return buildExFo;
}
 
Example 13
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 14
Source Project: netbeans   File: BaseFileObjectTestHid.java    License: Apache License 2.0 5 votes vote down vote up
public void testCaseSensitiveRenameEventForMasterFS() throws Exception {
    FileObject parent = root.getFileObject("testdir").createFolder("parent");
    FileObject file = parent.createData("origi.nal");
    file.addFileChangeListener(new FileChangeAdapter() {
        @Override
        public void fileRenamed(FileRenameEvent fe) {
            assertEquals("origi", fe.getName());
            assertEquals("nal", fe.getExt());
        }
    });
    FileLock lock = file.lock();
    file.rename(lock, "Origi", "nal");
    lock.releaseLock();
}
 
Example 15
Source Project: netbeans   File: TreePathHandleTest.java    License: Apache License 2.0 5 votes vote down vote up
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 16
private void createFile(FileObject target, String content, String encoding) throws IOException{            
    FileLock lock = target.lock();
    try {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(target.getOutputStream(lock), encoding));
        bw.write(content);
        bw.close();

    }
    finally {
        lock.releaseLock();
    }
}
 
Example 17
Source Project: netbeans   File: StatFilesTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testLockFile() throws IOException {
    FileObject fobj = getFileObject(testFile);
    monitor.reset();
    final FileLock lock = fobj.lock();
    try {
        int expectedCount = 0;
        if (Utilities.isUnix()) {
            // called File.toURI() from FileUtil.normalizeFile()
            expectedCount = 1;
        }
        // we check canWrite once
        monitor.getResults().assertResult(1, StatFiles.WRITE);
        // adding one for the canWrite access above
        monitor.getResults().assertResult(1 + expectedCount, StatFiles.ALL);
        //second time
        monitor.reset();
        FileLock lock2 = null;
        try {
            lock2 = fobj.lock();
            fail();
        } catch (IOException ex) {
        }
        // again one for canWrite
        monitor.getResults().assertResult(1 + expectedCount, StatFiles.ALL);
    } finally {
        lock.releaseLock();
    }
}
 
Example 18
Source Project: netbeans   File: Controller.java    License: Apache License 2.0 4 votes vote down vote up
void saveTransaction(Node[] nodes) {

	if(!haveDirectories()) {
	    // PENDING - report the error properly
	    // This should not happen
	    log("Couldn't get the directory"); //NOI18N
	    return;
	}

	Node[] newNodes = new Node[nodes.length];
	TransactionNode mvNode; 
	String id;
	 
	boolean error = false; 

	for(int i=0; i < nodes.length; ++i) {
	    
	    mvNode = (TransactionNode)nodes[i];
	    id = mvNode.getID();
	    
	    if(debug) log(" Saving " + id); //NOI18N 

	    if(currBeans.containsKey(id)) 
		saveBeans.put(id, currBeans.remove(id)); 
	    
	    // Note I didn't load the bean here yet. Will only do that 
	    // if the data is displayed. 
		
	    FileLock lock = null; 
	    try {
		FileObject fold = 
		    currDir.getFileObject(id, "xml"); //NOI18N
		lock = fold.lock();
		fold.copy(saveDir, id, "xml"); //NOI18N
		if(debug) log(fold.getName());
		fold.delete(lock);
		mvNode.setCurrent(false);
		newNodes[i] = mvNode;
	    }
	    catch(FileAlreadyLockedException falex) {
		error = true;
		// PENDING report properly
	    }
	    catch(IOException ioex) {
		error = true;
		// PENDING report properly
	    }
	    catch(Exception ex) {
		error = true; 
		// PENDING report properly
	    }
	    finally { 
		if(lock != null) lock.releaseLock(); 
	    }
	    
	}
	if(!error) currTrans.remove(nodes);
	savedTrans.add(newNodes);
    }
 
Example 19
@Override
public List<FileObject> createFromTemplate(CreateDescriptor desc) throws IOException {
    FileObject template = desc.getTemplate();
    String name = desc.getProposedName();
    Map<String, ?> values = desc.getParameters();
    FileObject f = desc.getTarget();
    
    boolean noExt = desc.hasFreeExtension() && name.indexOf('.') != -1;
    
    String extWithDot;
    if (noExt) {
        extWithDot = null;
    } else {
        extWithDot = '.' + template.getExt();
        if (name.endsWith(extWithDot)) { // Test whether the extension happens to be there already
            // And remove it if yes, it will be appended to the unique name.
            name = name.substring(0, name.length() - extWithDot.length());
        }
    }
    
    String nameUniq = FileUtil.findFreeFileName(f, name, noExt ? null : template.getExt());
    FileObject output = FileUtil.createData(f, noExt ? nameUniq : nameUniq + extWithDot);
    Charset targetEnc = FileEncodingQuery.getEncoding(output);
    Charset sourceEnc = FileEncodingQuery.getEncoding(template);
    
    ScriptEngine eng = engine(template);
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);
    
    if(!values.containsKey(ENCODING_PROPERTY_NAME)) {
        bind.put(ENCODING_PROPERTY_NAME, targetEnc.name());
    }
    
    //Document doc = createDocument(template.getMIMEType());
    FileLock lock = output.lock();
    try (Writer w = new OutputStreamWriter(output.getOutputStream(lock), targetEnc);
         Reader is = new InputStreamReader(template.getInputStream(), sourceEnc);
        /*IndentWriter w2 = new IndentWriter(doc, 0, w, false) */) {
        StringWriter sw = new StringWriter();
        ScriptEngine eng2 = desc.isPreformatted() ? null : indentEngine();
        
        eng.getContext().setWriter(new PrintWriter(eng2 != null ? sw : w));
        //eng.getContext().setBindings(bind, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE);
        eng.eval(is);
        
        if (eng2 != null) {
            eng2.getContext().setAttribute("mimeType", template.getMIMEType(), ScriptContext.ENGINE_SCOPE);
            eng2.getContext().setWriter(w);
            eng2.eval(new StringReader(sw.toString()));
        }
    }catch (ScriptException ex) {
        IOException io = new IOException(ex.getMessage(), ex);
        throw io;
    } finally {
        lock.releaseLock();
    }
    return Collections.singletonList(output);
}
 
Example 20
Source Project: netbeans   File: ModuleLifecycleManager.java    License: Apache License 2.0 4 votes vote down vote up
void disableOtherModules () {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            boolean notify = false;
            outter: for (int i = 0; i < otherGitModules.length; i++) {
                FileLock lock = null;
                OutputStream os = null;
                try {
                    String newModule = otherGitModules[i];
                    String newModuleXML = "Modules/" + newModule.replace('.', '-') + ".xml"; // NOI18N
                    FileObject fo = FileUtil.getConfigFile(newModuleXML);
                    if (fo == null) continue;
                    Document document = readModuleDocument(fo);

                    NodeList list = document.getDocumentElement().getElementsByTagName("param"); // NOI18N
                    int n = list.getLength();
                    for (int j = 0; j < n; j++) {
                        Element node = (Element) list.item(j);
                        if ("enabled".equals(node.getAttribute("name"))) { // NOI18N
                            Text text = (Text) node.getChildNodes().item(0);
                            String value = text.getNodeValue();
                            if ("true".equals(value)) { // NOI18N
                                text.setNodeValue("false"); // NOI18N
                                break;
                            } else {
                                continue outter;
                            }
                        }
                    }
                    notify = true;                            
                    lock = fo.lock();
                    os = fo.getOutputStream(lock);
                    
                    XMLUtil.write(document, os, "UTF-8"); // NOI18N
                } catch (Exception e) {
                    Git.LOG.log(Level.WARNING, null, e);
                } finally {
                    if (os != null) try { os.close(); } catch (IOException ex) {}
                    if (lock != null) lock.releaseLock();
                }
            }
            if(notify) {
                JTextPane ballonDetails = getPane(NbBundle.getBundle(ModuleLifecycleManager.class).getString("MSG_Install_Warning")); // using the same pane causes the balloon popup
                JTextPane popupDetails = getPane(NbBundle.getBundle(ModuleLifecycleManager.class).getString("MSG_Install_Warning"));  // to trim the text to the first line
                NotificationDisplayer.getDefault().notify(
                        NbBundle.getMessage(ModuleLifecycleManager.class, "MSG_Install_Warning_Title"), //NOI18N
                        ImageUtilities.loadImageIcon("org/netbeans/modules/git/resources/icons/info.png", false),
                        ballonDetails, popupDetails, NotificationDisplayer.Priority.NORMAL, NotificationDisplayer.Category.WARNING);
            }
        }
                    
        private JTextPane getPane(String txt) {
            JTextPane bubble = new JTextPane();
            bubble.setOpaque(false);
            bubble.setEditable(false);
            if (UIManager.getLookAndFeel().getID().equals("Nimbus")) {                   //NOI18N
                //#134837
                //http://forums.java.net/jive/thread.jspa?messageID=283882
                bubble.setBackground(new Color(0, 0, 0, 0));
            }
            bubble.setContentType("text/html");                                          //NOI18N
            bubble.setText(txt);
            return bubble;
        }             
    };
    RequestProcessor.getDefault().post(runnable);
}