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();
}
}
}
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);
}
});
}
}
}
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);
}
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;
}
}
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;
}
};
}
Aggregations