Java Code Examples for org.openide.filesystems.FileSystem#AtomicAction

The following examples show how to use org.openide.filesystems.FileSystem#AtomicAction . 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: DataShadowTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCreatedShadowFoundInParent() throws Exception {
    class R implements FileSystem.AtomicAction {
        @Override
        public void run() throws IOException {
            DataObject[] old = folder.getChildren();
            assertEquals("No children yet", 0, old.length);
            DataShadow ds = original.createShadow(folder);
            assertEquals("Parent is OK", folder, ds.getFolder());
            DataObject[] arr = folder.getChildren();
            List<DataObject> all = Arrays.asList(arr);
            assertTrue("Newly created " + ds + " shall be in list of children", all.contains(ds));
        }
    }
    R action = new R();
    FileUtil.runAtomicAction(action);
}
 
Example 2
Source File: DataEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** The time when the data has been modified
*/
public Date getTime() {
    // #32777 - refresh file object and return always the actual time
    action = new FileSystem.AtomicAction() {
        public void run() throws IOException {
            getFileImpl().refresh(false);
        }
    };
    try {
        getFileImpl().getFileSystem().runAtomicAction(action);
    } catch (IOException ex) {
        //Nothing to do here
    }
    
    return getFileImpl ().lastModified ();
}
 
Example 3
Source File: ToolbarPoolDeadlockTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 4
Source File: StorageImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void runAtomicAction(FileSystem.AtomicAction task) throws IOException {
    assert atomicAction == null;
    atomicAction = task;
    try {
        fileSystem.runAtomicAction(task);
    } finally {
        atomicAction = null;
    }
}
 
Example 5
Source File: DataShadowTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeleteInvalidatesCreateCreatesWhenChangeHappensInAtomicAction () throws Exception {
    DataShadow shade = original.createShadow (folder);
    FileObject primary = shade.getPrimaryFile ();

    assertTrue ("Is valid now", shade.isValid ());
    
    class DeleteCreate implements FileSystem.AtomicAction {
        public FileObject fo;
        
        public void run () throws java.io.IOException {
            FileSystem fs = original.getPrimaryFile ().getFileSystem ();
            String create = original.getPrimaryFile ().getPath ();
            original.getPrimaryFile ().delete ();
            
            fo = FileUtil.createData (fs.getRoot (), create);
        }
    }
    DeleteCreate deleteCreate = new DeleteCreate ();
    original.getPrimaryFile ().getFileSystem ().runAtomicAction (deleteCreate);
    
    assertTrue ("Shadow is valid (again)", shade.isValid ());
    assertFalse ("Original is gone", original.isValid ());
    DataObject orig = DataObject.find (deleteCreate.fo);
    if (orig == original) {
        fail ("new original shall be created");
    }
    assertTrue ("New orig is valid", orig.isValid ());
    
    // life would be nicer without this sleep, but somewhere inside
    // the DataShadow validation a request is send to RP with a delay
    // to not slow down regular apps. If you managed to kill next line,
    // you will have done the right job. Meanwhile it is here:
    Thread.sleep (2000);
    
    assertEquals ("Shadow's original is updated", orig, shade.getOriginal ());
}
 
Example 6
Source File: PropertiesEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Helper method. Saves this entry. */
    private void saveThisEntry() throws IOException {
        FileSystem.AtomicAction aa = new SaveImpl(this);
        FileUtil.runAtomicAction(aa);
//        super.saveDocument();
        // #32777 - it can happen that save operation was interrupted
        // and file is still modified. Mark it unmodified only when it is really
        // not modified.
        if (!env.isModified()) {
            myEntry.setModified(false);
        }
    }
 
Example 7
Source File: FileManagerTransaction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Future<Void> runConcurrent(@NonNull final FileSystem.AtomicAction action) throws IOException {
    Parameters.notNull("action", action);   //NOI18N
    final FileManagerTransaction fmtx = TransactionContext.get().get(FileManagerTransaction.class);
    if (fmtx == null) {
        throw new IllegalStateException("No FileManagerTransaction");   //NOI18N
    }
    final Future<Void> res;
    fmtx.fork();
    try {
        action.run();
    } finally {
        res = fmtx.join();
    }
    return res;
}
 
