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.roda.core.storage.fs.FSUtils.java

private static void moveRecursively(final Path sourcePath, final Path targetPath, final boolean replaceExisting)
        throws GenericException {
    final CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    try {/*from w w w .  j  a  v a2  s  .  c o  m*/
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path sourceDir, BasicFileAttributes attrs)
                    throws IOException {
                Path targetDir = targetPath.resolve(sourcePath.relativize(sourceDir));
                LOGGER.trace("Creating target directory {}", targetDir);
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
                Path targetFile = targetPath.resolve(sourcePath.relativize(sourceFile));
                LOGGER.trace("Moving file from {} to {}", sourceFile, targetFile);
                Files.move(sourceFile, targetFile, copyOptions);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path sourceFile, IOException exc) throws IOException {
                LOGGER.trace("Deleting source directory {}", sourceFile);
                Files.delete(sourceFile);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new GenericException(
                "Error while moving (recursively) directory from " + sourcePath + " to " + targetPath, e);
    }

}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Before
public void prepare() throws Exception {
    workDir = temp.newFolder().toPath();
    Path srcDir = Paths.get("src/test/resources/CSharpSensorTest");
    Files.walk(srcDir).forEach(path -> {
        if (Files.isDirectory(path)) {
            return;
        }//from  w w  w. ja  v a  2  s  .c  o m
        Path relativized = srcDir.relativize(path);
        try {
            Path destFile = workDir.resolve(relativized);
            if (!Files.exists(destFile.getParent())) {
                Files.createDirectories(destFile.getParent());
            }
            Files.copy(path, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    });
    File csFile = new File("src/test/resources/Program.cs").getAbsoluteFile();

    EncodingInfo msg = EncodingInfo.newBuilder().setEncoding("UTF-8").setFilePath(csFile.getAbsolutePath())
            .build();
    try (OutputStream output = Files.newOutputStream(workDir.resolve("output-cs\\encoding.pb"))) {
        msg.writeDelimitedTo(output);
    } catch (IOException e) {
        throw new IllegalStateException("could not save message to file", e);
    }

    Path roslynReport = workDir.resolve("roslyn-report.json");
    Files.write(roslynReport,
            StringUtils
                    .replace(new String(Files.readAllBytes(roslynReport), StandardCharsets.UTF_8), "Program.cs",
                            StringEscapeUtils.escapeJavaScript(csFile.getAbsolutePath()))
                    .getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.WRITE);

    tester = SensorContextTester.create(new File("src/test/resources"));
    tester.fileSystem().setWorkDir(workDir.toFile());

    inputFile = new DefaultInputFile(tester.module().key(), "Program.cs").setLanguage(CSharpPlugin.LANGUAGE_KEY)
            .initMetadata(new FileMetadata().readMetadata(new FileReader(csFile)));
    tester.fileSystem().add(inputFile);

    fileLinesContext = mock(FileLinesContext.class);
    fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(inputFile)).thenReturn(fileLinesContext);

    extractor = mock(SonarAnalyzerScannerExtractor.class);
    when(extractor.executableFile(CSharpPlugin.LANGUAGE_KEY))
            .thenReturn(new File(workDir.toFile(), SystemUtils.IS_OS_WINDOWS ? "fake.bat" : "fake.sh"));

    noSonarFilter = mock(NoSonarFilter.class);
    settings = new Settings();

    CSharpConfiguration csConfigConfiguration = new CSharpConfiguration(settings);
    sensor = new CSharpSensor(settings, extractor, fileLinesContextFactory, noSonarFilter,
            csConfigConfiguration,
            new EncodingPerFile(
                    ProjectDefinition.create().setProperty(CoreProperties.ENCODING_PROPERTY, "UTF-8"),
                    new SonarQubeVersion(tester.getSonarQubeVersion())));
}

From source file:org.openhab.tools.analysis.checkstyle.PackageExportsNameCheck.java

/**
 * Filter and return the packages from the source directory. Only not excluded packages will be returned.
 *
 * @param sourcePath - The full path of the source directory
 * @return {@link Set } of {@link String }s with the package names.
 * @throws IOException if an I/O error is thrown while visiting files
 *//*from   w w  w .  j  a  v  a2 s .  com*/
private Set<String> getFilteredPackagesFromSourceDirectory(Path sourcePath) throws IOException {
    Set<String> packages = new HashSet<>();
    // No symbolic links are expected in the source directory
    if (Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
                Path packageRelativePath = sourcePath.relativize(path.getParent());
                String packageName = packageRelativePath.toString()
                        .replaceAll(Matcher.quoteReplacement(File.separator), ".");

                if (!isExcluded(packageName)) {
                    packages.add(packageName);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }

    return packages;
}

From source file:com.gitpitch.services.DiskService.java

public void copyDirectory(Path source, Path dest) {

    log.debug("copyDirectory: source={}, dest={}", source, dest);

    try {/*from ww w  .  j a va  2  s . com*/

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {

            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                Path relative = source.relativize(dir);
                Path visitPath = Paths.get(dest.toString(), relative.toString());
                ensure(visitPath);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                Path copyTarget = Paths.get(dest.toString(), source.relativize(file).toString());
                if (!file.getFileName().toString().matches("\\..*")
                        && !copyTarget.getFileName().toString().matches("\\..*")) {
                    Files.copy(file, copyTarget);
                }
                return FileVisitResult.CONTINUE;
            }
        });

    } catch (Exception cex) {
        log.warn("copyDirectory: source={}, dest={}, ex={}", source, dest, cex);
    }
}

