use of java.nio.file.DirectoryNotEmptyException in project elasticsearch by elastic.
the class StreamInput method readException.
public <T extends Exception> T readException() throws IOException {
if (readBoolean()) {
int key = readVInt();
switch(key) {
case 0:
final int ord = readVInt();
return (T) ElasticsearchException.readException(this, ord);
case 1:
String msg1 = readOptionalString();
String resource1 = readOptionalString();
return (T) readStackTrace(new CorruptIndexException(msg1, resource1, readException()), this);
case 2:
String resource2 = readOptionalString();
int version2 = readInt();
int minVersion2 = readInt();
int maxVersion2 = readInt();
return (T) readStackTrace(new IndexFormatTooNewException(resource2, version2, minVersion2, maxVersion2), this);
case 3:
String resource3 = readOptionalString();
if (readBoolean()) {
int version3 = readInt();
int minVersion3 = readInt();
int maxVersion3 = readInt();
return (T) readStackTrace(new IndexFormatTooOldException(resource3, version3, minVersion3, maxVersion3), this);
} else {
String version3 = readOptionalString();
return (T) readStackTrace(new IndexFormatTooOldException(resource3, version3), this);
}
case 4:
return (T) readStackTrace(new NullPointerException(readOptionalString()), this);
case 5:
return (T) readStackTrace(new NumberFormatException(readOptionalString()), this);
case 6:
return (T) readStackTrace(new IllegalArgumentException(readOptionalString(), readException()), this);
case 7:
return (T) readStackTrace(new AlreadyClosedException(readOptionalString(), readException()), this);
case 8:
return (T) readStackTrace(new EOFException(readOptionalString()), this);
case 9:
return (T) readStackTrace(new SecurityException(readOptionalString(), readException()), this);
case 10:
return (T) readStackTrace(new StringIndexOutOfBoundsException(readOptionalString()), this);
case 11:
return (T) readStackTrace(new ArrayIndexOutOfBoundsException(readOptionalString()), this);
case 12:
return (T) readStackTrace(new FileNotFoundException(readOptionalString()), this);
case 13:
final int subclass = readVInt();
final String file = readOptionalString();
final String other = readOptionalString();
final String reason = readOptionalString();
// skip the msg - it's composed from file, other and reason
readOptionalString();
final Exception exception;
switch(subclass) {
case 0:
exception = new NoSuchFileException(file, other, reason);
break;
case 1:
exception = new NotDirectoryException(file);
break;
case 2:
exception = new DirectoryNotEmptyException(file);
break;
case 3:
exception = new AtomicMoveNotSupportedException(file, other, reason);
break;
case 4:
exception = new FileAlreadyExistsException(file, other, reason);
break;
case 5:
exception = new AccessDeniedException(file, other, reason);
break;
case 6:
exception = new FileSystemLoopException(file);
break;
case 7:
exception = new FileSystemException(file, other, reason);
break;
default:
throw new IllegalStateException("unknown FileSystemException with index " + subclass);
}
return (T) readStackTrace(exception, this);
case 14:
return (T) readStackTrace(new IllegalStateException(readOptionalString(), readException()), this);
case 15:
return (T) readStackTrace(new LockObtainFailedException(readOptionalString(), readException()), this);
case 16:
return (T) readStackTrace(new InterruptedException(readOptionalString()), this);
case 17:
return (T) readStackTrace(new IOException(readOptionalString(), readException()), this);
default:
assert false : "no such exception for id: " + key;
}
}
return null;
}
use of java.nio.file.DirectoryNotEmptyException in project jdk8u_jdk by JetBrains.
the class MaxPathLength method testLongPath.
static void testLongPath(int max, String fn, boolean tryAbsolute) throws Exception {
String[] created = new String[max];
String pathString = ".";
for (int i = 0; i < max - 1; i++) {
pathString = pathString + pathComponent + (counter++);
created[max - 1 - i] = pathString;
}
File dirFile = new File(pathString);
File f = new File(pathString + sep + fn);
String tPath = f.getPath();
if (tryAbsolute) {
tPath = f.getCanonicalPath();
}
created[0] = tPath;
//for getCanonicalPath testing on win32
File fu = new File(pathString + sep + fn.toUpperCase());
if (dirFile.exists()) {
System.err.println("Warning: Test directory structure exists already!");
return;
}
try {
Files.createDirectories(dirFile.toPath());
if (tryAbsolute)
dirFile = new File(dirFile.getCanonicalPath());
if (!dirFile.isDirectory())
throw new RuntimeException("File.isDirectory() failed");
f = new File(tPath);
if (!f.createNewFile()) {
throw new RuntimeException("File.createNewFile() failed");
}
if (!f.exists())
throw new RuntimeException("File.exists() failed");
if (!f.isFile())
throw new RuntimeException("File.isFile() failed");
if (!f.canRead())
throw new RuntimeException("File.canRead() failed");
if (!f.canWrite())
throw new RuntimeException("File.canWrite() failed");
if (!f.delete())
throw new RuntimeException("File.delete() failed");
FileOutputStream fos = new FileOutputStream(f);
fos.write(1);
fos.close();
if (f.length() != 1)
throw new RuntimeException("File.length() failed");
long time = System.currentTimeMillis();
if (!f.setLastModified(time))
throw new RuntimeException("File.setLastModified() failed");
if (f.lastModified() == 0) {
throw new RuntimeException("File.lastModified() failed");
}
String[] list = dirFile.list();
if (list == null || !fn.equals(list[0])) {
throw new RuntimeException("File.list() failed");
}
File[] flist = dirFile.listFiles();
if (flist == null || !fn.equals(flist[0].getName()))
throw new RuntimeException("File.listFiles() failed");
if (isWindows && !fu.getCanonicalPath().equals(f.getCanonicalPath()))
throw new RuntimeException("getCanonicalPath() failed");
char[] cc = tPath.toCharArray();
cc[cc.length - 1] = 'B';
File nf = new File(new String(cc));
if (!f.renameTo(nf)) {
/*there is a known issue that renameTo fails if
(1)the path is a UNC path and
(2)the path length is bigger than 1092
so don't stop if above are true
*/
String abPath = f.getAbsolutePath();
if (!abPath.startsWith("\\\\") || abPath.length() < 1093) {
throw new RuntimeException("File.renameTo() failed for lenth=" + abPath.length());
}
} else {
if (!nf.canRead())
throw new RuntimeException("Renamed file is not readable");
if (!nf.canWrite())
throw new RuntimeException("Renamed file is not writable");
if (nf.length() != 1)
throw new RuntimeException("Renamed file's size is not correct");
if (!nf.renameTo(f)) {
created[0] = nf.getPath();
}
/* add a script to test these two if we got a regression later
if (!f.setReadOnly())
throw new RuntimeException ("File.setReadOnly() failed");
f.deleteOnExit();
*/
}
} finally {
// Clean up
for (int i = 0; i < max; i++) {
Path p = (new File(created[i])).toPath();
try {
Files.deleteIfExists(p);
// Test if the file is really deleted and wait for 1 second at most
for (int j = 0; j < 10 && Files.exists(p); j++) {
Thread.sleep(100);
}
} catch (DirectoryNotEmptyException ex) {
// Give up the clean-up, let jtreg handle it.
System.err.println("Dir, " + p + ", is not empty");
break;
}
}
}
}
use of java.nio.file.DirectoryNotEmptyException in project jdk8u_jdk by JetBrains.
the class FileUtils method deleteFileWithRetry0.
private static void deleteFileWithRetry0(Path path) throws IOException, InterruptedException {
int times = 0;
IOException ioe = null;
while (true) {
try {
Files.delete(path);
while (Files.exists(path)) {
times++;
if (times > MAX_RETRY_DELETE_TIMES)
throw new IOException("File still exists after " + times + " waits.");
Thread.sleep(RETRY_DELETE_MILLIS);
}
break;
} catch (NoSuchFileException | DirectoryNotEmptyException x) {
throw x;
} catch (IOException x) {
// Backoff/retry in case another process is accessing the file
times++;
if (ioe == null)
ioe = x;
else
ioe.addSuppressed(x);
if (times > MAX_RETRY_DELETE_TIMES)
throw ioe;
Thread.sleep(RETRY_DELETE_MILLIS);
}
}
}
use of java.nio.file.DirectoryNotEmptyException in project javacpp by bytedeco.
the class Builder method build.
/**
* Starts the build process and returns an array of {@link File} produced.
*
* @return the array of File produced
* @throws IOException
* @throws InterruptedException
* @throws ParserException
*/
public File[] build() throws IOException, InterruptedException, ParserException {
if (buildCommand != null && buildCommand.length > 0) {
List<String> command = Arrays.asList(buildCommand);
String platform = Loader.getPlatform();
boolean windows = platform.startsWith("windows");
for (int i = 0; i < command.size(); i++) {
String arg = command.get(i);
if (arg == null) {
arg = "";
}
if (arg.trim().isEmpty() && windows) {
// seems to be the only way to pass empty arguments on Windows?
arg = "\"\"";
}
command.set(i, arg);
}
String text = "";
for (String s : command) {
boolean hasSpaces = s.indexOf(" ") > 0 || s.isEmpty();
if (hasSpaces) {
text += windows ? "\"" : "'";
}
text += s;
if (hasSpaces) {
text += windows ? "\"" : "'";
}
text += " ";
}
logger.info(text);
ProcessBuilder pb = new ProcessBuilder(command);
if (workingDirectory != null) {
pb.directory(workingDirectory);
}
if (environmentVariables != null) {
pb.environment().putAll(environmentVariables);
}
String paths = properties.getProperty("platform.buildpath", "");
String links = properties.getProperty("platform.linkresource", "");
String resources = properties.getProperty("platform.buildresource", "");
String separator = properties.getProperty("platform.path.separator");
if (paths.length() > 0 || resources.length() > 0) {
// Get all native libraries for classes on the class path.
List<String> libs = new ArrayList<String>();
ClassProperties libProperties = null;
for (Class c : classScanner.getClasses()) {
if (Loader.getEnclosingClass(c) != c) {
continue;
}
libProperties = Loader.loadProperties(c, properties, true);
if (!libProperties.isLoaded()) {
logger.warn("Could not load platform properties for " + c);
continue;
}
libs.addAll(libProperties.get("platform.preload"));
libs.addAll(libProperties.get("platform.link"));
}
// Extract the required resources.
for (String s : resources.split(separator)) {
for (File f : Loader.cacheResources(s)) {
String path = f.getCanonicalPath();
if (paths.length() > 0 && !paths.endsWith(separator)) {
paths += separator;
}
paths += path;
// Also create symbolic links for native libraries found there.
List<String> linkPaths = new ArrayList<String>();
for (String s2 : links.split(separator)) {
for (File f2 : Loader.cacheResources(s2)) {
String path2 = f2.getCanonicalPath();
if (path2.startsWith(path) && !path2.equals(path)) {
linkPaths.add(path2);
}
}
}
File[] files = f.listFiles();
if (files != null && libProperties != null) {
for (File file : files) {
Loader.createLibraryLink(file.getAbsolutePath(), libProperties, null, linkPaths.toArray(new String[linkPaths.size()]));
}
}
}
}
if (paths.length() > 0) {
pb.environment().put("BUILD_PATH", paths);
pb.environment().put("BUILD_PATH_SEPARATOR", separator);
}
}
int exitValue = pb.inheritIO().start().waitFor();
if (exitValue != 0) {
throw new RuntimeException("Process exited with an error: " + exitValue);
}
return null;
}
if (classScanner.getClasses().isEmpty()) {
return null;
}
List<File> outputFiles = new ArrayList<File>();
Map<String, LinkedHashSet<Class>> map = new LinkedHashMap<String, LinkedHashSet<Class>>();
for (Class c : classScanner.getClasses()) {
if (Loader.getEnclosingClass(c) != c) {
continue;
}
ClassProperties p = Loader.loadProperties(c, properties, false);
if (!p.isLoaded()) {
logger.warn("Could not load platform properties for " + c);
continue;
}
try {
if (Arrays.asList(c.getInterfaces()).contains(BuildEnabled.class)) {
((BuildEnabled) c.newInstance()).init(logger, properties, encoding);
}
} catch (ClassCastException | InstantiationException | IllegalAccessException e) {
// fail silently as if the interface wasn't implemented
}
String target = p.getProperty("target");
if (target != null && !c.getName().equals(target)) {
File f = parse(classScanner.getClassLoader().getPaths(), c);
if (f != null) {
outputFiles.add(f);
}
continue;
}
String libraryName = outputName != null ? outputName : p.getProperty("platform.library", "");
if (libraryName.length() == 0) {
continue;
}
LinkedHashSet<Class> classList = map.get(libraryName);
if (classList == null) {
map.put(libraryName, classList = new LinkedHashSet<Class>());
}
classList.addAll(p.getEffectiveClasses());
}
int count = 0;
for (String libraryName : map.keySet()) {
LinkedHashSet<Class> classSet = map.get(libraryName);
Class[] classArray = classSet.toArray(new Class[classSet.size()]);
File[] files = generateAndCompile(classArray, libraryName, count == 0, count == map.size() - 1);
if (files != null && files.length > 0) {
// files[0] might be null if "jnijavacpp" was not generated and compiled
File directory = files[files.length - 1].getParentFile();
outputFiles.addAll(Arrays.asList(files));
if (copyLibs) {
// Do not copy library files from inherit properties ...
ClassProperties p = Loader.loadProperties(classArray, properties, false);
List<String> preloads = new ArrayList<String>();
preloads.addAll(p.get("platform.preload"));
preloads.addAll(p.get("platform.link"));
// ... but we should try to use all the inherited paths!
ClassProperties p2 = Loader.loadProperties(classArray, properties, true);
for (String s : preloads) {
if (s.trim().endsWith("#")) {
// the user specified an empty destination to skip the copy
continue;
}
URL[] urls = Loader.findLibrary(null, p, s);
File fi;
try {
fi = new File(urls[0].toURI());
} catch (Exception e) {
// try with inherited paths as well
urls = Loader.findLibrary(null, p2, s);
try {
fi = new File(urls[0].toURI());
} catch (Exception e2) {
logger.warn("Could not find library " + s);
continue;
}
}
File fo = new File(directory, fi.getName());
if (fi.exists() && !outputFiles.contains(fo)) {
logger.info("Copying " + fi);
FileInputStream fis = new FileInputStream(fi);
FileOutputStream fos = new FileOutputStream(fo);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fos.close();
fis.close();
outputFiles.add(fo);
}
}
}
if (copyResources) {
// Do not copy resources from inherit properties ...
ClassProperties p = Loader.loadProperties(classArray, properties, false);
List<String> resources = p.get("platform.resource");
// ... but we should use all the inherited paths!
p = Loader.loadProperties(classArray, properties, true);
List<String> paths = p.get("platform.resourcepath");
Path directoryPath = directory.toPath();
for (String resource : resources) {
final Path target = directoryPath.resolve(resource);
if (!Files.exists(target)) {
Files.createDirectories(target);
}
for (String path : paths) {
final Path source = Paths.get(path, resource);
if (Files.exists(source)) {
logger.info("Copying " + source);
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path targetdir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, targetdir, StandardCopyOption.REPLACE_EXISTING);
} catch (DirectoryNotEmptyException | FileAlreadyExistsException e) {
if (!Files.isDirectory(targetdir)) {
throw e;
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
}
}
}
}
}
count++;
}
File[] files = outputFiles.toArray(new File[outputFiles.size()]);
if (jarPrefix != null && files.length > 0) {
File jarFile = new File(jarPrefix + "-" + properties.getProperty("platform") + properties.getProperty("platform.extension", "") + ".jar");
File d = jarFile.getParentFile();
if (d != null && !d.exists()) {
d.mkdir();
}
createJar(jarFile, outputDirectory == null ? classScanner.getClassLoader().getPaths() : null, files);
}
// reset the load flag to let users load compiled libraries
System.setProperty("org.bytedeco.javacpp.loadlibraries", "true");
return files;
}
use of java.nio.file.DirectoryNotEmptyException in project cryptofs by cryptomator.
the class CryptoFileSystemImpl method copy.
void copy(CryptoPath cleartextSource, CryptoPath cleartextTarget, CopyOption... options) throws IOException {
if (cleartextSource.equals(cleartextTarget)) {
return;
}
Path ciphertextSourceFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource, CiphertextFileType.FILE);
Path ciphertextSourceDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource, CiphertextFileType.DIRECTORY);
if (Files.exists(ciphertextSourceFile)) {
// FILE:
Path ciphertextTargetFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget, CiphertextFileType.FILE);
Files.copy(ciphertextSourceFile, ciphertextTargetFile, options);
} else if (Files.exists(ciphertextSourceDirFile)) {
// DIRECTORY (non-recursive as per contract):
Path ciphertextTargetDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget, CiphertextFileType.DIRECTORY);
if (!Files.exists(ciphertextTargetDirFile)) {
// create new:
createDirectory(cleartextTarget);
} else if (ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING)) {
// keep existing (if empty):
Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
try (DirectoryStream<Path> ds = Files.newDirectoryStream(ciphertextTargetDir)) {
if (ds.iterator().hasNext()) {
throw new DirectoryNotEmptyException(cleartextTarget.toString());
}
}
} else {
throw new FileAlreadyExistsException(cleartextTarget.toString());
}
if (ArrayUtils.contains(options, StandardCopyOption.COPY_ATTRIBUTES)) {
Path ciphertextSourceDir = cryptoPathMapper.getCiphertextDirPath(cleartextSource);
Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
copyAttributes(ciphertextSourceDir, ciphertextTargetDir);
}
} else {
throw new NoSuchFileException(cleartextSource.toString());
}
}
Aggregations