Search in sources :

Example 61 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project che by eclipse.

the class JschSshClient method copyRecursively.

private void copyRecursively(String sourceFolder, String targetFolder) throws MachineException {
    // create target dir
    try {
        int execCode = execAndGetCode("mkdir -p " + targetFolder);
        if (execCode != 0) {
            throw new MachineException(format("Creation of folder %s failed. Exit code is %s", targetFolder, execCode));
        }
    } catch (JSchException | IOException e) {
        throw new MachineException(format("Creation of folder %s failed. Error: %s", targetFolder, e.getLocalizedMessage()));
    }
    // not normalized paths don't work
    final String targetAbsolutePath = getAbsolutePath(targetFolder);
    // copy files
    ChannelSftp sftp = null;
    try {
        sftp = (ChannelSftp) session.openChannel("sftp");
        sftp.connect(connectionTimeout);
        final ChannelSftp finalSftp = sftp;
        Files.walkFileTree(Paths.get(sourceFolder), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    if (!attrs.isDirectory()) {
                        copyFile(file.toString(), Paths.get(targetAbsolutePath, file.getFileName().toString()).toString(), finalSftp);
                    } else {
                        finalSftp.mkdir(file.normalize().toString());
                    }
                } catch (MachineException | SftpException e) {
                    throw new IOException(format("Sftp copying of file %s failed. Error: %s", file, e.getLocalizedMessage()));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (JSchException | IOException e) {
        throw new MachineException("Copying failed. Error: " + e.getLocalizedMessage());
    } finally {
        if (sftp != null) {
            sftp.disconnect();
        }
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) Path(java.nio.file.Path) ChannelSftp(com.jcraft.jsch.ChannelSftp) MachineException(org.eclipse.che.api.machine.server.exception.MachineException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 62 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project elasticsearch by elastic.

the class JarHell method checkJarHell.

/**
     * Checks the set of URLs for duplicate classes
     * @throws IllegalStateException if jar hell was found
     */
@SuppressForbidden(reason = "needs JarFile for speed, just reading entries")
public static void checkJarHell(URL[] urls) throws URISyntaxException, IOException {
    Logger logger = Loggers.getLogger(JarHell.class);
    // we don't try to be sneaky and use deprecated/internal/not portable stuff
    // like sun.boot.class.path, and with jigsaw we don't yet have a way to get
    // a "list" at all. So just exclude any elements underneath the java home
    String javaHome = System.getProperty("java.home");
    logger.debug("java.home: {}", javaHome);
    final Map<String, Path> clazzes = new HashMap<>(32768);
    Set<Path> seenJars = new HashSet<>();
    for (final URL url : urls) {
        final Path path = PathUtils.get(url.toURI());
        // exclude system resources
        if (path.startsWith(javaHome)) {
            logger.debug("excluding system resource: {}", path);
            continue;
        }
        if (path.toString().endsWith(".jar")) {
            if (!seenJars.add(path)) {
                logger.debug("excluding duplicate classpath element: {}", path);
                continue;
            }
            logger.debug("examining jar: {}", path);
            try (JarFile file = new JarFile(path.toString())) {
                Manifest manifest = file.getManifest();
                if (manifest != null) {
                    checkManifest(manifest, path);
                }
                // inspect entries
                Enumeration<JarEntry> elements = file.entries();
                while (elements.hasMoreElements()) {
                    String entry = elements.nextElement().getName();
                    if (entry.endsWith(".class")) {
                        // for jar format, the separator is defined as /
                        entry = entry.replace('/', '.').substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                }
            }
        } else {
            logger.debug("examining directory: {}", path);
            // case for tests: where we have class files in the classpath
            final Path root = PathUtils.get(url.toURI());
            final String sep = root.getFileSystem().getSeparator();
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String entry = root.relativize(file).toString();
                    if (entry.endsWith(".class")) {
                        // normalize with the os separator
                        entry = entry.replace(sep, ".").substring(0, entry.length() - 6);
                        checkClass(clazzes, entry, path);
                    }
                    return super.visitFile(file, attrs);
                }
            });
        }
    }
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Logger(org.apache.logging.log4j.Logger) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 63 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project elasticsearch by elastic.

the class LogConfigurator method configure.

private static void configure(final Settings settings, final Path configsPath, final Path logsPath) throws IOException, UserException {
    Objects.requireNonNull(settings);
    Objects.requireNonNull(configsPath);
    Objects.requireNonNull(logsPath);
    setLogConfigurationSystemProperty(logsPath, settings);
    // we initialize the status logger immediately otherwise Log4j will complain when we try to get the context
    configureStatusLogger();
    final LoggerContext context = (LoggerContext) LogManager.getContext(false);
    final List<AbstractConfiguration> configurations = new ArrayList<>();
    final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
    final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            if (file.getFileName().toString().equals("log4j2.properties")) {
                configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri()));
            }
            return FileVisitResult.CONTINUE;
        }
    });
    if (configurations.isEmpty()) {
        throw new UserException(ExitCodes.CONFIG, "no log4j2.properties found; tried [" + configsPath + "] and its subdirectories");
    }
    context.start(new CompositeConfiguration(configurations));
    configureLoggerLevels(settings);
}
Also used : Path(java.nio.file.Path) FileVisitOption(java.nio.file.FileVisitOption) CompositeConfiguration(org.apache.logging.log4j.core.config.composite.CompositeConfiguration) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) LoggerContext(org.apache.logging.log4j.core.LoggerContext) PropertiesConfiguration(org.apache.logging.log4j.core.config.properties.PropertiesConfiguration) AbstractConfiguration(org.apache.logging.log4j.core.config.AbstractConfiguration) PropertiesConfigurationFactory(org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory) UserException(org.elasticsearch.cli.UserException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 64 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project elasticsearch by elastic.

the class InstallPluginCommand method install.

/**
     * Installs the plugin from {@code tmpRoot} into the plugins dir.
     * If the plugin has a bin dir and/or a config dir, those are copied.
     */
private void install(Terminal terminal, boolean isBatch, Path tmpRoot, Environment env) throws Exception {
    List<Path> deleteOnFailure = new ArrayList<>();
    deleteOnFailure.add(tmpRoot);
    try {
        PluginInfo info = verify(terminal, tmpRoot, isBatch, env);
        final Path destination = env.pluginsFile().resolve(info.getName());
        Path tmpBinDir = tmpRoot.resolve("bin");
        if (Files.exists(tmpBinDir)) {
            Path destBinDir = env.binFile().resolve(info.getName());
            deleteOnFailure.add(destBinDir);
            installBin(info, tmpBinDir, destBinDir);
        }
        Path tmpConfigDir = tmpRoot.resolve("config");
        if (Files.exists(tmpConfigDir)) {
            // some files may already exist, and we don't remove plugin config files on plugin removal,
            // so any installed config files are left on failure too
            installConfig(info, tmpConfigDir, env.configFile().resolve(info.getName()));
        }
        Files.move(tmpRoot, destination, StandardCopyOption.ATOMIC_MOVE);
        Files.walkFileTree(destination, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path pluginFile, BasicFileAttributes attrs) throws IOException {
                if (Files.isDirectory(pluginFile)) {
                    setFileAttributes(pluginFile, PLUGIN_DIR_PERMS);
                } else {
                    // There can also be "bin" directories under the plugin directory, storing native code executables
                    Path parentDir = pluginFile.getParent().getFileName();
                    if ("bin".equals(parentDir.toString())) {
                        setFileAttributes(pluginFile, BIN_FILES_PERMS);
                    } else {
                        setFileAttributes(pluginFile, PLUGIN_FILES_PERMS);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
        terminal.println("-> Installed " + info.getName());
    } catch (Exception installProblem) {
        try {
            IOUtils.rm(deleteOnFailure.toArray(new Path[0]));
        } catch (IOException exceptionWhileRemovingFiles) {
            installProblem.addSuppressed(exceptionWhileRemovingFiles);
        }
        throw installProblem;
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) IOException(java.io.IOException) UserException(org.elasticsearch.cli.UserException)

Example 65 with BasicFileAttributes

use of java.nio.file.attribute.BasicFileAttributes in project vert.x by eclipse.

the class FileSystemImpl method chmodInternal.

protected BlockingAction<Void> chmodInternal(String path, String perms, String dirPerms, Handler<AsyncResult<Void>> handler) {
    Objects.requireNonNull(path);
    Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(perms);
    Set<PosixFilePermission> dirPermissions = dirPerms == null ? null : PosixFilePermissions.fromString(dirPerms);
    return new BlockingAction<Void>(handler) {

        public Void perform() {
            try {
                Path target = vertx.resolveFile(path).toPath();
                if (dirPermissions != null) {
                    Files.walkFileTree(target, new SimpleFileVisitor<Path>() {

                        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                            //The directory entries typically have different permissions to the files, e.g. execute permission
                            //or can't cd into it
                            Files.setPosixFilePermissions(dir, dirPermissions);
                            return FileVisitResult.CONTINUE;
                        }

                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                            Files.setPosixFilePermissions(file, permissions);
                            return FileVisitResult.CONTINUE;
                        }
                    });
                } else {
                    Files.setPosixFilePermissions(target, permissions);
                }
            } catch (SecurityException e) {
                throw new FileSystemException("Accessed denied for chmod on " + path);
            } catch (IOException e) {
                throw new FileSystemException(e);
            }
            return null;
        }
    };
}
Also used : Path(java.nio.file.Path) FileSystemException(io.vertx.core.file.FileSystemException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)119 Path (java.nio.file.Path)93 IOException (java.io.IOException)87 FileVisitResult (java.nio.file.FileVisitResult)66 File (java.io.File)18 Test (org.junit.Test)13 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)11 ArrayList (java.util.ArrayList)11 HashSet (java.util.HashSet)8 FileNotFoundException (java.io.FileNotFoundException)7 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)5 BasicFileAttributeView (java.nio.file.attribute.BasicFileAttributeView)5 SourcePath (com.facebook.buck.rules.SourcePath)4 ImmutableList (com.google.common.collect.ImmutableList)4 OutputStream (java.io.OutputStream)4 URI (java.net.URI)4 FileSystem (java.nio.file.FileSystem)4 FileVisitor (java.nio.file.FileVisitor)4