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:jodtemplate.pptx.ImageService.java

private Relationship getImageRelationship(final Image image, final Slide slide) {
    final Path imageFullPath = Paths.get(image.getFullPath());
    final Path slideFullPath = Paths.get(FilenameUtils
            .getFullPath(slide.getPresentation().getFullPath() + slide.getRelationship().getTarget()));
    final Path relativeImagePath = slideFullPath.relativize(imageFullPath);
    final String normRelativeImagePath = FilenameUtils.separatorsToUnix(relativeImagePath.toString());

    Relationship imageRel = slide.getRelationshipByTarget(normRelativeImagePath);

    if (imageRel == null) {
        imageRel = new Relationship();
        imageRel.setId(slide.getNextId());
        imageRel.setTarget(normRelativeImagePath);
        imageRel.setType(Relationship.IMAGE_TYPE);
        slide.addOtherRelationship(imageRel);
    }/*from  w w  w.  j  a v  a2s  .  c o m*/

    return imageRel;
}

From source file:ffx.xray.DiffractionFile.java

/**
 * read in a diffraction file based on the molecular assembly filename,
 * using a weight of 1.0 and neutron value of false
 *
 * @param assembly {@link ffx.potential.MolecularAssembly} from which a
 * filename will be determined/*from   w w  w.  j av  a 2  s.  co m*/
 * @param weight the weight of the data
 * @param neutron if true, this is a neutron data set
 */
public DiffractionFile(MolecularAssembly assembly, double weight, boolean neutron) {
    String name = removeExtension(assembly.getFile().getPath());

    File tmp = new File(name + ".mtz");
    if (tmp.exists()) {
        //logger.info("\n Data file: " + tmp.getName());
        diffractionfilter = new MTZFilter();
    } else {
        tmp = new File(name + ".cif");
        if (tmp.exists()) {
            //logger.info("\n Data file: " + tmp.getName());
            diffractionfilter = new CIFFilter();
        } else {
            tmp = new File(name + ".ent");
            if (tmp.exists()) {
                //logger.info("\n Data file: " + tmp.getName());
                diffractionfilter = new CIFFilter();
            } else {
                tmp = new File(name + ".sf");
                if (tmp.exists()) {
                    //logger.info("\n Data file: " + tmp.getName());
                    diffractionfilter = new CIFFilter();
                } else {
                    tmp = new File(name + ".cns");
                    if (tmp.exists()) {
                        //logger.info("\n Data file: " + tmp.getName());
                        diffractionfilter = new CNSFilter();
                    } else {
                        tmp = new File(name + ".hkl");
                        if (tmp.exists()) {
                            //logger.info("\n Data file: " + tmp.getName());
                            diffractionfilter = new CNSFilter();
                        } else {
                            logger.severe("no input data found!");
                            diffractionfilter = null;
                        }
                    }
                }
            }
        }
    }
    String filenameHolder; // Compiler complains if I set this.filename directly.
    try {
        Path filepath = Paths.get(tmp.getCanonicalPath());
        Path pwdPath = Paths.get(new File("").getCanonicalPath());
        filenameHolder = pwdPath.relativize(filepath).toString();
    } catch (IOException ex) {
        logger.warning(
                " Relative path to provided data file could not be resolved: using data file name instead.");
        filenameHolder = tmp.getName();
    }
    this.filename = filenameHolder;
    this.weight = weight;
    this.neutron = neutron;
}

From source file:ezbake.deployer.publishers.artifact.ArtifactContentsPublisher.java

protected Collection<ArtifactDataEntry> collectConfigurationResources(DeploymentArtifact artifact,
        String resourceClassPath, java.nio.file.Path artifactBasePath, ArtifactDataEntryResourceCreator creator,
        boolean forceOverwrite) throws DeploymentException {
    java.util.List<ezbake.deployer.utilities.ArtifactDataEntry> artifactCollection = com.google.common.collect.Lists
            .newArrayList();/*from  w  w  w.  j  a v a2s.  c  om*/
    final java.util.List<String> resources = getResourcesFromClassPath(this.getClass(), resourceClassPath);
    final java.nio.file.Path resourceDir = java.nio.file.Paths.get(resourceClassPath.replaceAll("\\.", "/"));

    for (String resource : resources) {
        try {
            java.nio.file.Path artifactPath = java.nio.file.Paths.get(artifactBasePath.toString(),
                    resourceDir.relativize(java.nio.file.Paths.get(resource)).toString());

            if (forceOverwrite || !doesResourceAlreadyExistInArtifact(artifactPath, artifactBasePath,
                    artifact.getArtifact())) {
                logger.info("Adding " + artifactPath.toString() + " because it doesn't exist.");
                artifactCollection.add(creator.createFromClassPathResource(artifactPath.toString(), resource));
            }
        } catch (java.io.IOException e) {
            throw new DeploymentException(e.getMessage());
        }
    }
    return artifactCollection;
}

