Java Code Examples for org.openide.filesystems.FileUtil#runAtomicAction()

The following examples show how to use org.openide.filesystems.FileUtil#runAtomicAction() . 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: DDHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Created validation.xml deployment descriptor
 * @param j2eeProfile Java EE profile
 * @param dir Directory where validation.xml should be created
 * @param name name of configuration file to create;
 * @return validation.xml file as FileObject
 * @throws IOException
 * @since 1.52
 */
public static FileObject createValidationXml(Profile j2eeProfile, FileObject dir, String name) throws IOException {
    String template = null;
    if (Profile.JAVA_EE_6_FULL == j2eeProfile || Profile.JAVA_EE_6_WEB == j2eeProfile ||
            Profile.JAVA_EE_7_FULL == j2eeProfile || Profile.JAVA_EE_7_WEB == j2eeProfile ||
            Profile.JAVA_EE_8_FULL == j2eeProfile || Profile.JAVA_EE_8_WEB == j2eeProfile) {
        template = "validation.xml"; //NOI18N
    }

    if (template == null)
        return null;

    MakeFileCopy action = new MakeFileCopy(RESOURCE_FOLDER + template, dir, name+".xml");
    FileUtil.runAtomicAction(action);
    if (action.getException() != null)
        throw action.getException();
    else
        return action.getResult();
}
 
Example 2
Source File: DerbyOptions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void registerDrivers(final String newLocation) {
    try {
        // registering the drivers in an atomic action so the Drivers node
        // is refreshed only once
        FileUtil.runAtomicAction(new FileSystem.AtomicAction() {
            @Override
            public void run() {
                registerDriver(DRIVER_NAME_NET, DRIVER_DISP_NAME_NET, DRIVER_CLASS_NET,
                        new String[]{DRIVER_PATH_NET, DRIVER_PATH_EMBEDDED}, newLocation);
                registerDriver(DRIVER_NAME_EMBEDDED, DRIVER_DISP_NAME_EMBEDDED,
                        DRIVER_CLASS_EMBEDDED, new String[]{DRIVER_PATH_EMBEDDED}, newLocation);
            }
        });
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 3
Source File: DDHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates beans.xml deployment descriptor.
 * @param j2eeProfile Java EE profile to specify which version of beans.xml should be created
 * @param dir Directory where beans.xml should be created
 * @param name name of configuration file to create; should be always "beans" for now
 * @return beans.xml file as FileObject
 * @throws java.io.IOException
 * @since 1.49
 */
public static FileObject createBeansXml(Profile j2eeProfile, FileObject dir, String name) throws IOException {
    String template = null;
    if (Profile.JAVA_EE_6_FULL == j2eeProfile || Profile.JAVA_EE_6_WEB == j2eeProfile) {
        template = "beans-1.0.xml"; //NOI18N
    }
    if (Profile.JAVA_EE_7_FULL == j2eeProfile || Profile.JAVA_EE_7_WEB == j2eeProfile) {
        template = "beans-1.1.xml"; //NOI18N
    }
    if (Profile.JAVA_EE_8_FULL == j2eeProfile || Profile.JAVA_EE_8_WEB == j2eeProfile) {
        template = "beans-2.0.xml"; //NOI18N
    }

    if (template == null)
        return null;

    MakeFileCopy action = new MakeFileCopy(RESOURCE_FOLDER + template, dir, name+".xml");
    FileUtil.runAtomicAction(action);
    if (action.getException() != null)
        throw action.getException();
    else
        return action.getResult();
}
 
Example 4
Source File: DDHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Created Constraint declaration deployment descriptor
 * @param j2eeProfile Java EE profile
 * @param dir Directory where constraint.xml should be created
 * @param name name of configuration file to create;
 * @return validation.xml file as FileObject
 * @throws IOException
 * @since 1.52
 */
public static FileObject createConstraintXml(Profile j2eeProfile, FileObject dir, String name) throws IOException {
    String template = null;
    if (Profile.JAVA_EE_6_FULL == j2eeProfile || Profile.JAVA_EE_6_WEB == j2eeProfile ||
            Profile.JAVA_EE_7_FULL == j2eeProfile || Profile.JAVA_EE_7_WEB == j2eeProfile ||
            Profile.JAVA_EE_8_FULL == j2eeProfile || Profile.JAVA_EE_8_WEB == j2eeProfile) {
        template = "constraint.xml"; //NOI18N
    }

    if (template == null)
        return null;

    MakeFileCopy action = new MakeFileCopy(RESOURCE_FOLDER + template, dir, name+".xml");
    FileUtil.runAtomicAction(action);
    if (action.getException() != null)
        throw action.getException();
    else
        return action.getResult();
}
 
Example 5
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 6
Source File: FsEventFromAtomicActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFiredFromManyAtomicActions() throws Exception {
    final File workDir = getWorkDir();
    final FileObject workDirFo = FileUtil.toFileObject(workDir);

    final MyAtomicAction myAtomicAction = new MyAtomicAction();
    MyFileChangeListener myChangeListener = new MyFileChangeListener(myAtomicAction);
    FileUtil.addRecursiveListener(myChangeListener, workDir);

    assertEquals("files before", 0, workDir.list().length);

    for (int i = 0; i < RUNS; ++i) {
        final int j = i;
        myAtomicAction.runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    FileUtil.createData(workDirFo, FILE_PREFIX + j);
                } catch (IOException ex) {
                    // checked later
                }
            }
        };
        FileUtil.runAtomicAction(myAtomicAction);
    }

    assertEquals("files after", RUNS, workDir.list().length);
    assertEquals(printEvents(myChangeListener.notFromAtomicAction), 0, myChangeListener.notFromAtomicAction.size());
    assertEquals("events", RUNS, myChangeListener.events.get());
}
 
