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.moe.gradle.remote.Server.java

public String getSDKRemotePath(@NotNull File file) throws IOException {
    Require.nonNull(file);//from   w w w  .j  ava2s  . com

    final Path filePath = file.toPath().toAbsolutePath();
    final Path sdk = plugin.getSDK().getRoot().toPath().toAbsolutePath();

    if (!filePath.getRoot().equals(sdk.getRoot())) {
        throw new IOException("non-sdk file");
    }

    final Path relative = sdk.relativize(filePath);
    return getRemotePath(getSdkDir(), relative);
}

From source file:org.openehr.adl.TestingArchetypeProvider.java

private Map<String, String> buildArchetypeIdToClasspathMap(final String classpath) throws IOException {
    final Map<String, String> result = new HashMap<>();
    String baseFile = getClass().getClassLoader().getResource(classpath).getFile();
    if (baseFile.contains(":") && baseFile.startsWith("/"))
        baseFile = baseFile.substring(1);
    final Path basePath = Paths.get(baseFile);
    Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
        @Override/*from   w  ww  .j  a v  a2  s  .c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String filename = file.getFileName().toString();
            String ext = FilenameUtils.getExtension(filename);
            if (ext.equalsIgnoreCase("adls") || ext.equalsIgnoreCase("adl")) {
                String archetypeId = FilenameUtils.getBaseName(filename);
                String relativePath = basePath.relativize(file).toString();
                result.put(archetypeId, Paths.get(classpath).resolve(relativePath).toString());
            }
            return super.visitFile(file, attrs);
        }
    });

    return result;
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.LocalDiskProfileReader.java

public InputStream readArchiveProfileFrom(Path profilePath) throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();/*  w ww  .  j  av a  2 s  . com*/
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

@Override
public String getAbsolutePath(final String resourceURI, final String tenantID) {
    final Path volumeIdentifier = Paths.get(VOLUME_IDENTIFIER);
    final Path relative = Paths.get(getRelativePath(resourceURI));
    return new StringBuilder().append(VOLUME).append("/").append(tenantID).append("/")
            .append(volumeIdentifier.relativize(relative).toString()).toString();
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GitProfileReader.java

@Override
public InputStream readArchiveProfile(String artifactName, String version, String profileName)
        throws IOException {
    Path profilePath = Paths.get(profilePath(artifactName, version, profileName));

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        int permissions = FileModeUtils.getFileMode(Files.getPosixFilePermissions(path));
        permissions = FileModeUtils.setFileBit(permissions);
        tarEntry.setMode(permissions);/*from  w  ww . j a v  a2s  .c o  m*/
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:org.apache.openaz.xacml.admin.view.windows.GitPushWindow.java

protected void refreshStatus() {
    try {//  w w  w. j a  v  a 2 s .c o m
        //
        // Grab our working repository
        //
        Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
        final Git git = Git.open(repoPath.toFile());
        //
        // Get our status
        //
        final String base;
        Status status;
        if (target == null) {
            base = ".";
        } else {
            Path relativePath = repoPath.relativize(Paths.get(target.getPath()));
            base = relativePath.toString();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Status on base: " + base);
        }
        status = git.status().addPath(base).call();
        //
        // Pass it to our container
        //
        this.container.refreshStatus(status);
        this.tableChanges.refreshRowCache();
    } catch (NoWorkTreeException | IOException | GitAPIException e) {
        String error = "Failed to refresh status: " + e.getLocalizedMessage();
        logger.error(error);
    }
}

From source file:com.oxiane.maven.xqueryMerger.Merger.java

@Override
public void execute() throws MojoExecutionException {
    Path sourceRootPath = inputSources.toPath();
    Path destinationRootPath = outputDirectory.toPath();
    IOFileFilter filter = buildFilter();
    Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter());
    if (!it.hasNext()) {
        getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath());
    }// w ww.ja  va  2 s . co  m
    while (it.hasNext()) {
        File sourceFile = it.next();
        Path fileSourcePath = sourceFile.toPath();
        Path relativePath = sourceRootPath.relativize(fileSourcePath);
        getLog().debug("[Merger] found source: " + fileSourcePath.toString());
        getLog().debug("[Merger]    relative path is " + relativePath.toString());
        StreamSource source = new StreamSource(sourceFile);
        XQueryMerger merger = new XQueryMerger(source);
        merger.setMainQuery();
        File destinationFile = destinationRootPath.resolve(relativePath).toFile();
        getLog().debug("[Merger]    destination will be " + destinationFile.getAbsolutePath());
        try {
            String result = merger.merge();
            destinationFile.getParentFile().mkdirs();
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile),
                    merger.getEncoding());
            osw.write(result);
            osw.flush();
            osw.close();
            getLog().debug("[Merger] " + relativePath.toString() + " merged into "
                    + destinationFile.getAbsolutePath());
        } catch (ParsingException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex);
        } catch (FileNotFoundException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException(
                    "Unable to create destination " + destinationFile.getAbsolutePath(), ex);
        } catch (IOException ex) {
            getLog().error(ex.getMessage());
            throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex);
        }
    }
}

