Example usage for java.nio.file Path relativize

List of usage examples for java.nio.file Path relativize

Introduction

In this page you can find the example usage for java.nio.file Path relativize.

Prototype

Path relativize(Path other);

Source Link

Document

Constructs a relative path between this path and a given path.

Usage

From source file:org.jamocha.classloading.Loader.java

/**
 * Recursively loads all class files in the specified directory. The name of the directory is to be split up into
 * the part specifying the path to the start of the package hierarchy and the part specifying which part of the
 * hierarchy is to be loaded. <br /> <b>Example:</b> loadClassesInDirectory("target/classes",
 * "org/jamocha/function/impls/predicates"); loads all class files within
 * "target/classes/org/jamocha/function/impls/predicates"
 * and the files found in that folder there have the package specification "org.jamocha.function.impls.predicates".
 * Class files in sub directories of the predicates folder have their package specification adjusted accordingly.
 *
 * @param pathToDir//from  ww w  .  j av  a2  s. c  om
 *         the base path to the directory containing the package hierarchy (separator '/')
 * @param packageString
 *         the path within the package hierarchy (separator '/')
 */
public static void loadClassesInDirectory(final String pathToDir, final String packageString) {
    log.debug("Loading classes in directory file:{}/{}", pathToDir, packageString);
    final Path basePath = FileSystems.getDefault().getPath(pathToDir);
    try (final Stream<Path> files = java.nio.file.Files
            .walk(FileSystems.getDefault().getPath(pathToDir, packageString))) {
        files.filter(file -> !file.toFile().isDirectory() && file.toString().endsWith(".class"))
                .forEach(file -> {
                    final Path filePath = basePath.relativize(file);
                    final String clazzName = filePathToClassName(filePath.toString());
                    log.debug("Loading class {}", clazzName);
                    try {
                        Class.forName(clazzName);
                    } catch (final ClassNotFoundException ex) {
                        log.catching(ex);
                    } catch (final ExceptionInInitializerError ex) {
                        log.catching(ex);
                    }
                });
    } catch (final IOException ex) {
        log.catching(ex);
    }
}

From source file:de.monticore.io.paths.IterablePath.java

/**
 * Creates a new {@link IterablePath} based on the supplied set of {@link Path}s containing all
 * files with the specified extensions. Note: an empty set of extensions will yield an empty
 * {@link IterablePath}./*w ww.  j  a  v a 2 s. co  m*/
 * 
 * @param paths
 * @param extensions
 * @return
 */
public static IterablePath fromPaths(List<Path> paths, Set<String> extensions) {
    Map<Path, Path> pMap = new LinkedHashMap<>();
    for (Path path : paths) {
        List<Path> entries = walkFileTree(path).filter(getExtensionsPredicate(extensions))
                .collect(Collectors.toList());
        for (Path entry : entries) {
            Path key = path.relativize(entry);
            if (key.toString().isEmpty()) {
                key = entry;
            }
            if (pMap.get(key) != null) {
                Log.debug("The qualified path " + key + " appears multiple times.",
                        IterablePath.class.getName());
            } else {
                pMap.put(key, entry);
            }
        }
    }
    return new IterablePath(paths, pMap);
}

From source file:com.excelsiorjet.api.util.Utils.java

public static void copyDirectory(Path source, Path target) throws IOException {
    Files.walkFileTree(source, new FileVisitor<Path>() {

        @Override/*from   w ww.  ja v  a 2 s  . c o  m*/
        public FileVisitResult preVisitDirectory(Path subfolder, BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(target.resolve(source.relativize(subfolder)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
            Path targetFile = target.resolve(source.relativize(sourceFile));
            copyFile(sourceFile, targetFile);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path sourceFile, IOException e) throws IOException {
            throw new IOException(Txt.s("Utils.CannotCopyFile.Error", sourceFile.toString(), e.getMessage()),
                    e);
        }

        @Override
        public FileVisitResult postVisitDirectory(Path source, IOException ioe) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.elasticsearch.bootstrap.JarHell.java

/**
 * Checks the set of URLs for duplicate classes
 * @throws IllegalStateException if jar hell was found
 *//*from www  . ja v a2 s .c  om*/
@SuppressForbidden(reason = "needs JarFile for speed, just reading entries")
public static void checkJarHell(URL urls[]) throws Exception {
    ESLogger 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; // we can't fail because of sheistiness with joda-time
            }
            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);
                }
            });
        }
    }
}

From source file:org.jsweet.input.typescriptdef.TypescriptDef2Java.java