Example 7
Source File: LibrariesTestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void registerLibraryTypeProvider (final Class<? extends LibraryTypeProvider> provider) throws Exception {
    final MockLibraryTypeRegistry mr = Lookup.getDefault().lookup(MockLibraryTypeRegistry.class);
    if (mr != null) {
        mr.register(provider.newInstance());
        return;
    }
    FileObject root = FileUtil.getConfigRoot();
    StringTokenizer tk = new StringTokenizer("org-netbeans-api-project-libraries/LibraryTypeProviders","/");
    while (tk.hasMoreElements()) {
        String pathElement = tk.nextToken();
        FileObject tmp = root.getFileObject(pathElement);
        if (tmp == null) {
            tmp = root.createFolder(pathElement);
        }
        root = tmp;
    }
    final FileObject rootFin = root;
    if (root.getChildren().length == 0) {
        FileUtil.runAtomicAction(new FileSystem.AtomicAction() {
            @Override
            public void run() throws IOException {
                FileObject inst = rootFin.createData("TestLibraryTypeProvider","instance");
                inst.setAttribute("instanceClass", getBinaryName(provider));
            }
        });
    }
}
 
Example 8
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails
public void testBinaryDeletedAdded() throws Exception {
    final TestHandler handler = new TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);

    final FileObject wd = FileUtil.toFileObject(getWorkDir());
    final FileObject[] jar2Delete = new FileObject[] {jarFile.copy(wd, "test", "jar")};
    ClassPath cp = ClassPathSupport.createClassPath(new FileObject[] {FileUtil.getArchiveRoot(jar2Delete[0])});

    globalPathRegistry_register(PLATFORM,new ClassPath[] {cp});
    assertTrue(handler.await());
    assertEquals(1, handler.getBinaries().size());

    handler.reset(TestHandler.Type.BINARY);

    final long timeStamp = jar2Delete[0].lastModified().getTime();

    jar2Delete[0].delete();
    handler.await();

    binIndexerFactory.indexer.indexedAllFilesIndexing.clear();
    handler.reset(TestHandler.Type.BINARY);
    FileUtil.runAtomicAction(new Runnable(){
        @Override
        public void run() {
            try {
                jar2Delete[0] = jarFile.copy(wd, "test", "jar");
                FileUtil.toFile(jar2Delete[0]).setLastModified(timeStamp);
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    });
    assertTrue(handler.await());
    assertTrue(binIndexerFactory.indexer.indexedAllFilesIndexing.toString(), binIndexerFactory.indexer.indexedAllFilesIndexing.contains(FileUtil.getArchiveRoot(jar2Delete[0]).toURL()));

}
 
Example 9
Source File: Helper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static File getBookFile(File dataDir, File workDir) throws IOException {
    final File source = new File(dataDir, "sample.book");
    final File target = new File(workDir, "sample.book");
    if (target.exists()) {
        return target;
    }
    FileUtil.runAtomicAction(new FileSystem.AtomicAction() {

        @Override
        public void run() throws IOException {
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(source));
            try {
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(target));
                try {
                    FileUtil.copy(is, os);
                } finally {
                    os.close();
                }
            } finally {
                is.close();
            }
        }
    });

    FileUtil.refreshFor(target);
    return target;
}
 