From source file:ffx.xray.parsers.DiffractionFile.java

/**
 * read in a diffraction file based on the molecular assembly fileName,
using a weight of 1.0 and neutron value of false
 *
 * @param assembly {@link ffx.potential.MolecularAssembly} from which a
fileName will be determined//  w  w  w  .  ja  v a2s .c  om
 * @param weight the weight of the data
 * @param neutron if true, this is a neutron data set
 */
public DiffractionFile(MolecularAssembly assembly, double weight, boolean neutron) {
    String name = removeExtension(assembly.getFile().getPath());

    File tmp = new File(name + ".mtz");
    if (tmp.exists()) {
        //logger.info("\n Data file: " + tmp.getName());
        diffractionFilter = new MTZFilter();
    } else {
        tmp = new File(name + ".cif");
        if (tmp.exists()) {
            //logger.info("\n Data file: " + tmp.getName());
            diffractionFilter = new CIFFilter();
        } else {
            tmp = new File(name + ".ent");
            if (tmp.exists()) {
                //logger.info("\n Data file: " + tmp.getName());
                diffractionFilter = new CIFFilter();
            } else {
                tmp = new File(name + ".sf");
                if (tmp.exists()) {
                    //logger.info("\n Data file: " + tmp.getName());
                    diffractionFilter = new CIFFilter();
                } else {
                    tmp = new File(name + ".cns");
                    if (tmp.exists()) {
                        //logger.info("\n Data file: " + tmp.getName());
                        diffractionFilter = new CNSFilter();
                    } else {
                        tmp = new File(name + ".hkl");
                        if (tmp.exists()) {
                            //logger.info("\n Data file: " + tmp.getName());
                            diffractionFilter = new CNSFilter();
                        } else {
                            logger.severe("no input data found!");
                            diffractionFilter = null;
                        }
                    }
                }
            }
        }
    }
    String filenameHolder; // Compiler complains if I set this.fileName directly.
    try {
        Path filepath = Paths.get(tmp.getCanonicalPath());
        Path pwdPath = Paths.get(new File("").getCanonicalPath());
        filenameHolder = pwdPath.relativize(filepath).toString();
    } catch (IOException ex) {
        logger.warning(
                " Relative path to provided data file could not be resolved: using data file name instead.");
        filenameHolder = tmp.getName();
    }
    this.fileName = filenameHolder;
    this.weight = weight;
    this.neutron = neutron;
}

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

