use of java.nio.file.FileVisitResult in project che by eclipse.
the class Resource method accept.
@Override
public void accept(final IResourceProxyVisitor visitor, final int depth, final int memberFlags) throws CoreException {
java.io.File file = workspace.getFile(getFullPath());
int maxDepth = depth == IResource.DEPTH_INFINITE ? Integer.MAX_VALUE : depth;
try {
final ResourceProxy resourceProxy = new ResourceProxy();
final int workspacePath = workspace.getAbsoluteWorkspacePath().length();
Files.walkFileTree(file.toPath(), Collections.<FileVisitOption>emptySet(), maxDepth, new FileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult preVisitDirectory(java.nio.file.Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException {
FileVisitResult result = FileVisitResult.CONTINUE;
try {
String string = file.toString();
IPath path = new Path(string.substring(workspacePath));
resourceProxy.info = workspace.getResourceInfo(path);
resourceProxy.fullPath = path;
boolean shouldContinue = true;
switch(depth) {
case DEPTH_ZERO:
shouldContinue = false;
break;
case DEPTH_ONE:
shouldContinue = !Resource.this.path.equals(path.removeLastSegments(1));
break;
case DEPTH_INFINITE:
shouldContinue = true;
break;
}
boolean visit = visitor.visit(resourceProxy) && shouldContinue;
result = visit ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
} catch (CoreException e) {
throw new WrappedRuntimeException(e);
} finally {
resourceProxy.reset();
}
return result;
}
@Override
public FileVisitResult visitFileFailed(java.nio.file.Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, ResourcesPlugin.getPluginId(), e.getMessage(), e));
}
}
use of java.nio.file.FileVisitResult 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.FileVisitResult 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.FileVisitResult 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.FileVisitResult 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;
}
}
Aggregations