Example 10
Source File: DnDSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Perform the drop operation.
 *
 * @return True if the drop has been successful.
 */
private boolean handleDrop( final Transferable t ) {
    final boolean[] res = { false };
    FileUtil.runAtomicAction(new Runnable() {
        @Override
        public void run() {
            res[0] = handleDropImpl(t);
        }
    });
    return res[0];
}
 
Example 11
Source File: FsEventFromAtomicActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFiredFromOneAtomicAction() throws Exception {
    final File workDir = getWorkDir();
    final FileObject workDirFo = FileUtil.toFileObject(workDir);

    final AtomicAction myAtomicAction = new AtomicAction() {
        @Override
        public void run() throws IOException {
            try {
                for (int i = 0; i < RUNS; ++i) {
                    FileUtil.createData(workDirFo, FILE_PREFIX + i);
                }
            } catch (IOException ex) {
                // checked later
            }
        }
    };
    MyFileChangeListener myChangeListener = new MyFileChangeListener(myAtomicAction);
    FileUtil.addRecursiveListener(myChangeListener, workDir);

    assertEquals("files before", 0, workDir.list().length);

    FileUtil.runAtomicAction(myAtomicAction);

    assertEquals("files after", RUNS, workDir.list().length);
    assertEquals(printEvents(myChangeListener.notFromAtomicAction), 0, myChangeListener.notFromAtomicAction.size());
    assertEquals("events", RUNS, myChangeListener.events.get());
}
 