Example 8
Source File: ToolbarPoolDeadlockTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWhoCreatesConstructor() throws Exception {
    FileObject root = FileUtil.getConfigRoot();
    FileObject fo = FileUtil.createFolder (root, "ToolbarsWhoCreates");
    final DataFolder df = DataFolder.findFolder(fo);
    ToolbarPool pool = new ToolbarPool(df);

    assertEquals("No children now", 0, pool.getToolbars().length);

    class Atom implements FileSystem.AtomicAction {

        FileObject m1, m2;

        public void run() throws IOException {
            m1 = FileUtil.createFolder(df.getPrimaryFile(), "m1");
            DataFolder f1 = DataFolder.findFolder(m1);
            InstanceDataObject.create(f1, "X", MyAction.class);
        }
    }
    Atom atom = new Atom();
    df.getPrimaryFile().getFileSystem().runAtomicAction(atom);
    pool.waitFinished();

    assertEquals("One toolbar is there", 1, pool.getToolbars().length);
    Toolbar tb = pool.getToolbars()[0];
    assertEquals("Pool name", "m1", tb.getName());
    assertEquals("Has one subcomponent", 1, tb.getComponents().length);
    Object o1 = tb.getComponent(0);
    if (!(o1 instanceof JButton)) {
        fail("Need JPanel " + o1);
    }
    assertEquals("And now the action is created", 1, MyAction.counter);
}
 
Example 9
Source File: ToolbarPoolTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 10
Source File: ToolbarPoolTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWhoCreatesConstructor() throws Exception {
    FileObject root = FileUtil.getConfigRoot();
    FileObject fo = FileUtil.createFolder (root, "ToolbarsWhoCreates");
    final DataFolder df = DataFolder.findFolder(fo);
    ToolbarPool pool = new ToolbarPool(df);

    assertEquals("No children now", 0, pool.getToolbars().length);

    class Atom implements FileSystem.AtomicAction {

        FileObject m1, m2;

        public void run() throws IOException {
            m1 = FileUtil.createFolder(df.getPrimaryFile(), "m1");
            DataFolder f1 = DataFolder.findFolder(m1);
            InstanceDataObject.create(f1, "X", MyAction.class);
        }
    }
    Atom atom = new Atom();
    df.getPrimaryFile().getFileSystem().runAtomicAction(atom);

    assertEquals("One toolbar is there", 1, pool.getToolbars().length);
    Toolbar tb = pool.getToolbars()[0];
    assertEquals("Pool name", "m1", tb.getName());
    assertEquals("Has one subcomponent", 1, tb.getComponents().length);
    Object o1 = tb.getComponent(0);
    if (!(o1 instanceof JButton)) {
        fail("Need JPanel " + o1);
    }
    assertEquals("And now the action is created", 1, MyAction.counter);
}
 
Example 11
Source File: ProvidedExtensionsProxy.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void runCheckCode(FileSystem.AtomicAction code) throws IOException {
    try {
        reentrantCheck.set(Boolean.TRUE);
        code.run();
    } finally {
        reentrantCheck.set(null);
    }
}
 
Example 12
Source File: ModuleList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Check if a given file event in the Modules/ folder was a result
 * of our own manipulations, as opposed to some other code (or polled
 * refresh) manipulating one of these XML files. See #15573.
 */
