NbTestCase: use Files#delete for better exception on failure,
- "Cannot delete file" isn't very useful, Files#delete will state
the cause if available
- might help to debug some sporadic test failures
- global refactoring to replace similar patterns resulted in some
TestUtil/TestFileUtils cleanup which was duplicated everywhere
diff --git a/apisupport/apisupport.ant/test/unit/src/org/netbeans/modules/apisupport/project/TestBase.java b/apisupport/apisupport.ant/test/unit/src/org/netbeans/modules/apisupport/project/TestBase.java
index 9c7da76..9b79efa 100644
--- a/apisupport/apisupport.ant/test/unit/src/org/netbeans/modules/apisupport/project/TestBase.java
+++ b/apisupport/apisupport.ant/test/unit/src/org/netbeans/modules/apisupport/project/TestBase.java
@@ -437,7 +437,7 @@
@Deprecated
public static void delete(File f) throws IOException {
- TestUtil.delete(f);
+ TestFileUtils.deleteFile(f);
}
private static File getTestNBRoot() {
diff --git a/apisupport/apisupport.project/test/unit/src/org/netbeans/modules/apisupport/project/TestUtil.java b/apisupport/apisupport.project/test/unit/src/org/netbeans/modules/apisupport/project/TestUtil.java
index e5c3e9a..4ace410 100644
--- a/apisupport/apisupport.project/test/unit/src/org/netbeans/modules/apisupport/project/TestUtil.java
+++ b/apisupport/apisupport.project/test/unit/src/org/netbeans/modules/apisupport/project/TestUtil.java
@@ -112,18 +112,6 @@
}
}
- public static void delete(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- for (int i = 0; i < kids.length; i++) {
- delete(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Could not delete " + f);
- }
- }
-
/** @deprecated Use {@link TestFileUtils#writeFile} instead. */
@Deprecated
public static void dump(FileObject f, String contents) throws IOException {
diff --git a/enterprise/j2ee.clientproject/test/unit/src/org/netbeans/modules/j2ee/clientproject/test/TestUtil.java b/enterprise/j2ee.clientproject/test/unit/src/org/netbeans/modules/j2ee/clientproject/test/TestUtil.java
index 2f8bb8d..f635f14 100644
--- a/enterprise/j2ee.clientproject/test/unit/src/org/netbeans/modules/j2ee/clientproject/test/TestUtil.java
+++ b/enterprise/j2ee.clientproject/test/unit/src/org/netbeans/modules/j2ee/clientproject/test/TestUtil.java
@@ -42,6 +42,7 @@
import org.openide.filesystems.Repository;
import org.openide.filesystems.URLMapper;
import org.openide.util.Lookup;
+import org.openide.util.test.TestFileUtils;
/**
* Help set up org.netbeans.api.project.*Test.
@@ -96,18 +97,7 @@
* Delete a file and all subfiles.
*/
public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
+ TestFileUtils.deleteFile(f);
}
/**
diff --git a/enterprise/j2ee.earproject/test/unit/src/org/netbeans/modules/j2ee/earproject/test/TestUtil.java b/enterprise/j2ee.earproject/test/unit/src/org/netbeans/modules/j2ee/earproject/test/TestUtil.java
index ec39caf..4da83a1 100644
--- a/enterprise/j2ee.earproject/test/unit/src/org/netbeans/modules/j2ee/earproject/test/TestUtil.java
+++ b/enterprise/j2ee.earproject/test/unit/src/org/netbeans/modules/j2ee/earproject/test/TestUtil.java
@@ -48,6 +48,7 @@
import org.openide.filesystems.URLMapper;
import org.openide.util.Lookup;
import org.openide.util.test.MockLookup;
+import org.openide.util.test.TestFileUtils;
/**
* Help set up org.netbeans.api.project.*Test.
@@ -168,18 +169,7 @@
* Delete a file and all subfiles.
*/
public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
+ TestFileUtils.deleteFile(f);
}
/**
diff --git a/enterprise/j2ee.ejbjarproject/test/unit/src/org/netbeans/modules/j2ee/ejbjarproject/test/TestUtil.java b/enterprise/j2ee.ejbjarproject/test/unit/src/org/netbeans/modules/j2ee/ejbjarproject/test/TestUtil.java
index 41f2d01..d084404 100644
--- a/enterprise/j2ee.ejbjarproject/test/unit/src/org/netbeans/modules/j2ee/ejbjarproject/test/TestUtil.java
+++ b/enterprise/j2ee.ejbjarproject/test/unit/src/org/netbeans/modules/j2ee/ejbjarproject/test/TestUtil.java
@@ -27,6 +27,7 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
+import java.nio.file.Files;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
@@ -43,6 +44,7 @@
import org.openide.filesystems.URLMapper;
import org.openide.util.Lookup;
import org.openide.util.lookup.ProxyLookup;
+import org.openide.util.test.TestFileUtils;
/**
* Help set up org.netbeans.api.project.*Test.
@@ -92,18 +94,7 @@
* Delete a file and all subfiles.
*/
public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
+ TestFileUtils.deleteFile(f);
}
/**
diff --git a/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/WebInjectionTargetQueryImplementationTest.java b/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/WebInjectionTargetQueryImplementationTest.java
index 4396d59..a51c0d3 100644
--- a/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/WebInjectionTargetQueryImplementationTest.java
+++ b/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/WebInjectionTargetQueryImplementationTest.java
@@ -19,7 +19,6 @@
package org.netbeans.modules.web.core;
-import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -32,18 +31,10 @@
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.modules.j2ee.metadata.model.support.JavaSourceTestCase;
import org.netbeans.modules.j2ee.metadata.model.support.TestUtilities;
-import org.netbeans.modules.j2ee.core.api.support.java.SourceUtils;
import static org.netbeans.api.java.source.JavaSource.Phase;
import org.netbeans.modules.parsing.api.indexing.IndexingManager;
-
-
import org.openide.filesystems.FileObject;
-import org.openide.filesystems.FileUtil;
-
-import org.netbeans.junit.NbTestCase;
-
-import org.netbeans.modules.web.core.test.TestUtil;
/**
*
@@ -52,7 +43,6 @@
*/
public class WebInjectionTargetQueryImplementationTest extends JavaSourceTestCase {
- private String serverID;
private FileObject ordinaryClass;
private FileObject fileSubclass;
private FileObject directServletSubclass;
@@ -144,8 +134,8 @@
}
+ @Override
protected void tearDown() {
- serverID = null;
ordinaryClass = null;
fileSubclass = null;
directServletSubclass = null;
diff --git a/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/test/TestUtil.java b/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/test/TestUtil.java
deleted file mode 100644
index e9347cd..0000000
--- a/enterprise/web.core/test/unit/src/org/netbeans/modules/web/core/test/TestUtil.java
+++ /dev/null
@@ -1,569 +0,0 @@
-package org.netbeans.modules.web.core.test;
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-import java.beans.PropertyVetoException;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.WeakHashMap;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import org.junit.Assert;
-import org.netbeans.api.project.Project;
-import org.netbeans.api.project.ProjectManagerTest;
-import org.netbeans.junit.NbTestCase;
-import org.netbeans.modules.j2ee.deployment.impl.ServerRegistry;
-import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
-import org.netbeans.spi.project.ProjectFactory;
-import org.netbeans.spi.project.ProjectState;
-import org.netbeans.spi.project.support.ant.AntProjectHelper;
-import org.netbeans.spi.project.support.ant.EditableProperties;
-import org.openide.filesystems.FileLock;
-import org.openide.filesystems.FileObject;
-import org.openide.filesystems.FileSystem;
-import org.openide.filesystems.FileUtil;
-import org.openide.filesystems.LocalFileSystem;
-import org.openide.filesystems.MultiFileSystem;
-import org.openide.filesystems.Repository;
-import org.openide.filesystems.URLMapper;
-import org.openide.filesystems.XMLFileSystem;
-import org.openide.modules.InstalledFileLocator;
-import org.openide.util.Lookup;
-import org.openide.util.lookup.Lookups;
-import org.openide.util.lookup.ProxyLookup;
-import org.xml.sax.SAXException;
-
-
-/**
- * Help set up org.netbeans.api.project.*Test.
- * @author Jesse Glick
- */
-public final class TestUtil extends ProxyLookup {
-
- static {
- TestUtil.class.getClassLoader().setDefaultAssertionStatus(true);
- System.setProperty("org.openide.util.Lookup", TestUtil.class.getName());
- Assert.assertEquals(TestUtil.class, Lookup.getDefault().getClass());
- }
-
- private static TestUtil DEFAULT;
- private static final int BUFFER = 2048;
-
- /** Do not call directly */
- public TestUtil() {
- Assert.assertNull(DEFAULT);
- DEFAULT = this;
- setLookup(new Object[0]);
- }
-
- /**
- * Set the global default lookup.
- * Caution: if you don't include Lookups.metaInfServices, you may have trouble,
- * e.g. {@link #makeScratchDir} will not work.
- */
- public static void setLookup(Lookup l) {
- DEFAULT.setLookups(new Lookup[] {l});
- }
-
- /**
- * Set the global default lookup with some fixed instances including META-INF/services/*.
- */
- public static void setLookup(Object[] instances) {
- ClassLoader l = TestUtil.class.getClassLoader();
- DEFAULT.setLookups(new Lookup[] {
- Lookups.fixed(instances),
- Lookups.metaInfServices(l),
- Lookups.singleton(l),
- });
- }
-
- private static boolean warned = false;
- /**
- * Create a scratch directory for tests.
- * Will be in /tmp or whatever, and will be empty.
- * If you just need a java.io.File use clearWorkDir + getWorkDir.
- */
- public static FileObject makeScratchDir(NbTestCase test) throws IOException {
- test.clearWorkDir();
- File root = test.getWorkDir();
- assert root.isDirectory() && root.list().length == 0;
- FileObject fo = FileUtil.toFileObject(root);
- if (fo != null) {
- return fo;
- } else {
- if (!warned) {
- warned = true;
- System.err.println("No FileObject for " + root + " found.\n" +
- "Maybe you need ${openide/masterfs.dir}/modules/org-netbeans-modules-masterfs.jar\n" +
- "in test.unit.run.cp.extra, or make sure Lookups.metaInfServices is included in Lookup.default, so that\n" +
- "Lookup.default<URLMapper>=" + Lookup.getDefault().lookup(new Lookup.Template(URLMapper.class)).allInstances() + " includes MasterURLMapper\n" +
- "e.g. by using TestUtil.setLookup(Object[]) rather than TestUtil.setLookup(Lookup).");
- }
- // For the benefit of those not using masterfs.
- LocalFileSystem lfs = new LocalFileSystem();
- try {
- lfs.setRootDirectory(root);
- } catch (PropertyVetoException e) {
- assert false : e;
- }
- Repository.getDefault().addFileSystem(lfs);
- return lfs.getRoot();
- }
- }
-
- /**
- * Delete a file and all subfiles.
- */
- public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
- }
-
- /**
- * Create a testing project factory which recognizes directories containing
- * a subdirectory called "testproject".
- * If that subdirectory contains a file named "broken" then loading the project
- * will fail with an IOException.
- */
- public static ProjectFactory testProjectFactory() {
- return new TestProjectFactory();
- }
-
- /**
- * Try to force a GC.
- */
- public static void gc() {
- System.gc();
- System.runFinalization();
- System.gc();
- }
-
- private static final Map<FileObject,Integer> loadCount = new WeakHashMap<>();
-
- /**
- * Check how many times {@link ProjectFactory#loadProject} has been called
- * (with any outcome) on a given project directory.
- */
- public static int projectLoadCount(FileObject dir) {
- Integer i = loadCount.get(dir);
- if (i != null) {
- return i;
- } else {
- return 0;
- }
- }
-
- /**
- * Mark a test project to fail with a given error when it is next saved.
- * The error only applies to the next save, not subsequent ones.
- * @param p a test project
- * @param error an error to throw (IOException or Error or RuntimeException),
- * or null if it should succeed
- */
- public static void setProjectSaveWillFail(Project p, Throwable error) {
- ((TestProject)p).error = error;
- }
-
- /**
- * Get the number of times a test project was successfully saved with no error.
- * @param p a test project
- * @return the save count
- */
- public static int projectSaveCount(Project p) {
- return ((TestProject)p).saveCount;
- }
-
- /**
- * Mark a test project as modified.
- * @param p a test project
- */
- public static void modify(Project p) {
- ((TestProject)p).state.markModified();
- }
-
- /**
- * Mark a test project as modified.
- * @param p a test project
- */
- public static void notifyDeleted(Project p) {
- ((TestProject)p).state.notifyDeleted();
- }
-
- /**
- * Register Sun Application Server in the "IDE" to be used by unit test.
- * This method creates dummy userdir as well as dummy NetBeans home
- * in test's working directory. Both properties - <code>netbeans.home</code>
- * and <code>netbeans.user</code> - will be set by this method if they are
- * not already defined.
- *
- * @param test a test which requires SunAppServer
- * @return id of registered server
- */
- public static String registerSunAppServer(NbTestCase test) throws Exception {
- return registerSunAppServer(test, new Object[0]);
-}
-
- public static String registerSunAppServer(NbTestCase test, Object[] additionalLookupItems) throws Exception {
- String oldNbHome = System.getProperty("netbeans.home"); // NOI18N
- String oldNbUser = System.getProperty("netbeans.user"); // NOI18N
- File root = test.getWorkDir();
- File systemDir = new File(root, "ud/system"); // NOI18N
- new File(systemDir, "J2EE/InstalledServers").mkdirs(); // NOI18N
- new File(systemDir, "J2EE/DeploymentPlugins").mkdirs(); // NOI18N
- new File(root, "nb").mkdirs(); // NOI18N
- System.setProperty("netbeans.home", new File(test.getWorkDir(), "nb").getAbsolutePath()); // NOI18N
- System.setProperty("netbeans.user", new File(test.getWorkDir(), "ud").getAbsolutePath()); // NOI18N
-
- // lookup content
- Object[] appServerNeed = new Object[] { new Repo(test), new IFL() };
- Object[] instances = new Object[additionalLookupItems.length + appServerNeed.length];
- System.arraycopy(additionalLookupItems, 0, instances, 0, additionalLookupItems.length);
- System.arraycopy(appServerNeed, 0, instances, additionalLookupItems.length, appServerNeed.length);
- TestUtil.setLookup(instances);
-
- File asRoot = null;
- if (System.getProperty("appserv.home") != null) { // NOI18N
- asRoot = new File(System.getProperty("appserv.home")); // NOI18N
- } else {
- asRoot = extractAppSrv(test.getWorkDir(), new File(test.getDataDir(), "SunAppServer.zip")); // NOI18N
- }
- FileObject dir = FileUtil.getConfigFile("J2EE/InstalledServers"); // NOI18N
- String name = FileUtil.findFreeFileName(dir, "instance", null); // NOI18N
- FileObject instanceFO = dir.createData(name);
- String serverID = "[" + asRoot.getAbsolutePath() + "]deployer:Sun:AppServer::localhost:4848"; // NOI18N
- instanceFO.setAttribute(InstanceProperties.URL_ATTR, serverID);
- instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, "admin"); // NOI18N
- instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, "adminadmin"); // NOI18N
- instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, "testdname"); // NOI18N
- instanceFO.setAttribute(InstanceProperties.HTTP_PORT_NUMBER, "4848"); // NOI18N
- instanceFO.setAttribute("DOMAIN", "testdomain1"); // NOI18N
- instanceFO.setAttribute("LOCATION", new File(asRoot, "domains").getAbsolutePath()); // NOI18N
- ServerRegistry sr = ServerRegistry.getInstance();
- sr.addInstance(instanceFO);
- if (oldNbHome != null) {
- System.setProperty("netbeans.home", oldNbHome); // NOI18N
- }
- if (oldNbUser != null) {
- System.setProperty("netbeans.user", oldNbUser); // NOI18N
- }
- return serverID;
- }
-
- private static File extractAppSrv(File destDir, File archiveFile) throws IOException {
- ZipInputStream zis = null;
- BufferedOutputStream dest = null;
- try {
- FileInputStream fis = new FileInputStream(archiveFile);
- zis = new ZipInputStream(new BufferedInputStream(fis));
- ZipEntry entry;
- while((entry = zis.getNextEntry()) != null) {
- byte data[] = new byte[BUFFER];
- File entryFile = new File(destDir, entry.getName());
- if (entry.isDirectory()) {
- entryFile.mkdirs();
- } else {
- entryFile.getParentFile().mkdirs();
- FileOutputStream fos = new FileOutputStream(entryFile);
- dest = new BufferedOutputStream(fos, BUFFER);
- int count;
- while ((count = zis.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, count);
- }
- dest.flush();
- }
- }
- } finally {
- if (zis != null) { zis.close(); }
- if (dest != null) { dest.close(); }
- }
- return new File(destDir, archiveFile.getName().substring(0, archiveFile.getName().length() - 4));
- }
-
- public static EditableProperties loadProjectProperties(
- final FileObject projectDir) throws IOException {
- FileObject propsFO = projectDir.getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
- InputStream propsIS = propsFO.getInputStream();
- EditableProperties props = new EditableProperties(true);
- try {
- props.load(propsIS);
- } finally {
- propsIS.close();
- }
- return props;
- }
-
- public static void storeProjectProperties(FileObject projectDir, EditableProperties props) throws IOException {
- FileObject propsFO = projectDir.getFileObject(AntProjectHelper.PROJECT_PROPERTIES_PATH);
- FileLock lock = propsFO.lock();
- try {
- OutputStream os = propsFO.getOutputStream(lock);
- try {
- props.store(os);
- } finally {
- os.close();
- }
- } finally {
- lock.releaseLock();
- }
- }
-
- /**
- * If set to something non-null, loading a broken project will wait for
- * notification on this monitor before throwing an exception.
- * @see ProjectManagerTest#testLoadExceptionWithConcurrentLoad
- */
- public static Object BROKEN_PROJECT_LOAD_LOCK = null;
-
- private static final class TestProjectFactory implements ProjectFactory {
-
- TestProjectFactory() {}
-
- public Project loadProject(FileObject projectDirectory, ProjectState state) throws IOException {
- Integer i = loadCount.get(projectDirectory);
- if (i == null) {
- i = 1;
- } else {
- i++;
- }
- loadCount.put(projectDirectory, i);
- FileObject testproject = projectDirectory.getFileObject("testproject");
- if (testproject != null && testproject.isFolder()) {
- if (testproject.getFileObject("broken") != null) {
- if (BROKEN_PROJECT_LOAD_LOCK != null) {
- synchronized (BROKEN_PROJECT_LOAD_LOCK) {
- try {
- BROKEN_PROJECT_LOAD_LOCK.wait();
- } catch (InterruptedException e) {
- assert false : e;
- }
- }
- }
- throw new IOException("Load failed of " + projectDirectory);
- } else {
- return new TestProject(projectDirectory, state);
- }
- } else {
- return null;
- }
- }
-
- public void saveProject(Project project) throws IOException, ClassCastException {
- TestProject p = (TestProject)project;
- Throwable t = p.error;
- if (t != null) {
- p.error = null;
- if (t instanceof IOException) {
- throw (IOException)t;
- } else if (t instanceof Error) {
- throw (Error)t;
- } else {
- throw (RuntimeException)t;
- }
- }
- p.saveCount++;
- }
-
- public boolean isProject(FileObject dir) {
- FileObject testproject = dir.getFileObject("testproject");
- return testproject != null && testproject.isFolder();
- }
-
- }
-
- private static final class TestProject implements Project {
-
- private final FileObject dir;
- final ProjectState state;
- Throwable error;
- int saveCount = 0;
-
- public TestProject(FileObject dir, ProjectState state) {
- this.dir = dir;
- this.state = state;
- }
-
- public Lookup getLookup() {
- return Lookup.EMPTY;
- }
-
- public FileObject getProjectDirectory() {
- return dir;
- }
-
- public String toString() {
- return "testproject:" + getProjectDirectory().getNameExt();
- }
-
- /* Probably unnecessary to have a ProjectInformation here:
- public String getName() {
- return "testproject:" + getProjectDirectory().getNameExt();
- }
-
- public String getDisplayName() {
- return "Test Project in " + getProjectDirectory().getNameExt();
- }
-
- public Image getIcon() {
- return null;
- }
-
- public void addPropertyChangeListener(PropertyChangeListener listener) {}
- public void removePropertyChangeListener(PropertyChangeListener listener) {}
- */
-
- }
-
- /**
- * Open a URL of content (for example from {@link Class#getResource}) and copy it to a named file.
- * The new file can be given as a parent directory plus a relative (slash-separated) path.
- * The file may not already exist, but intermediate directories may or may not.
- * If the content URL is null, the file is just created, no more; if it already existed
- * it is touched (timestamp updated) and its contents are cleared.
- * @return the file object
- */
- public static FileObject createFileFromContent(URL content, FileObject parent, String path) throws IOException {
- if (parent == null) {
- throw new IllegalArgumentException("null parent");
- }
- Assert.assertTrue("folder", parent.isFolder());
- FileObject fo = parent;
- StringTokenizer tok = new StringTokenizer(path, "/");
- boolean touch = false;
- while (tok.hasMoreTokens()) {
- Assert.assertNotNull("fo is null (parent=" + parent + " path=" + path + ")", fo);
- String name = tok.nextToken();
- if (tok.hasMoreTokens()) {
- FileObject sub = fo.getFileObject(name);
- if (sub == null) {
- FileObject fo2 = fo.createFolder(name);
- Assert.assertNotNull("createFolder(" + fo + ", " + name + ") -> null", fo2);
- fo = fo2;
- } else {
- Assert.assertTrue("folder", sub.isFolder());
- fo = sub;
- }
- } else {
- FileObject sub = fo.getFileObject(name);
- if (sub == null) {
- FileObject fo2 = fo.createData(name);
- Assert.assertNotNull("createData(" + fo + ", " + name + ") -> null", fo2);
- fo = fo2;
- } else {
- fo = sub;
- touch = true;
- }
- }
- }
- assert fo.isData();
- if (content != null || touch) {
- FileLock lock = fo.lock();
- try {
- OutputStream os = fo.getOutputStream(lock);
- try {
- if (content != null) {
- InputStream is = content.openStream();
- try {
- FileUtil.copy(is, os);
- } finally {
- is.close();
- }
- }
- } finally {
- os.close();
- }
- } finally {
- lock.releaseLock();
- }
- }
- return fo;
- }
-
- private static final class Repo extends Repository {
-
- public Repo(NbTestCase t) throws Exception {
- super(mksystem(t));
- }
-
- private static FileSystem mksystem(NbTestCase t) throws Exception {
- LocalFileSystem lfs = new LocalFileSystem();
- File systemDir = new File(t.getWorkDir(), "ud/system");
- systemDir.mkdirs();
- lfs.setRootDirectory(systemDir);
- lfs.setReadOnly(false);
- List<FileSystem> layers = new ArrayList<FileSystem>();
- layers.add(lfs);
- /*
- //get layer for the generic server
- java.net.URL layerFile = Repo.class.getClassLoader().getResource("org/netbeans/modules/j2ee/genericserver/resources/layer.xml");
- assert layerFile != null;
- layers.add(new XMLFileSystem(layerFile));
- */
-
- // get layer for the AS/GlassFish
-// addLayer(layers, "org/netbeans/modules/j2ee/sun/ide/j2ee/layer.xml");
-// addLayer(layers, "org/netbeans/modules/tomcat5/resources/layer.xml");
- MultiFileSystem mfs = new MultiFileSystem((FileSystem[]) layers.toArray(new FileSystem[0]));
- return mfs;
- }
-
- private static void addLayer(List<FileSystem> layers, String layerRes) throws SAXException {
- URL layerFile = Repo.class.getClassLoader().getResource(layerRes);
- assert layerFile != null;
- layers.add(new XMLFileSystem(layerFile));
- }
-
- }
-
- /** Copied from AntLoggerTest. */
- private static final class IFL extends InstalledFileLocator {
-
- public IFL() {}
-
- public File locate(String relativePath, String codeNameBase, boolean localized) {
- if (relativePath.equals("modules/ext/appsrvbridge.jar")) {
- String path = System.getProperty("test.appsrvbridge.jar");
- Assert.assertNotNull("must set test.appsrvbridge.jar", path);
- return new File(path);
- }
- return null;
- }
- }
-
-}
diff --git a/enterprise/web.project/test/unit/src/org/netbeans/modules/web/project/test/TestUtil.java b/enterprise/web.project/test/unit/src/org/netbeans/modules/web/project/test/TestUtil.java
index ffb08e3..0da6c32 100644
--- a/enterprise/web.project/test/unit/src/org/netbeans/modules/web/project/test/TestUtil.java
+++ b/enterprise/web.project/test/unit/src/org/netbeans/modules/web/project/test/TestUtil.java
@@ -64,6 +64,7 @@
import org.openide.util.lookup.ProxyLookup;
import org.openide.util.lookup.ServiceProvider;
import org.openide.util.test.MockLookup;
+import org.openide.util.test.TestFileUtils;
import org.xml.sax.SAXException;
/**
@@ -119,18 +120,7 @@
* Delete a file and all subfiles.
*/
public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
+ TestFileUtils.deleteFile(f);
}
/**
diff --git a/harness/nbjunit/src/org/netbeans/junit/NbTestCase.java b/harness/nbjunit/src/org/netbeans/junit/NbTestCase.java
index ee467fc..2d9f960 100644
--- a/harness/nbjunit/src/org/netbeans/junit/NbTestCase.java
+++ b/harness/nbjunit/src/org/netbeans/junit/NbTestCase.java
@@ -41,6 +41,10 @@
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -991,20 +995,18 @@
// private method for deleting a file/directory (and all its subdirectories/files)
private static void deleteFile(File file) throws IOException {
- if (file.isDirectory() && file.equals(file.getCanonicalFile())) {
- // file is a directory - delete sub files first
- File files[] = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteFile(files[i]);
+ Files.walkFileTree(file.toPath(), new SimpleFileVisitor<java.nio.file.Path>() {
+ @Override
+ public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
}
-
- }
- // file is a File :-)
- boolean result = file.delete();
- if (result == false ) {
- // a problem has appeared
- throw new IOException("Cannot delete file, file = "+file.getPath());
- }
+ @Override
+ public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException {
+ Files.delete(dir);
+ return FileVisitResult.CONTINUE;
+ }
+ });
}
// private method for deleting every subfiles/subdirectories of a file object
diff --git a/ide/o.n.swing.dirchooser/src/org/netbeans/swing/dirchooser/DirectoryChooserUI.java b/ide/o.n.swing.dirchooser/src/org/netbeans/swing/dirchooser/DirectoryChooserUI.java
index 0808766..deaf452 100644
--- a/ide/o.n.swing.dirchooser/src/org/netbeans/swing/dirchooser/DirectoryChooserUI.java
+++ b/ide/o.n.swing.dirchooser/src/org/netbeans/swing/dirchooser/DirectoryChooserUI.java
@@ -1049,9 +1049,7 @@
if (fo != null && file.equals(FileUtil.toFile(fo))) {
fo.delete();
} else {
- if (!file.delete()) {
- throw new IOException();
- }
+ Files.delete(file.toPath());
}
}
diff --git a/ide/projectapi/test/unit/src/org/netbeans/api/project/TestUtil.java b/ide/projectapi/test/unit/src/org/netbeans/api/project/TestUtil.java
index 45551ac..16caaf1 100644
--- a/ide/projectapi/test/unit/src/org/netbeans/api/project/TestUtil.java
+++ b/ide/projectapi/test/unit/src/org/netbeans/api/project/TestUtil.java
@@ -26,11 +26,11 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
+import java.nio.file.Files;
import java.util.Arrays;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
-import java.util.logging.Logger;
import javax.swing.Icon;
import org.junit.Assert;
import org.netbeans.junit.NbTestCase;
@@ -42,6 +42,7 @@
import org.openide.filesystems.URLMapper;
import org.openide.util.Lookup;
import org.openide.util.test.MockLookup;
+import org.openide.util.test.TestFileUtils;
/**
* Help set up org.netbeans.api.project.*Test.
@@ -77,18 +78,7 @@
* Delete a file and all subfiles.
*/
public static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) {
- throw new IOException("List " + f);
- }
- for (File kid : kids) {
- deleteRec(kid);
- }
- }
- if (!f.delete()) {
- throw new IOException("Delete " + f);
- }
+ TestFileUtils.deleteFile(f);
}
/**
diff --git a/ide/projectui/src/org/netbeans/modules/project/ui/zip/ExportZIP.java b/ide/projectui/src/org/netbeans/modules/project/ui/zip/ExportZIP.java
index 47a8410..fdb325c 100644
--- a/ide/projectui/src/org/netbeans/modules/project/ui/zip/ExportZIP.java
+++ b/ide/projectui/src/org/netbeans/modules/project/ui/zip/ExportZIP.java
@@ -31,6 +31,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -105,9 +106,7 @@
@Override public void run() {
try {
if (!build(root, zip)) {
- if (!zip.delete()) {
- throw new IOException("Cannot delete " + zip);
- }
+ Files.delete(zip.toPath());
return;
}
} catch (IOException x) {
diff --git a/platform/netbinox/test/unit/src/org/netbeans/SetupHid.java b/platform/netbinox/test/unit/src/org/netbeans/SetupHid.java
index 36e19a5..a7cbde6 100644
--- a/platform/netbinox/test/unit/src/org/netbeans/SetupHid.java
+++ b/platform/netbinox/test/unit/src/org/netbeans/SetupHid.java
@@ -79,17 +79,6 @@
return Level.FINE;
}
- protected static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) throw new IOException("Could not list: " + f);
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (! f.delete()) throw new IOException("Could not delete: " + f);
- }
-
/** same as FileUtil.copy */
protected static void copyStreams(InputStream is, OutputStream os) throws IOException {
final byte[] BUFFER = new byte[4096];
diff --git a/platform/o.n.bootstrap/test/unit/src/org/netbeans/SetupHid.java b/platform/o.n.bootstrap/test/unit/src/org/netbeans/SetupHid.java
index e5d19b8..71e296b 100644
--- a/platform/o.n.bootstrap/test/unit/src/org/netbeans/SetupHid.java
+++ b/platform/o.n.bootstrap/test/unit/src/org/netbeans/SetupHid.java
@@ -32,7 +32,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
-import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -46,6 +45,7 @@
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.netbeans.junit.NbTestCase;
+import org.openide.util.test.TestFileUtils;
/** Some infrastructure for module system tests.
* @author Jesse Glick
@@ -81,14 +81,7 @@
}
protected static void deleteRec(File f) throws IOException {
- if (f.isDirectory()) {
- File[] kids = f.listFiles();
- if (kids == null) throw new IOException("Could not list: " + f);
- for (int i = 0; i < kids.length; i++) {
- deleteRec(kids[i]);
- }
- }
- if (! f.delete()) throw new IOException("Could not delete: " + f);
+ TestFileUtils.deleteFile(f);
}
/** same as FileUtil.copy */
diff --git a/platform/openide.util.ui/test/unit/src/org/openide/util/test/TestFileUtils.java b/platform/openide.util.ui/test/unit/src/org/openide/util/test/TestFileUtils.java
index e007006..ea6a38e 100644
--- a/platform/openide.util.ui/test/unit/src/org/openide/util/test/TestFileUtils.java
+++ b/platform/openide.util.ui/test/unit/src/org/openide/util/test/TestFileUtils.java
@@ -19,16 +19,18 @@
package org.openide.util.test;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -48,52 +50,61 @@
private TestFileUtils() {}
/**
- * Create a new data file with specified initial contents.
+ * Create or overwrite a file with specified initial contents.
* @param f a file to create (parents will be created automatically)
* @param body the complete contents of the new file (in UTF-8 encoding)
*/
public static File writeFile(File f, String body) throws IOException {
f.getParentFile().mkdirs();
- OutputStream os = new FileOutputStream(f);
- PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
- pw.print(body);
- pw.flush();
- os.close();
+ Files.write(f.toPath(), body.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
+ // TODO jdk11
+// Files.writeString(f.toPath(), body, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
return f;
}
/**
* Read the contents of a file as a single string.
- * @param a data file
+ * @param file data file
* @return its contents (in UTF-8 encoding)
*/
public static String readFile(File file) throws IOException {
- InputStream is = new FileInputStream(file);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[4096];
- int read;
- while ((read = is.read(buf)) != -1) {
- baos.write(buf, 0, read);
- }
- is.close();
- return baos.toString("UTF-8");
+ return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
+ // TODO jdk11, inline candidate
+// return Files.readString(file.toPath());
}
/**
* Read the contents of a file as a byte array.
- * @param a data file
+ * @param file data file
* @return its raw binary contents
*/
public static byte[] readFileBin(File file) throws IOException {
- InputStream is = new FileInputStream(file);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[4096];
- int read;
- while ((read = is.read(buf)) != -1) {
- baos.write(buf, 0, read);
- }
- is.close();
- return baos.toByteArray();
+ return Files.readAllBytes(file.toPath());
+ }
+
+ /**
+ * @see #deleteFile(java.nio.file.Path)
+ */
+ public static void deleteFile(File file) throws IOException {
+ deleteFile(file.toPath());
+ }
+
+ /**
+ * Deletes the file or recursively deletes the directory.
+ */
+ public static void deleteFile(Path path) throws IOException {
+ Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+ @Override
+ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+ Files.delete(dir);
+ return FileVisitResult.CONTINUE;
+ }
+ });
}
/**
@@ -116,7 +127,7 @@
* @throws IOException for the usual reasons
*/
public static void writeZipFile(OutputStream os, String... entries) throws IOException {
- Map<String,byte[]> binary = new LinkedHashMap<String,byte[]>();
+ Map<String, byte[]> binary = new LinkedHashMap<>();
for (String entry : entries) {
int colon = entry.indexOf(':');
assert colon != -1 : entry;
@@ -132,42 +143,42 @@
* @throws IOException for the usual reasons
*/
public static void writeZipFile(OutputStream os, Map<String,byte[]> entries) throws IOException {
- ZipOutputStream zos = new ZipOutputStream(os);
- Set<String> parents = new HashSet<String>();
- if (entries.isEmpty()) {
- entries = Collections.singletonMap("PLACEHOLDER", new byte[0]);
- }
- for (Map.Entry<String,byte[]> entry : entries.entrySet()) {
- String name = entry.getKey();
- assert name.length() > 0 && !name.endsWith("/") && !name.startsWith("/") && name.indexOf("//") == -1 : name;
- for (int i = 0; i < name.length(); i++) {
- if (name.charAt(i) == '/') {
- String parent = name.substring(0, i + 1);
- if (parents.add(parent)) {
- ZipEntry ze = new ZipEntry(parent);
- ze.setMethod(ZipEntry.STORED);
- ze.setSize(0);
- ze.setCrc(0);
- ze.setTime(0);
- zos.putNextEntry(ze);
- zos.closeEntry();
+ try (ZipOutputStream zos = new ZipOutputStream(os)) {
+ Set<String> parents = new HashSet<>();
+ if (entries.isEmpty()) {
+ entries = Collections.singletonMap("PLACEHOLDER", new byte[0]);
+ }
+ for (Map.Entry<String,byte[]> entry : entries.entrySet()) {
+ String name = entry.getKey();
+ assert name.length() > 0 && !name.endsWith("/") && !name.startsWith("/") && name.indexOf("//") == -1 : name;
+ for (int i = 0; i < name.length(); i++) {
+ if (name.charAt(i) == '/') {
+ String parent = name.substring(0, i + 1);
+ if (parents.add(parent)) {
+ ZipEntry ze = new ZipEntry(parent);
+ ze.setMethod(ZipEntry.STORED);
+ ze.setSize(0);
+ ze.setCrc(0);
+ ze.setTime(0);
+ zos.putNextEntry(ze);
+ zos.closeEntry();
+ }
}
}
+ byte[] data = entry.getValue();
+ ZipEntry ze = new ZipEntry(name);
+ ze.setMethod(ZipEntry.STORED);
+ ze.setSize(data.length);
+ CRC32 crc = new CRC32();
+ crc.update(data);
+ ze.setCrc(crc.getValue());
+ ze.setTime(0);
+ zos.putNextEntry(ze);
+ zos.write(data, 0, data.length);
+ zos.closeEntry();
}
- byte[] data = entry.getValue();
- ZipEntry ze = new ZipEntry(name);
- ze.setMethod(ZipEntry.STORED);
- ze.setSize(data.length);
- CRC32 crc = new CRC32();
- crc.update(data);
- ze.setCrc(crc.getValue());
- ze.setTime(0);
- zos.putNextEntry(ze);
- zos.write(data, 0, data.length);
- zos.closeEntry();
+ zos.finish();
}
- zos.finish();
- zos.close();
os.close();
}
@@ -183,9 +194,7 @@
*/
public static void unpackZipFile(File zip, File dir) throws IOException {
byte[] buf = new byte[8192];
- InputStream is = new FileInputStream(zip);
- try {
- ZipInputStream zis = new ZipInputStream(is);
+ try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zip))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
@@ -196,19 +205,14 @@
}
if (slash != name.length() - 1) {
File f = new File(dir, name.replace('/', File.separatorChar));
- OutputStream os = new FileOutputStream(f);
- try {
+ try (OutputStream os = new FileOutputStream(f)) {
int read;
while ((read = zis.read(buf)) != -1) {
os.write(buf, 0, read);
}
- } finally {
- os.close();
}
}
}
- } finally {
- is.close();
}
}