Example 12
Source File: IntroduceSuggestion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void implement() throws Exception {
    final DataFolder dataFolder = DataFolder.findFolder(folder);
    final DataObject configDataObject = DataObject.find(template);
    final FileObject[] clsFo = new FileObject[1];
    FileUtil.runAtomicAction(new Runnable() {

        @Override
        public void run() {
            try {
                Map<String, String> parameters = new HashMap<>();
                if (StringUtils.hasText(nsPart)) {
                    parameters.put(NAMESPACE_PARAMETER_NAME, nsPart); //NOI18N
                }
                DataObject clsDataObject = configDataObject.createFromTemplate(dataFolder, className, parameters);
                clsFo[0] = clsDataObject.getPrimaryFile();
                FileObject fo = clsFo[0];
                FileLock lock = fo.lock();
                try {
                    fo.rename(lock, fo.getName(), "php"); //NOI18N
                } finally {
                    lock.releaseLock();
                }
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    if (clsFo[0] != null) {
        UiUtils.open(clsFo[0], 0);
    }
}
 
Example 13
Source File: RefreshSlow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
boolean refreshFileObject(final BaseFileObj fo, final boolean expected, final int add) {
    final boolean[] b = { true };
    ActionEvent r = this.ref;
    final Runnable goingIdle = r instanceof Runnable ? (Runnable) r : null;
    Runnable refresh = new Runnable() {
        boolean second;
        @Override
        public void run() {
            if (second) {
                before();
                fo.refresh(expected);
                if (!after()) {
                    b[0] = false;
                    return;
                }
            } else {
                second = true;
                FileChangedManager.idleIO(50, this, goingIdle, RefreshSlow.this);
            }
        }
    };
    FileUtil.runAtomicAction(refresh);
    if (b[0]) {
        progress(add, fo);
    }
    return b[0];
}
 
Example 14
Source File: NbInstaller.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void unload(final List<Module> modules) {
    FileUtil.runAtomicAction(new Runnable() {
        @Override
        public void run() {
            unloadImpl(modules);
        }
    });
}
 
Example 15
Source File: EditorConfigProcessor.java    From editorconfig-netbeans with MIT License 5 votes vote down vote up
private void updateChangesInEditorWindow(final FileInfo info) {
  LOG.log(Level.INFO, "Update changes in Editor window for: {0}", info.getPath());

      try {
        FileUtil.runAtomicAction((AtomicAction) new WriteEditorAction(info));
      } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage());
      }
}
 
Example 16
Source File: ModuleClassPathsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static FileObject createModuleInfo(
        @NonNull final ClassPath src,
        @NonNull final String moduleName,
        @NonNull final String... requiredModules) throws IOException {
    final FileObject[] roots = src.getRoots();
    if (roots.length == 0) {
        throw new IOException("No source roots");   //NOI18N
    }
    final FileObject[] res = new FileObject[1];
    FileUtil.runAtomicAction((FileSystem.AtomicAction)() -> {
            res[0] = FileUtil.createData(roots[0], "module-info.java");    //NOI18N
            final StringBuilder module = new StringBuilder("module ").append(moduleName).append(" {");    //NOI18N
            for (String mod : requiredModules) {
                module.append("requires ").append(mod).append(";");
            }
            module.append("}"); //NOI18N
            final FileLock lck = res[0].lock();
            try (OutputStream out = res[0].getOutputStream(lck);
                    InputStream in = new ByteArrayInputStream(module.toString().getBytes(FileEncodingQuery.getEncoding(res[0])))) {
                FileUtil.copy(in, out);
            } finally {
                lck.releaseLock();
            }
    });
    return res[0];
}
 
Example 17
Source File: TestUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static FileObject createFO(final String path, final boolean folder, final String contents, long delay) throws IOException {
    final FileObject [] createdFo = new FileObject[1];
    FileUtil.runAtomicAction(new FileSystem.AtomicAction() {
        public void run() throws IOException {
            FileObject fo = FileUtil.getConfigRoot();
            String [] pathElements = path.split("/", -1);
            for (int i = 0; i < pathElements.length; i++ ) {
                String elementName = pathElements[i];

                if (elementName.length() == 0) {
                    continue;
                }

                FileObject f = fo.getFileObject(elementName);
                if (f != null && f.isValid()) {
                    fo = f;
                } else {
                    if (i + 1 < pathElements.length || folder) {
                        fo = fo.createFolder(elementName);
                    } else {
                        // The last element in the path should be a file
                        fo = fo.createData(elementName);
                        if (contents != null) {
                            OutputStream os = fo.getOutputStream();
                            try {
                                os.write(contents.getBytes());
                            } finally {
                                os.close();
                            }
                        }
                    }
                }
            }
            createdFo[0] = fo;
        }
    });
    
    if (delay > 0) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {
            // ignore
        }
    }
    
    return createdFo[0];
}
 
Example 18
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 19
Source File: TestUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static FileObject createFO(final String path, final boolean folder, final String contents, long delay) throws IOException {
    final FileObject [] createdFo = new FileObject[1];
    FileUtil.runAtomicAction(new FileSystem.AtomicAction() {
        public void run() throws IOException {
            FileObject fo = FileUtil.getConfigRoot();
            String [] pathElements = path.split("/", -1);
            for (int i = 0; i < pathElements.length; i++ ) {
                String elementName = pathElements[i];

                if (elementName.length() == 0) {
                    continue;
                }

                FileObject f = fo.getFileObject(elementName);
                if (f != null && f.isValid()) {
                    fo = f;
                } else {
                    if (i + 1 < pathElements.length || folder) {
                        fo = fo.createFolder(elementName);
                    } else {
                        // The last element in the path should be a file
                        fo = fo.createData(elementName);
                        if (contents != null) {
                            OutputStream os = fo.getOutputStream();
                            try {
                                os.write(contents.getBytes());
                            } finally {
                                os.close();
                            }
                        }
                    }
                }
            }
            createdFo[0] = fo;
        }
    });
    
    if (delay > 0) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ie) {
            // ignore
        }
    }
    
    return createdFo[0];
}
 