private String getAbsolutePath(final String relativePath) {
    final Path volumeIdentifier = Paths.get(HashedDirectoryServiceImpl.VOLUME_IDENTIFIER);
    final Path relative = Paths.get(relativePath);
    return new StringBuilder().append(temporaryFolder.getRoot().getAbsolutePath()).append("/").append("/")
            .append(volumeIdentifier.relativize(relative).toString()).toString();
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy every file of given {@code zipFile} beginning with given {@code zipSubPath} to {@code destDir}
 *
 * @param zipFile/*w  ww. ja  va 2 s. c o  m*/
 * @param zipSubPath must start with a "/"
 * @param destDir
 * @throws RuntimeIOException
 */
public static void unzipSubDirectoryIfExists(@Nonnull Path zipFile, @Nonnull String zipSubPath,
        @Nonnull final Path destDir) throws RuntimeIOException {
    Preconditions.checkArgument(zipSubPath.startsWith("/"), "zipSubPath '%s' must start with a '/'",
            zipSubPath);
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath(zipSubPath);
            if (Files.notExists(root)) {
                logger.trace("Zip sub path {} does not exist in {}", zipSubPath, zipFile);
                return;
            }

            //walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), root.relativize(file).toString());
                        logger.trace("Extract file {} to {} as {}", file, destDir, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' with root '" + root
                                + "' to destDir '" + destDir + "', ignore file", e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    dir.relativize(root).toString();
                    final Path dirToCreate = Paths.get(destDir.toString(), root.relativize(dir).toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubPath + " to " + destDir, e);
    }
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Before
public void setUp() throws IOException {
    IAndroidTarget target = SdkHelper.getTarget(23);
    assertThat(target).isNotNull();//from   w  ww . j  av  a2 s . c  om

    ApkManifest.Builder apkManifest = ApkManifest.newBuilder()
            .setAndroidSdk(ExternalBuildApkManifest.AndroidSdk.newBuilder()
                    .setAndroidJar(target.getFile(IAndroidTarget.ANDROID_JAR).getAbsolutePath())
                    // TODO: Start putting dx.jar in the proto
                    .setDx(SdkHelper.getDxJar().getAbsolutePath())
                    .setAapt(target.getBuildToolInfo().getPath(BuildToolInfo.PathId.AAPT)))
            .setResourceApk(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("resources.ap_"))
            .setAndroidManifest(
                    ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("AndroidManifest.xml"));

    List<String> jarFiles = new FileNameFinder().getFileNames(mProject.getTestDir().getAbsolutePath(),
            "**/*.jar");
    Path projectPath = mProject.getTestDir().toPath();
    for (String jarFile : jarFiles) {
        Path jarFilePath = new File(jarFile).toPath();
        Path relativePath = projectPath.relativize(jarFilePath);
        apkManifest
                .addJars(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath(relativePath.toString())
                        .setHash(ByteString.copyFromUtf8(String.valueOf(jarFile.hashCode()))));
    }

    manifestFile = mProject.file("apk_manifest.tmp");
    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(manifestFile))) {
        CodedOutputStream cos = CodedOutputStream.newInstance(os);
        apkManifest.build().writeTo(cos);
        cos.flush();
    }
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean archiveDirZip(final File dir, final File dest) {
    final Path dirPath = dir.toPath();
    final String parent = dir.getName();
    Map<String, String> env = Maps.newHashMap();
    env.put("create", "true");
    URI uri = dest.toURI();//w  w  w  .  jav  a 2 s  .  co m

    try {
        uri = new URI("jar:" + uri.getScheme(), uri.getPath(), null);
    } catch (Exception e) {
        return false;
    }

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Files.createDirectory(zipfs.getPath(parent));

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, zipfs.getPath(parent, dirPath.relativize(file).toString()),
                                StandardCopyOption.REPLACE_EXISTING);

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Files.createDirectory(zipfs.getPath(parent, dirPath.relativize(dir).toString()));

                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                Files.copy(file.toPath(), zipfs.getPath(parent, file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:nl.knaw.huygens.alexandria.dropwizard.cli.commands.AlexandriaCommand.java

private void putFileStatus(Path workDir, Path filePath, Multimap<FileStatus, String> fileStatusMap,
        CLIContext context, Set<String> watchedFiles) {
    String file = workDir.relativize(filePath).toString().replace("\\", "/");
    if (watchedFiles.contains(file)) {
        Instant lastCommit = context.getWatchedFiles().get(file).getLastCommit();
        try {// ww w .j a v a2 s.  c  o m
            Instant lastModified = Files.getLastModifiedTime(filePath).toInstant();
            FileStatus fileStatus = lastModified.isAfter(lastCommit) ? FileStatus.changed
                    : FileStatus.unchanged;
            fileStatusMap.put(fileStatus, file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        watchedFiles.remove(file);
    } else {
        fileStatusMap.put(FileStatus.created, file);
    }
}

From source file:com.redhat.plugin.eap6.AbstractEAP6Mojo.java

protected void addResourceDir(final File resDir) {
    if (addResourceFolder && resDir != null && resDir.exists()) {
        final Resource res = new Resource();
        final Path pathResourceDir = Paths.get(resDir.toURI());
        final Path pathProject = Paths.get(project.getBasedir().toURI());
        final Path pathRelativeDir = pathProject.relativize(pathResourceDir);
        final String stringRelativeDir = FilenameUtils.separatorsToUnix(pathRelativeDir.toString());
        res.setDirectory(stringRelativeDir);
        getLog().info("Adding dir <" + resDir.getPath() + "> as relative path <" + stringRelativeDir
                + "> to project-resources");
        if (project != null) {
            project.addResource(res);//from   w w  w.j a v a2 s  . co  m
        } else {
            getLog().warn("No project available, adding of resource-dir skipped");
        }
    }
}