From source file:com.seleniumtests.driver.screenshots.ScreenshotUtil.java

/**
 * Export buffered image to screenshot object, adding HTML source, title, ...
 * @param image// ww w . j  av  a  2s . c  o  m
 * @param prefix
 * @param duration
 * @return
 */
private ScreenShot exportToScreenshot(BufferedImage image, String prefix, long duration) {
    ScreenShot screenShot = new ScreenShot();

    String url = "app";
    String title = prefix + "app";
    String pageSource = "";

    if (SeleniumTestsContextManager.isWebTest()) {
        try {
            url = driver.getCurrentUrl();
        } catch (org.openqa.selenium.UnhandledAlertException ex) {
            // ignore alert customexception
            logger.error(ex);
            url = driver.getCurrentUrl();
        } catch (Throwable e) {
            // allow screenshot even if some problem occurs
            url = "http://no/url/available";
        }

        try {
            title = driver.getTitle();
        } catch (Throwable e) {
            // allow screenshot even if some problem occurs
            title = "No Title";
        }
        title = prefix + title == null ? "" : prefix + title;

        try {
            pageSource = driver.getPageSource();
        } catch (Throwable e) {
            pageSource = "";
        }
    }

    File screenshotFile = exportToFile(image);

    screenShot.setLocation(url);
    screenShot.setTitle(title);
    try {
        FileUtils.writeStringToFile(new File(outputDirectory + "/" + HTML_DIR + filename + ".html"),
                pageSource);
        screenShot.setHtmlSourcePath(HTML_DIR + filename + ".html");
    } catch (IOException e) {
        logger.warn("Ex", e);
    }

    // record duration of screenshot
    screenShot.setDuration(duration);
    if (screenshotFile.exists()) {
        Path pathAbsolute = Paths.get(screenshotFile.getAbsolutePath());
        Path pathBase = Paths.get(getOutputDirectory());
        screenShot.setImagePath(pathBase.relativize(pathAbsolute).toString());
    }
    return screenShot;
}

From source file:org.openthinclient.util.dpkg.DPKGPackageManager.java

private File relativeFile(File baseDirectory, File absoluteFile) {

    final Path basePath = baseDirectory.getAbsoluteFile().toPath();
    final Path absolutePath = absoluteFile.getAbsoluteFile().toPath();

    return basePath.relativize(absolutePath).toFile();

}

From source file:org.nuxeo.connect.update.standalone.PackageTestCase.java

/** Zips a directory into the given ZIP file. */
protected void createZip(File zip, Path basePath) throws IOException {
    try (ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)))) {
        Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
            @Override/*from  w  w  w.  j a v  a2 s .co m*/
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                if (attrs.isDirectory()) {
                    return FileVisitResult.CONTINUE;
                }
                String rel = basePath.relativize(path).toString();
                if (rel.startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                zout.putNextEntry(new ZipEntry(rel));
                try (InputStream in = Files.newInputStream(path)) {
                    org.apache.commons.io.IOUtils.copy(in, zout);
                }
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zout.flush();
    }
}

From source file:im.bci.gamesitekit.GameSiteKitMain.java

private List<ScreenshotMV> createScreenshotsMV(Path localeOutputDir) throws IOException {
    List<ScreenshotMV> screenshots = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(screenshotThumbnailsOutputDir, IMAGE_GLOB)) {
        for (Path thumbnail : stream) {
            Path screenshot = screenshotsOutputDir.resolve(thumbnail.getFileName());
            if (Files.exists(screenshot)) {
                ScreenshotMV mv = new ScreenshotMV();
                mv.setFull(localeOutputDir.relativize(screenshot).toString().replace('\\', '/'));
                mv.setThumbnail(localeOutputDir.relativize(thumbnail).toString().replace('\\', '/'));
                screenshots.add(mv);// w ww. j a  v  a2s. c o m
            }
        }
    }
    Collections.sort(screenshots, new Comparator<ScreenshotMV>() {

        @Override
        public int compare(ScreenshotMV o1, ScreenshotMV o2) {
            return o1.getFull().compareTo(o2.getFull());
        }

    });
    return screenshots;
}