Example 20
Source File: ConfigurationImplTest.java    From netbeans with Apache License 2.0 2 votes vote down vote up
private void doTestConfigurationChanges(String jdkProjectDir) throws Exception {
    clearWorkDir();

    ((TestLookup) Lookup.getDefault()).setLookupsImpl(Lookups.metaInfServices(ConfigurationImplTest.class.getClassLoader()));

    File jdkRoot = getWorkDir();
    final File buildDir = new File(jdkRoot, "build");
    FileObject jdkRootFO = FileUtil.toFileObject(jdkRoot);
    FileObject jdkProject = FileUtil.createFolder(jdkRootFO, jdkProjectDir);

    dir2Project.put(jdkProject, new TestProject(jdkProject));

    try {
        ProviderImpl provider = new ProviderImpl(jdkRootFO, buildDir);

        assertConfigurations(provider, null);

        FileObject buildDirFO = FileUtil.createFolder(buildDir);
        FileObject conf1 = FileUtil.createData(buildDirFO, "conf1/Makefile").getParent();

        assertConfigurations(provider, "conf1", "conf1");

        FileObject conf0 = FileUtil.createData(buildDirFO, "conf0/Makefile").getParent();

        assertConfigurations(provider, "conf1", "conf0", "conf1");

        conf0.delete();

        assertConfigurations(provider, "conf1", "conf1");

        conf0 = FileUtil.createData(buildDirFO, "conf0/Makefile").getParent();

        assertConfigurations(provider, "conf1", "conf0", "conf1");

        conf1.delete();

        assertConfigurations(provider, "conf1", "conf0", "conf1");

        provider = new ProviderImpl(jdkRootFO, buildDir);

        assertConfigurations(provider, "conf1", "conf0", "conf1");

        buildDirFO.delete();

        //verify no listeners inside build directory:
        Class<?> fileChangeImpl = Class.forName("org.openide.filesystems.FileChangeImpl");
        Field holders = fileChangeImpl.getDeclaredField("holders");
        holders.setAccessible(true);
        Map listeningOn = (Map) ((Map) holders.get(null)).get(provider);
        assertTrue(listeningOn.toString(), listeningOn.size() == 1 && listeningOn.containsKey(buildDir));

        //create one-by-one:
        buildDirFO = FileUtil.createFolder(buildDir);

        FileObject conf2 = FileUtil.createFolder(buildDirFO, "conf2");

        assertConfigurations(provider, "conf1", "conf1");

        FileUtil.createData(conf2, "Makefile");

        assertConfigurations(provider, "conf1", "conf1", "conf2");
        
        buildDirFO.delete();

        //attempt to create all at once:
        FileUtil.runAtomicAction(new AtomicAction() {
            @Override
            public void run() throws IOException {
                File conf3 = new File(new File(buildDir, "conf3"), "Makefile");

                FileUtil.createData(conf3);
            }
        });

        assertConfigurations(provider, "conf1", "conf1", "conf3");
    } finally {
        dir2Project.remove(jdkProject);
    }
}