private boolean isOurs(FileEvent ev) {
    for (FileSystem.AtomicAction action : myAtomicActions) {
        if (ev.firedFrom(action)) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: ModuleList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Delete a module from disk.
 */
private void deleteFromDisk(final Module m, final DiskStatus status) throws IOException {
    final String nameDashes = m.getCodeNameBase().replace('.', '-'); // NOI18N
    //final long expectedTime = status.lastApprovedChange;
    FileSystem.AtomicAction aa = new FileSystem.AtomicAction() {
        public void run() throws IOException {
            FileObject xml = folder.getFileObject(nameDashes, "xml"); // NOI18N
            if (xml == null) {
                // Could be that the XML was already deleted externally, etc.
                LOG.fine("ModuleList: " + m + "'s XML already gone from disk");
                return;
            }
            //if (xml == null) throw new IOException("No such XML file: " + nameDashes + ".xml"); // NOI18N
            if (status.dirty) {
                // Someone wrote to the file since we did. Don't delete it blindly!
                // XXX should this throw an exception, or just warn??
                throw new IOException("Unapproved external change to " + xml); // NOI18N
            }
            LOG.fine("ModuleList: deleting " + xml);
            /*
            if (xml.lastModified().getTime() != expectedTime) {
                // Someone wrote to the file since we did. Don't delete it blindly!
                throw new IOException("Unapproved external change to " + xml); // NOI18N
            }
             */
            xml.delete();
            FileObject ser = folder.getFileObject(nameDashes, "ser"); // NOI18N
            if (ser != null) {
                LOG.fine("(and also " + ser + ")");
                ser.delete();
            }
        }
    };
    myAtomicActions.add(aa);
    folder.getFileSystem().runAtomicAction(aa);
}
 
Example 14
Source File: DataEditorSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Saves document. Overrides superclass method, adds checking
 * for read-only property of saving file and warns user in that case. */
@Override
public void saveDocument() throws IOException {
    FileSystem.AtomicAction aa = new SaveImpl(this);
    FileUtil.runAtomicAction(aa);
}
 
Example 15
Source File: ScheduledRequest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates a new instance of ScheduledRequest
 * @param fobj file containing a persistent setting object
 * @param run impl performing the storing task
 */
public ScheduledRequest(FileObject fobj, FileSystem.AtomicAction run) {
    this.fobj = fobj;
    this.run = run;
}
 
Example 16
Source File: SerialDataConvertorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Tests the creation in atomic section.
 */
public void testSameInAtomicSection () throws Exception {
    class AtomAct extends FileChangeAdapter 
    implements FileSystem.AtomicAction {
        
        private java.awt.Button testSer = new java.awt.Button ();
        
        private FileObject data;
        private InstanceDataObject obj;
        
        public void run () throws IOException {
            folder.getPrimaryFile ().addFileChangeListener (this);
            data = folder.getPrimaryFile ().createData ("SomeData");
            
            
            obj = InstanceDataObject.create (folder, null, testSer, null);
        }
        
        public void doTest () throws Exception {
            Object now = obj.instanceCreate ();
            if (now != testSer) {
                fail ("Different values. Original: " + testSer + " now: " + now);
            }
        }
        
        public void cleanUp () throws Exception {
            data.delete ();
            obj.delete ();
        }
        
        public void fileDataCreated (FileEvent ev) {
            try {
                Thread.sleep (500);
            } catch (Exception ex) {
            }
        }
    }

    
    AtomAct t = new AtomAct ();
    try {
        folder.getPrimaryFile().getFileSystem ().runAtomicAction (t);

        t.doTest ();
    } finally {
        t.cleanUp ();
    }
}
 
Example 17
Source File: StorageImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean filterEvents(FileEvent event) {
    // filter out anything that does not match required file path pattern
    if (!controlledFilesPattern.matcher(event.getFile().getPath()).matches()) {
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer(event.getFile().getPath() + " does not match: " + controlledFilesPattern.pattern()); //NOI18N
        }
        return true;
    }

    // filter out our own events
    final FileSystem.AtomicAction aa = atomicAction;
    if (aa != null && event.firedFrom(aa)) {
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("Filesystem event for " + event.getFile().getPath() + " caused by saving settings"); //NOI18N
        }
        return true;
    }
    
    // filter out duplicate events, maybe this does not have any effect
    synchronized (recentEvents) {
        for(Iterator<Reference<FileEvent>> i = recentEvents.iterator(); i.hasNext(); ) {
            Reference<FileEvent> ref = i.next();
            FileEvent e = ref.get();
            if (e == null) {
                i.remove();
            } else {
                if (e == event) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("Filtering out duplicate filesystem event (1): original=[" + printEvent(e) + "]" //NOI18N
                            + ", duplicate=[" + printEvent(event) + "]"); //NOI18N
                    }
                    return true;
                }
                
                if (e.getTime() == event.getTime() && e.getFile().getPath().equals(event.getFile().getPath())) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("Filtering out duplicate filesystem event (2): original=[" + printEvent(e) + "]" //NOI18N
                                + ", duplicate=[" + printEvent(event) + "]"); //NOI18N
                    }
                    return true;
                }
            }
        }

        if (recentEvents.size() > 100) {
            recentEvents.remove(recentEvents.size() - 1);
        }
        recentEvents.add(0, new WeakReference<FileEvent>(event));
        return false;
    }
}
 
Example 18
Source File: CachingAndExternalPathsTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@RandomlyFails
public void testInitUserDir() throws Exception {
    File simpleModule = new File(System.getProperty("external.jar"));

    File newModule = new File(new File(new File(System.getProperty("netbeans.user")), "modules"), "org-external.jar");
    newModule.getParentFile().mkdirs();
    simpleModule.renameTo(newModule);
    assertTrue("New module correctly created", newModule.exists());

    class Activate implements FileSystem.AtomicAction {
        FileObject fo;

        public Activate() throws IOException {
        }
        
        public void run() throws IOException {
            fo = FileUtil.getConfigFile("Modules").createData("org-external.xml");
            OutputStream os = fo.getOutputStream();
            os.write((
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
    "<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"\n" +
    "                        \"http://www.netbeans.org/dtds/module-status-1_0.dtd\">\n" +
    "<module name=\"org.external\">\n" +
    "    <param name=\"autoload\">false</param>\n" +
    "    <param name=\"eager\">false</param>\n" +
    "    <param name=\"enabled\">true</param>\n" +
    "    <param name=\"jar\">modules/org-external.jar</param>\n" +
    "    <param name=\"reloadable\">false</param>\n" +
    "</module>\n" +
    "").getBytes());
            os.close();
        }
    }
    Activate a = new Activate();
    System.getProperties().remove("activated.ok");

    LOG.log(Level.INFO, "Creating config file");
    FileUtil.runAtomicAction(a);
    LOG.log(Level.INFO, "Done creating {0}", a.fo);


    for (int i = 0; i < 360 && System.getProperty("activated.ok") == null; i++) {
        LOG.log(Level.INFO, "Not found, but activated.ok: {0}", System.getProperty("activated.ok"));
        Thread.sleep(500);
    }
    LOG.log(Level.INFO, "activated.ok: {0}", System.getProperty("activated.ok"));
    assertEquals("true", System.getProperty("activated.ok"));
    doNecessarySetup();
    
    LOG.info("testInitUserDir - finished");
}
 
