List of usage examples for java.nio.file FileVisitOption FOLLOW_LINKS
FileVisitOption FOLLOW_LINKS
To view the source code for java.nio.file FileVisitOption FOLLOW_LINKS.
Click Source Link
From source file:net.mozq.picto.core.ProcessCore.java
public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter, BooleanSupplier processStopper) throws IOException { Set<FileVisitOption> fileVisitOptionSet; if (processCondition.isFollowLinks()) { fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS); } else {/*from ww w .j a va2 s . c o m*/ fileVisitOptionSet = Collections.emptySet(); } Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isDirectory()) { return FileVisitResult.SKIP_SUBTREE; } if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } if (!processCondition.getPathFilter().accept(file, attrs)) { return FileVisitResult.SKIP_SUBTREE; } Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent()); ImageMetadata imageMetadata = getImageMetadata(file); Date baseDate; if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate() || processCondition.isChangeFileAccessDate() || processCondition.isChangeExifDate()) { baseDate = getBaseDate(processCondition, file, attrs, imageMetadata); } else { baseDate = null; } String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> { try { switch (varName) { case "Now": return new Date(); case "ParentSubPath": return rootRelativeSubPath.toString(); case "FileName": return file.getFileName().toString(); case "BaseName": return FileUtilz.getBaseName(file.getFileName().toString()); case "Extension": return FileUtilz.getExt(file.getFileName().toString()); case "Size": return Long.valueOf(Files.size(file)); case "CreationDate": return (processCondition.isChangeFileCreationDate()) ? baseDate : new Date(attrs.creationTime().toMillis()); case "ModifiedDate": return (processCondition.isChangeFileModifiedDate()) ? baseDate : new Date(attrs.lastModifiedTime().toMillis()); case "AccessDate": return (processCondition.isChangeFileAccessDate()) ? baseDate : new Date(attrs.lastAccessTime().toMillis()); case "PhotoTakenDate": return (processCondition.isChangeExifDate()) ? baseDate : getPhotoTakenDate(file, imageMetadata); case "Width": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH); case "Height": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH); case "FNumber": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER); case "Aperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_APERTURE_VALUE); case "MaxAperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE); case "ISO": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO); case "FocalLength": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ? case "FocalLength35mm": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT); case "ShutterSpeed": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE); case "Exposure": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // case "ExposureTime": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // case "ExposureMode": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE); case "ExposureProgram": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM); case "Brightness": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE); case "WhiteBalance": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1); case "LightSource": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE); case "Lens": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS); case "LensMake": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE); case "LensModel": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL); case "LensSerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER); case "Make": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE); case "Model": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL); case "SerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SERIAL_NUMBER); case "Software": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE); case "ProcessingSoftware": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE); case "OwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME); case "CameraOwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME); case "GPSLat": return getEXIFGpsLat(imageMetadata); case "GPSLatDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 0); case "GPSLatMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 1); case "GPSLatSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 2); case "GPSLatRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF); case "GPSLon": return getEXIFGpsLon(imageMetadata); case "GPSLonDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 0); case "GPSLonMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 1); case "GPSLonSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 2); case "GPSLonRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF); case "GPSAlt": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE); case "GPSAltRef": return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF); default: throw new PictoInvalidDestinationPathException(Messages .getString("message.warn.invalid.destSubPath.varName", varName)); } } catch (PictoException e) { throw e; } catch (Exception e) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destSubPath.pattern"), e); } }); Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize(); if (!destSubPath.startsWith(processCondition.getDestRootPath())) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destination.path", destSubPath)); } ProcessData processData = new ProcessData(); processData.setSrcPath(file); processData.setSrcFileAttributes(attrs); processData.setDestPath(destSubPath); processData.setBaseDate(baseDate); processDataSetter.accept(processData); return FileVisitResult.CONTINUE; } }); }
From source file:com.amazonaws.codepipeline.jenkinsplugin.CompressionTools.java
public static List<File> addFilesToCompress(final Path pathToCompress, final BuildListener listener) throws IOException { final List<File> files = new ArrayList<>(); if (pathToCompress != null) { Files.walkFileTree(pathToCompress, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override//from w w w .jav a2s . com public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { files.add(file.toFile()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) throws IOException { if (e != null) { LoggingHelper.log(listener, "Failed to visit file '%s'. Error: %s.", file.toString(), e.getMessage()); LoggingHelper.log(listener, e); throw e; } return FileVisitResult.CONTINUE; } }); } return files; }
From source file:de.ingrid.interfaces.csw.cache.AbstractFileCache.java
/** * Get document ids from a directory and all sub directories * /* ww w . ja va 2 s . c o m*/ * @param directory * The start directory * @return Set */ protected Set<Serializable> getDocumentIds(File directory) { Set<Serializable> documentIds = new HashSet<Serializable>(); EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); CacheFileLister cfl = new CacheFileLister(documentIds); try { Files.walkFileTree(directory.toPath(), opts, Integer.MAX_VALUE, cfl); } catch (IOException e) { log.error("Error getting document IDs from cache."); } return documentIds; }
From source file:com.google.devtools.build.android.PackedResourceTarExpander.java
private void copyRemainingResources(final Path resourcePath, final Path packedResources) throws IOException { Files.walkFileTree(resourcePath, ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new ConditionallyLinkingVisitor(packedResources, out, workingDirectory)); }
From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java
@Override public void run() { try {/*from ww w. j av a2 s. co m*/ // Send TASK_RUNNING sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot"); if (Objects.equals(context.getRestoreType(), new String("new"))) { final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName() + File.separator + context.getNodeId(); final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader") .toString(); final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString(); final File keyspacesDirectory = new File(keyspaceDirectory); LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists()); final File[] keyspaces = keyspacesDirectory.listFiles(); String libProcessAddress = System.getenv("LIBPROCESS_IP"); libProcessAddress = StringUtils.isBlank(libProcessAddress) ? InetAddress.getLocalHost().getHostAddress() : libProcessAddress; for (File keyspace : keyspaces) { final File[] columnFamilies = keyspace.listFiles(); final String keyspaceName = keyspace.getName(); if (keyspaceName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Going to bulk load keyspace: {}", keyspaceName); for (File columnFamily : columnFamilies) { final String columnFamilyName = columnFamily.getName(); if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName, columnFamilyName); final String columnFamilyPath = columnFamily.getAbsolutePath(); final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress, "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml, columnFamilyPath); LOGGER.info("Executing command: {}", command); final ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { LOGGER.info(line); } int exitCode = process.waitFor(); LOGGER.info("Command exit code: {}", exitCode); // Send TASK_ERROR if (exitCode != 0) { final String errMessage = String.format("Error restoring snapshot. Exit code: %s", (exitCode + "")); LOGGER.error(errMessage); sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage); } LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName, columnFamilyName); } LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName); } // cleanup downloaded snapshot directory recursively. Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName()); if (rootPath.toFile().exists()) { Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(Path::toFile).forEach(File::delete); } } else { // run nodetool refresh rather than SSTableLoader, as on performance test // I/O stream was pretty slow between mesos container processes final String localLocation = context.getLocalLocation(); final List<String> keyspaces = cassandra.getNonSystemKeySpaces(); for (String keyspace : keyspaces) { final String keySpaceDirPath = localLocation + "/" + keyspace; File keySpaceDir = new File(keySpaceDirPath); File[] cfNames = keySpaceDir .listFiles((current, name) -> new File(current, name).isDirectory()); for (File cfName : cfNames) { String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-")); cassandra.getProbe().loadNewSSTables(keyspace, columnFamily); LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace, columnFamily); } } } final String message = "Finished restoring snapshot"; LOGGER.info(message); sendStatus(driver, Protos.TaskState.TASK_FINISHED, message); } catch (Throwable t) { // Send TASK_FAILED final String errorMessage = "Failed restoring snapshot. Reason: " + t; LOGGER.error(errorMessage, t); sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage); } }
From source file:com.eqbridges.vertx.VerticleModuleMojo.java
private void copyFiles(File fromDir, File verticleFolder) throws MojoExecutionException { Path from = Paths.get(fromDir.toURI()); Path to = Paths.get(verticleFolder.toURI()); try {/*from ww w . j a v a 2s . c om*/ Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new CopyDirVisitor(from, to, getLog())); } catch (IOException e) { throw new MojoExecutionException("unable to copy classes to verticleFolder", e); } }
From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java
/** * Calculate single db chunk size./*from w w w . ja va2s .c o m*/ * * @return long chunk size * * @throws IOException I/O error in visitor method */ private long getMaxChunkSize() throws IOException { // Calculate db chunk size DirSizeVisitor dbSizeVisitor = new DirSizeVisitor(filter); Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, dbSizeVisitor); final long chunkSize = dbSizeVisitor.getSize() / maxDbSizeSizePerChunk + (dbSizeVisitor.getSize() % maxDbSizeSizePerChunk == 0 ? 0 : 1); return dbSizeVisitor.getSize() / chunkSize + 1; }
From source file:dk.dma.dmiweather.service.FTPLoader.java
private static void deleteRecursively(File lastTempDir) throws IOException { Path rootPath = lastTempDir.toPath(); //noinspection ResultOfMethodCallIgnored Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) // flips the tree so leefs are deleted first .map(Path::toFile).peek(f -> log.debug("deleting file " + f.getAbsolutePath())) .forEach(File::delete); }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }/*from w w w .ja va 2 s. c o m*/ } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java
/** * Creates all databases.//from www . ja va 2s .co m * * @throws IOException I/O error in visitor method * @throws InterruptedException thread is interrupted */ public void createDatabases() throws IOException, InterruptedException { final long maxChunkSize = getMaxChunkSize(); // Create databases FileVisitor<Path> basexPartitioner = new BasexFileVisitorPartitioner(maxChunkSize); Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, basexPartitioner); if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } logger.info("Added " + fileCount + " files (" + FileUtils.byteCountToDisplaySize(size) + ") to " + getDbCount() + " database(s) "); logger.info("Optimizing database " + dbBaseName + "-0"); flushAndOptimize(ctx); new Open(dbBaseName + "-0").execute(ctx); new Close().execute(ctx); ctx.close(); logger.info("Import completed"); }