private static void parse(Context context, File f) throws IOException {
    // context.compilationUnits.stream().map((cu) -> { return
    // cu.getFile();}).
    if (context.compilationUnits.contains(new CompilationUnit(f))) {
        // logger.info("skipping: " + f);
        return;/*  ww w  .  j a  v a  2s .co m*/
    }
    logger.info("parsing: " + f);
    // This class is automatically generated by CUP (please generate to compile)
    TypescriptDefParser parser = TypescriptDefParser.parseFile(f);
    context.compilationUnits.add(parser.compilationUnit);
    grabReferences(parser.compilationUnit);
    for (String reference : parser.compilationUnit.getReferences()) {
        String path = Util.getLibPathFromReference(reference);
        if (path != null) {
            File dep = new File(f.getParent(), path);
            if (!dep.exists()) {
                context.reportError("dependency '" + dep + "' does not exist", (Token) null);
            } else {
                File tsDefFile = parser.compilationUnit.getFile();
                boolean ignored = isIgnoredReference(tsDefFile, path);
                if (dep.getPath().contains("..")) {
                    try {
                        Path currentPath = new File("").getAbsoluteFile().toPath();
                        Path depPath = dep.getCanonicalFile().toPath();
                        logger.debug("depPath: " + depPath);
                        Path relPath = currentPath.relativize(depPath);
                        if (!relPath.toString().contains("..")) {
                            dep = relPath.toFile();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                logger.info("handling dependency: " + dep);
                if (ignored) {
                    context.getDependenciesDefinitions().add(dep);
                } else {
                    parse(context, dep);
                }
            }
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtil.java

/**
 * Constructs a normalized relative path between base directory and a given path.
 *
 * @param baseDirectory//from   w w w . j av a  2 s.  co m
 *            the base path to which given path is relativized
 * @param path
 *            the path to relativize against base directory
 * @return the relative normalized path between base directory and
 *     path or path if base directory is null.
 */
public static String relativizeAndNormalizePath(final String baseDirectory, final String path) {
    final String resultPath;
    if (baseDirectory == null) {
        resultPath = path;
    } else {
        final Path pathAbsolute = Paths.get(path).normalize();
        final Path pathBase = Paths.get(baseDirectory).normalize();
        resultPath = pathBase.relativize(pathAbsolute).toString();
    }
    return resultPath;
}

From source file:org.sonarsource.commandlinezip.ZipUtils7.java

public static void zipDir(final Path srcDir, Path zip) throws IOException {

    try (final OutputStream out = FileUtils.openOutputStream(zip.toFile());
            final ZipOutputStream zout = new ZipOutputStream(out)) {
        Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
            @Override/*  w  w  w . j  ava 2  s  .c  o  m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                    String entryName = srcDir.relativize(file).toString();
                    ZipEntry entry = new ZipEntry(entryName);
                    zout.putNextEntry(entry);
                    IOUtils.copy(in, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(srcDir)) {
                    return FileVisitResult.CONTINUE;
                }

                String entryName = srcDir.relativize(dir).toString();
                ZipEntry entry = new ZipEntry(entryName);
                zout.putNextEntry(entry);
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:org.sonarsource.commandlinezip.ZipUtils7.java

public static void smartReportZip(final Path srcDir, Path zip) throws IOException {
    try (final OutputStream out = FileUtils.openOutputStream(zip.toFile());
            final ZipOutputStream zout = new ZipOutputStream(out)) {
        Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
            @Override//from w  w  w  .  j  a  v a  2 s.  c  o  m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                    String entryName = srcDir.relativize(file).toString();
                    int level = file.toString().endsWith(".pb") ? ZipOutputStream.STORED
                            : Deflater.DEFAULT_COMPRESSION;
                    zout.setLevel(level);
                    ZipEntry entry = new ZipEntry(entryName);
                    zout.putNextEntry(entry);
                    IOUtils.copy(in, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(srcDir)) {
                    return FileVisitResult.CONTINUE;
                }

                String entryName = srcDir.relativize(dir).toString();
                ZipEntry entry = new ZipEntry(entryName);
                zout.putNextEntry(entry);
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:org.sonarsource.scanner.maven.bootstrap.MavenProjectConverter.java

private static void removeTarget(MavenProject pom, Collection<String> relativeOrAbsolutePaths) {
    final Path baseDir = pom.getBasedir().toPath().toAbsolutePath().normalize();
    final Path target = Paths.get(pom.getBuild().getDirectory()).toAbsolutePath().normalize();
    final Path targetRelativePath = baseDir.relativize(target);

    relativeOrAbsolutePaths.removeIf(pathStr -> {
        Path path = Paths.get(pathStr).toAbsolutePath().normalize();
        Path relativePath = baseDir.relativize(path);
        return relativePath.startsWith(targetRelativePath);
    });/*from w  ww.  ja  va 2s.c o  m*/
}

From source file:fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.java

/**
 * Unzip a jar file//www. j  av a2 s.  c  om
 * @param jarFile Jar file url like file:/path/to/foo.jar
 * @param destination Directory where we want to extract the content to
 * @throws IOException In case of any IO problem
 */
public static void unzip(String jarFile, Path destination) throws IOException {
    Map<String, String> zipProperties = new HashMap<>();
    /* We want to read an existing ZIP File, so we set this to false */
    zipProperties.put("create", "false");
    zipProperties.put("encoding", "UTF-8");
    URI zipFile = URI.create("jar:" + jarFile);

    try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, zipProperties)) {
        Path rootPath = zipfs.getPath("/");
        Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetPath = destination.resolve(rootPath.relativize(dir).toString());
                if (!Files.exists(targetPath)) {
                    Files.createDirectory(targetPath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, destination.resolve(rootPath.relativize(file).toString()),
                        StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}