Example 19
Source File: CachingPreventsFileTouchesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testInitUserDir() throws Exception {
    File simpleModule = new File(System.getProperty("activate.jar"));

    File newModule = new File(new File(new File(System.getProperty("netbeans.user")), "modules"), "org-activate.jar");
    newModule.getParentFile().mkdirs();
    simpleModule.renameTo(newModule);
    assertTrue("New module correctly created", newModule.exists());

    class Activate implements FileSystem.AtomicAction {
        public void run() throws IOException {
            FileObject fo = FileUtil.getConfigFile("Modules").createData("org-activate.xml");
            OutputStream os = fo.getOutputStream();
            os.write((
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
    "<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"\n" +
    "                        \"http://www.netbeans.org/dtds/module-status-1_0.dtd\">\n" +
    "<module name=\"org.activate\">\n" +
    "    <param name=\"autoload\">false</param>\n" +
    "    <param name=\"eager\">false</param>\n" +
    "    <param name=\"enabled\">true</param>\n" +
    "    <param name=\"jar\">modules/org-activate.jar</param>\n" +
    "    <param name=\"reloadable\">false</param>\n" +
    "</module>\n" +
    "").getBytes());
            os.close();
        }
    }

    FileUtil.runAtomicAction(new Activate());


    Class<?> main = null;
    Object s = null;
    for (int i = 0; i < 360; i++) {
        LOG.log(Level.INFO, "testInitUserDir - waiting for activation {0}", i);
        try {
            main = Thread.currentThread().getContextClassLoader().loadClass("org.activate.Main");
            s = main.getField("start").get(null);
            if (s == null) {
                Thread.sleep(500);
                continue;
            }
        } catch (ClassNotFoundException ex) {
            Thread.sleep(500);
            continue;
        }
        break;
    }
    LOG.log(Level.INFO, "testInitUserDir - waiting for activation over. Testing.");
    assertNotNull("Activate module shall start", main);
    LOG.log(Level.INFO, "checking field from {0}", main);
    s = main.getField("start").get(null);
    assertNotNull("Bundle started, its context provided", s);

    CachingAndExternalPathsTest.doNecessarySetup();
    
    LOG.info("testInitUserDir - finished");
}
 
Example 20
Source File: ModuleList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Write information about a module out to disk.
 * If the old status is given as null, this is a newly
 * added module; create an appropriate status and return it.
 * Else update the existing status and return it (it is
 * assumed properties are already updated).
 * Should write the XML and create/rewrite/delete the serialized
 * installer file as needed.
 */
private DiskStatus writeOut(Module m, DiskStatus old) throws IOException {
    final DiskStatus nue;
    if (old == null) {
        nue = new DiskStatus();
        nue.module = m;
        nue.setDiskProps(computeProperties(m));
    } else {
        nue = old;
    }
    FileSystem.AtomicAction aa = new FileSystem.AtomicAction() {
        public void run() throws IOException {
            if (nue.file == null) {
                nue.file = FileUtil.createData(folder, ((String)nue.diskProps.get("name")).replace('.', '-') + ".xml"); // NOI18N
            } else {
                // Just verify that no one else touched it since we last did.
                if (/*nue.lastApprovedChange != nue.file.lastModified().getTime()*/nue.dirty) {
                    // Oops, something is wrong. #156764 - log at lower level.
                    LOG.log(Level.INFO, null, new IOException("Will not clobber external changes in " + nue.file));
                    return;
                }
            }
            LOG.fine("ModuleList: (re)writing " + nue.file);
            FileLock lock = nue.file.lock();
            try {
                OutputStream os = nue.file.getOutputStream(lock);
                try {
                    writeStatus(nue.diskProps, os);
                } finally {
                    os.close();
                }
            } finally {
                lock.releaseLock();
            }
            //nue.lastApprovedChange = nue.file.lastModified().getTime();
        }
    };
    myAtomicActions.add(aa);
    folder.getFileSystem().runAtomicAction(aa);
    return nue;
}