From source file:org.zanata.sync.jobs.cache.RepoCacheImpl.java

private long copyDir(Path source, Path target) throws IOException {
    Files.createDirectories(target);
    AtomicLong totalSize = new AtomicLong(0);
    Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override//from w  ww .  j  ava  2 s . co  m
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    Path targetdir = target.resolve(source.relativize(dir));
                    try {
                        if (Files.isDirectory(targetdir) && Files.exists(targetdir)) {
                            return CONTINUE;
                        }
                        Files.copy(dir, targetdir, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (FileAlreadyExistsException e) {
                        if (!Files.isDirectory(targetdir)) {
                            throw e;
                        }
                    }
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file)) {
                        totalSize.accumulateAndGet(Files.size(file), (l, r) -> l + r);
                    }
                    Path targetFile = target.resolve(source.relativize(file));

                    // only copy to target if it doesn't exist or it exist but the content is different
                    if (!Files.exists(targetFile)
                            || !com.google.common.io.Files.equal(file.toFile(), targetFile.toFile())) {
                        Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    }
                    return CONTINUE;
                }
            });
    return totalSize.get();
}

From source file:cz.etnetera.reesmo.writer.storage.RestApiStorage.java

protected void addResultAttachment(final Result result, Object attachment) throws StorageException {
    File file = null;/*  www . j av  a 2  s  .c  o  m*/
    String path = null;
    String contentType = null;
    if (attachment instanceof File) {
        file = (File) attachment;
    } else if (attachment instanceof ExtendedFile) {
        ExtendedFile fileWithPath = (ExtendedFile) attachment;
        file = fileWithPath.getFile();
        path = fileWithPath.getPath();
        contentType = fileWithPath.getContentType();
    } else {
        throw new StorageException("Unsupported attachment type " + attachment.getClass());
    }

    if (path != null) {
        path = path.replaceAll("^/+", "").replaceAll("/+$", "");
    }

    if (file.isDirectory()) {
        Path root = file.toPath();
        final String rootPath = path == null ? file.getName() : path;
        try {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    FileVisitResult res = super.visitFile(file, attrs);
                    String relativePath = rootPath + "/" + root.relativize(file).normalize().toString();
                    try {
                        addResultAttachment(result, ExtendedFile.withPath(file.toFile(), relativePath));
                    } catch (StorageException e) {
                        throw new IOException(e);
                    }
                    return res;
                }
            });
        } catch (IOException e) {
            throw new StorageException(e);
        }
        // directory is not stored, just paths
        return;
    }

    MultipartBody body = Unirest
            .post(getUrl(METHOD_RESULT_ATTACHMENT_CREATE).replace("{resultId}", result.getId()))
            .basicAuth(username, password).header("Accept", "application/json").field("file", file);
    if (path != null) {
        body.field("path", path);
    }
    if (contentType != null) {
        body.field("contentType", contentType);
    }

    HttpResponse<String> response;
    try {
        response = body.asString();
    } catch (UnirestException e) {
        throw new StorageException("Unable to store result attachment", e);
    }

    if (response.getStatus() != 200) {
        throw new StorageException("Wrong status code when storing result attachment " + response.getStatus());
    }

    ResultAttachment resultAttachment = null;
    try {
        resultAttachment = new ObjectMapper().readValue(response.getBody(), ResultAttachment.class);
    } catch (UnsupportedOperationException | IOException e) {
        throw new StorageException("Unable to parse result attachment from response", e);
    }

    getLogger().info("Result attachment stored " + resultAttachment.getPath() + " " + resultAttachment.getId());
}

From source file:org.geowebcache.sqlite.OperationsRestTest.java

private void zipDirectory(Path directoryToZip, File outputZipFile) throws IOException {
    try (FileOutputStream fileOutputStream = new FileOutputStream(outputZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        Files.walkFileTree(directoryToZip, new SimpleFileVisitor<Path>() {

            public FileVisitResult visitFile(Path file, BasicFileAttributes fileAttributes) throws IOException {
                zipOutputStream.putNextEntry(new ZipEntry(directoryToZip.relativize(file).toString()));
                Files.copy(file, zipOutputStream);
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }/*from   w  ww  .  ja  v  a2s .  c  o  m*/

            public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
                    throws IOException {
                if (directory.equals(directoryToZip)) {
                    return FileVisitResult.CONTINUE;
                }
                // the zip structure is not tied the OS file separator
                zipOutputStream
                        .putNextEntry(new ZipEntry(directoryToZip.relativize(directory).toString() + "/"));
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}