From source file:ru.histone.staticrender.StaticRenderTest.java

private void assertFilesEqualsInDirs(final Path expectedDir, final Path actualDir) throws IOException {
    final Set<String> notFoundInResult = new TreeSet();
    final Set<String> unexpectedFilesInResult = new TreeSet();
    final Set<String> notIdenticalFiles = new TreeSet();

    FileVisitor<Path> filesVisitor1 = new SimpleFileVisitor<Path>() {
        @Override//from   w  w  w .j a  va  2  s.  co m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = expectedDir.relativize(file);

            String expected = new String(Files.readAllBytes(expectedDir.resolve(relativePath)), "UTF-8");
            String actual = null;
            final Path actualFile = actualDir.resolve(relativePath);
            if (actualFile.toFile().exists()) {
                actual = new String(Files.readAllBytes(actualFile), "UTF-8");
                if (!expected.equals(actual)) {
                    notIdenticalFiles.add(relativePath.toString());
                }
            } else {
                notFoundInResult.add(relativePath.toString());
            }

            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> filesVisitor2 = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = actualDir.relativize(file);

            String expected = new String(Files.readAllBytes(actualDir.resolve(relativePath)), "UTF-8");
            String actual = null;
            final Path actualFile = expectedDir.resolve(relativePath);
            if (actualFile.toFile().exists()) {
                actual = new String(Files.readAllBytes(actualFile), "UTF-8");
                if (!expected.equals(actual)) {
                    notIdenticalFiles.add(relativePath.toString());
                }
            } else {
                unexpectedFilesInResult.add(relativePath.toString());
            }

            return FileVisitResult.CONTINUE;
        }
    };

    Files.walkFileTree(expectedDir, filesVisitor1);
    Files.walkFileTree(actualDir, filesVisitor2);

    StringBuilder err = new StringBuilder();
    if (notFoundInResult.size() > 0) {
        err.append("Files not found in result: " + Joiner.on(", ").join(notFoundInResult)).append("\n");
    }
    if (unexpectedFilesInResult.size() > 0) {
        err.append("Unexpected files found in result: " + Joiner.on(", ").join(unexpectedFilesInResult))
                .append("\n");
    }
    if (notIdenticalFiles.size() > 0) {
        err.append("Files differ in expected and in result: " + Joiner.on(", ").join(notIdenticalFiles))
                .append("\n");
    }

    if (err.length() > 0) {
        fail("Folders diff fail:\n" + err.toString());
    }
}

From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

private String resolveSchemaLocation(String namespace, Path filePath, File workDir)
        throws MojoExecutionException, IOException {
    for (ArtifactItem artifactItem : artifactItems) {
        Catalog catalog = artifactItem.getResolveCatalog();
        String publicId = namespace;
        if (publicId.endsWith("#")) {
            publicId = publicId.substring(0, publicId.length() - 1);
        }//  w ww.ja v  a2 s. c o m
        String resolvedString = catalog.resolveEntity(filePath.toString(), publicId, publicId);
        if (resolvedString != null) {
            getLog().debug("-------------------");
            getLog().debug(
                    "Resolved namespace " + namespace + " to " + resolvedString + " using catalog " + catalog);
            URL resolvedUrl = new URL(resolvedString);
            String resolvedPathString = resolvedUrl.getPath();
            Path resolvedPath = new File(resolvedPathString).toPath();
            Path workDirPath = workDir.toPath();

            Path resolvedRelativeToCatalogWorkdir = artifactItem.getWorkDir().toPath().relativize(resolvedPath);
            Path fileRelativeToWorkdir = workDirPath.relativize(filePath);

            getLog().debug("workDirPath: " + workDirPath);
            getLog().debug("resolvedRelativeToCatalogWorkdir: " + resolvedRelativeToCatalogWorkdir
                    + ",  fileRelativeToWorkdir: " + fileRelativeToWorkdir);

            Path relativePath = fileRelativeToWorkdir.getParent().relativize(resolvedRelativeToCatalogWorkdir);
            getLog().debug("Rel: " + relativePath);
            return relativePath.toString();
        }
    }
    throw new MojoExecutionException(
            "Cannot resolve namespace " + namespace + " in file " + filePath + " using any of the catalogs");
}