Java Code Examples for java.nio.file.Path#relativize()

The following examples show how to use java.nio.file.Path#relativize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static void main(String[] args) { 

        Path path1 = Paths.get("JBossTools3.pdf");
        Path path2 = Paths.get("JavaModernChallenge.pdf");
        Path path3 = Paths.get("/learning/packt/2003/JBossTools3.pdf");
        Path path4 = Paths.get("/learning/packt/2019");

        Path path1ToPath2 = path1.relativize(path2);
        System.out.println("Path 1 to path 2: \n" + path1ToPath2);

        Path path2ToPath1 = path2.relativize(path1);
        System.out.println("\nPath 2 to path 1: \n" + path2ToPath1);

        Path path3ToPath4 = path3.relativize(path4);
        System.out.println("\nPath 3 to path 4: \n" + path3ToPath4);

        Path path4ToPath3 = path4.relativize(path3);
        System.out.println("\nPath 4 to path 3: \n" + path4ToPath3);
    }
 
Example 2
Source File: GitClone.java    From RepoSense with MIT License 6 votes vote down vote up
/**
 * Performs a full clone from {@code clonedBareRepoLocation} into the folder {@code outputFolderName} and
 * directly branches out to {@code targetBranch}.
 * @throws IOException if it fails to delete a directory.
 * @throws GitCloneException when an error occurs during command execution.
 */
public static void cloneFromBareAndUpdateBranch(Path rootPath, RepoConfiguration config)
        throws GitCloneException, IOException {
    Path relativePath = rootPath.relativize(FileUtil.getBareRepoPath(config));
    String outputFolderName = Paths.get(config.getRepoFolderName(), config.getRepoName()).toString();
    FileUtil.deleteDirectory(Paths.get(FileUtil.REPOS_ADDRESS, outputFolderName).toString());
    String command = String.format(
            "git clone %s --branch %s %s", relativePath, config.getBranch(), outputFolderName);
    try {
        runCommand(rootPath, command);
    } catch (RuntimeException rte) {
        logger.severe("Exception met while cloning or checking out " + config.getDisplayName() + "."
                + "Analysis terminated.");
        throw new GitCloneException(rte);
    }
}
 
Example 3
Source File: PathFileObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a PathFileObject whose binary name might be inferred from its
 * position on a search path.
 */
static PathFileObject createSimplePathFileObject(JavacPathFileManager fileManager,
        final Path path) {
    return new PathFileObject(fileManager, path) {
        @Override
        String inferBinaryName(Iterable<? extends Path> paths) {
            Path absPath = path.toAbsolutePath();
            for (Path p: paths) {
                Path ap = p.toAbsolutePath();
                if (absPath.startsWith(ap)) {
                    try {
                        Path rp = ap.relativize(absPath);
                        if (rp != null) // maybe null if absPath same as ap
                            return toBinaryName(rp);
                    } catch (IllegalArgumentException e) {
                        // ignore this p if cannot relativize path to p
                    }
                }
            }
            return null;
        }
    };
}
 
Example 4
Source File: PathFileObject.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a PathFileObject whose binary name might be inferred from its
 * position on a search path.
 */
static PathFileObject createSimplePathFileObject(JavacPathFileManager fileManager,
        final Path path) {
    return new PathFileObject(fileManager, path) {
        @Override
        String inferBinaryName(Iterable<? extends Path> paths) {
            Path absPath = path.toAbsolutePath();
            for (Path p: paths) {
                Path ap = p.toAbsolutePath();
                if (absPath.startsWith(ap)) {
                    try {
                        Path rp = ap.relativize(absPath);
                        if (rp != null) // maybe null if absPath same as ap
                            return toBinaryName(rp);
                    } catch (IllegalArgumentException e) {
                        // ignore this p if cannot relativize path to p
                    }
                }
            }
            return null;
        }
    };
}
 
Example 5
Source File: CopyNativeLibraries.java    From buck with Apache License 2.0 6 votes vote down vote up
static Step createMetadataStep(
    ProjectFilesystem filesystem, Path pathToMetadataTxt, Path pathToAllLibsDir) {
  return new AbstractExecutionStep("hash_native_libs") {
    @Override
    public StepExecutionResult execute(ExecutionContext context) throws IOException {
      ImmutableList.Builder<String> metadataLines = ImmutableList.builder();
      for (Path nativeLib : filesystem.getFilesUnderPath(pathToAllLibsDir)) {
        Sha1HashCode filesha1 = filesystem.computeSha1(nativeLib);
        Path relativePath = pathToAllLibsDir.relativize(nativeLib);
        metadataLines.add(String.format("%s %s", relativePath, filesha1));
      }
      filesystem.writeLinesToPath(metadataLines.build(), pathToMetadataTxt);
      return StepExecutionResults.SUCCESS;
    }
  };
}
 
Example 6
Source File: PathFileObject.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String inferBinaryName(Iterable<? extends Path> paths) {
    Path absPath = path.toAbsolutePath();
    for (Path p: paths) {
        Path ap = p.toAbsolutePath();
        if (absPath.startsWith(ap)) {
            try {
                Path rp = ap.relativize(absPath);
                if (rp != null) // maybe null if absPath same as ap
                    return toBinaryName(rp);
            } catch (IllegalArgumentException e) {
                // ignore this p if cannot relativize path to p
            }
        }
    }
    return null;
}
 
Example 7
Source File: ProjectInheritanceTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyRelativeExecutionRoot() throws Exception
{
    final File projectRoot = new File( System.getProperty( "user.dir" ), "pom.xml" );

    Path root = Paths.get( projectRoot.getParent() );
    Path absolute = Paths.get( projectRoot.toString() );
    Path relative = root.relativize( absolute );

    PomIO pomIO = new PomIO();

    List<Project> projects = pomIO.parseProject( relative.toFile() );

    assertEquals( 1, projects.size() );
    assertTrue( projects.get( 0 ).isExecutionRoot() );
}
 
Example 8
Source File: FileUtils.java    From karate with MIT License 5 votes vote down vote up
public static String toRelativeClassPath(Path path, ClassLoader cl) {
    if (isJarPath(path.toUri())) {
        return CLASSPATH_COLON + toStandardPath(path.toString());
    }
    for (URL url : getAllClassPathUrls(cl)) {
        Path rootPath = urlToPath(url, null);
        if (rootPath != null && path.startsWith(rootPath)) {
            Path relativePath = rootPath.relativize(path);
            return CLASSPATH_COLON + toStandardPath(relativePath.toString());
        }
    }
    // we didn't find this on the classpath, fall back to absolute
    return path.toString().replace('\\', '/');
}
 
Example 9
Source File: BuildFileManifestCache.java    From buck with Apache License 2.0 5 votes vote down vote up
private Invalidator(
    BuildFileManifestCache buildFileManifestCache,
    Path superRootPath,
    Path rootPath,
    Path buildFileName,
    ProjectFilesystemView fileSystemView) {
  this.buildFileManifestCache = buildFileManifestCache;
  this.superRootPath = superRootPath;
  this.rootPath = rootPath;
  this.buildFileName = buildFileName;
  this.fileSystemView = fileSystemView;

  rootToSuperRootRelativePath = superRootPath.relativize(rootPath);
}
 
Example 10
Source File: ResourceUtils.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public static Path getRelativePath(String resourcePath1, String resourcePath2) {
  	Path pathBase = Paths.get(resourcePath1);
  	Path pathAbsolute = Paths.get(resourcePath2);
  	
      Path result = pathBase.relativize(pathAbsolute);
return result;
  }
 
Example 11
Source File: FileSystemRepository.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void removeIncompleteContent(final String containerName, final Path containerPath, final Path fileToRemove) {
    if (Files.isDirectory(fileToRemove)) {
        final Path lastPathName = fileToRemove.subpath(1, fileToRemove.getNameCount());
        final String fileName = lastPathName.toFile().getName();
        if (fileName.equals(ARCHIVE_DIR_NAME)) {
            return;
        }

        final File[] children = fileToRemove.toFile().listFiles();
        if (children != null) {
            for (final File child : children) {
                removeIncompleteContent(containerName, containerPath, child.toPath());
            }
        }

        return;
    }

    final Path relativePath = containerPath.relativize(fileToRemove);
    final Path sectionPath = relativePath.subpath(0, 1);
    if (relativePath.getNameCount() < 2) {
        return;
    }

    final Path idPath = relativePath.subpath(1, relativePath.getNameCount());
    final String id = idPath.toFile().getName();
    final String sectionName = sectionPath.toFile().getName();

    final ResourceClaim resourceClaim = resourceClaimManager.newResourceClaim(containerName, sectionName, id, false, false);
    if (resourceClaimManager.getClaimantCount(resourceClaim) == 0) {
        removeIncompleteContent(fileToRemove);
    }
}
 
Example 12
Source File: PathParameterTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvert_relativePath_returnsOriginalFile() throws Exception {
  Path currentDirectory = Paths.get("").toAbsolutePath();
  Path file = Paths.get(folder.newFile().toString());
  Path relative = file.relativize(currentDirectory);
  assumeThat(relative, is(not(equalTo(file))));
  assumeThat(relative.toString(), startsWith("../"));
  Path converted = vanilla.convert(file.toString());
  assertThat((Object) converted).isEqualTo(file);
}
 
Example 13
Source File: ContentFilter.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean acceptFile(Path rootPath, Path file, InputStream in) throws IOException {
    Path relativePath = rootPath.relativize(file);
    if(this.depth < 0 || this.depth >= relativePath.getNameCount()) {
       if(archiveOnly) {
           if(in != null) {
               return PathUtil.isArchive(in);
           }
           return PathUtil.isArchive(file);
       }
       return true;
    }
    return false;
}
 
Example 14
Source File: TestDataUtils.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
public static <T extends NamedTest> List<T> loadJsonResourceFiles(String packageName, Class<T> cls) throws IOException {
  Preconditions.checkNotNull(packageName, "packageName cannot be null");
  Reflections reflections = new Reflections(packageName, new ResourcesScanner());
  Set<String> resources = reflections.getResources(new FilterBuilder.Include(".*"));
  List<T> datas = new ArrayList<>(resources.size());
  Path packagePath = Paths.get("/" + packageName.replace(".", "/"));
  for (String resource : resources) {
    log.trace("Loading resource {}", resource);
    Path resourcePath = Paths.get("/" + resource);
    Path relativePath = packagePath.relativize(resourcePath);
    File resourceFile = new File("/" + resource);
    T data;
    try (InputStream inputStream = cls.getResourceAsStream(resourceFile.getAbsolutePath())) {
      data = ObjectMapperFactory.INSTANCE.readValue(inputStream, cls);
    } catch (IOException ex) {
      if (log.isErrorEnabled()) {
        log.error("Exception thrown while loading {}", resourcePath, ex);
      }
      throw ex;
    }
    String nameWithoutExtension = Files.getNameWithoutExtension(resource);
    if (null != relativePath.getParent()) {
      String parentName = relativePath.getParent().getFileName().toString();
      data.testName(parentName + "/" + nameWithoutExtension);
    } else {
      data.testName(nameWithoutExtension);
    }
    datas.add(data);
  }
  return datas;
}
 
Example 15
Source File: FileUtils.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static File replaceParentInPath(@Nonnull final File oldParent, @Nonnull final File newParent, @Nonnull final File file) {
  final Path filePath = file.toPath();
  final Path oldParentPath = oldParent.toPath();
  final Path newParentPath = newParent.toPath();

  final Path relativePathInOld = oldParentPath.relativize(filePath);
  final Path newPath = newParentPath.resolve(relativePathInOld);

  return newPath.toFile();
}
 
Example 16
Source File: AbstractSassCompileTask.java    From GradleSassPlugin with Apache License 2.0 4 votes vote down vote up
private File getOutputFile(Path srcDirPath, File outputDir, File f) {
    Path relativePath = srcDirPath.relativize(f.toPath());
    return new File(outputDir,relativePath.toString().replaceAll("\\.scss",".css"));
}
 
Example 17
Source File: FileUtilTest.java    From copybara with Apache License 2.0 4 votes vote down vote up
@Test
public void testCopyMaterializeAbsolutePaths() throws Exception {
  Path one = Files.createDirectory(temp.resolve("one"));
  Path two = Files.createDirectory(temp.resolve("two"));
  Path absolute = touch(Files.createDirectory(temp.resolve("absolute")).resolve("absolute"));
  Path absoluteSymlink = Files.createSymbolicLink(
      temp.resolve("absolute").resolve("symlink"), absolute);

  Path absoluteDir = newTempDirectory("absoluteDir");
  Files.createDirectories(absoluteDir.resolve("absoluteDirDir"));
  Files.write(absoluteDir.resolve("absoluteDirElement"), "abc".getBytes(UTF_8));
  Files.write(absoluteDir.resolve("absoluteDirDir/element"), "abc".getBytes(UTF_8));

  FileUtil.addPermissions(touch(one.resolve("foo")),
      ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ));
  touch(one.resolve("some/folder/bar"));

  Files.createSymbolicLink(one.resolve("some/folder/baz"),
      one.getFileSystem().getPath("../../foo"));

  // Symlink to the root:
  Files.createSymbolicLink(one.resolve("dot"), one.getFileSystem().getPath("."));
  // Test multiple jumps inside the root: some/multiple -> folder/baz -> ../../foo
  Files.createSymbolicLink(one.resolve("some/multiple"),
      one.resolve("some").relativize(one.resolve("some/folder/baz")));

  Path folder = one.resolve("some/folder");
  Path absoluteTarget = folder.relativize(absolute);
  Files.createSymbolicLink(folder.resolve("absolute"), absoluteTarget);
  Path absoluteSymlinkTarget = folder.relativize(absoluteSymlink);
  Files.createSymbolicLink(folder.resolve("absoluteSymlink"), absoluteSymlinkTarget);
  // Multiple jumps of symlinks that ends out of the root
  Files.createSymbolicLink(folder.resolve("absolute2"),
      folder.relativize(folder.resolve("absolute")));

  // Symlink to a directory outside root
  Files.createSymbolicLink(folder.resolve("absolute3"), absoluteDir);

  FileUtil.copyFilesRecursively(one, two, CopySymlinkStrategy.MATERIALIZE_OUTSIDE_SYMLINKS);

  assertThatPath(two)
      .containsFile("foo", "abc")
      .containsFile("dot/foo", "abc")
      .containsFile("some/folder/bar", "abc")
      .containsFile("some/multiple", "abc")
      .containsFile("some/folder/absolute", "abc")
      .containsFile("some/folder/absoluteSymlink", "abc")
      .containsFile("some/folder/absolute2", "abc")
      .containsFile("some/folder/absolute3/absoluteDirElement", "abc")
      .containsFile("some/folder/absolute3/absoluteDirDir/element", "abc")
      .containsFile("some/folder/baz", "abc")
      .containsNoMoreFiles();

  assertThat(Files.isExecutable(two.resolve("foo"))).isTrue();
  assertThat(Files.isExecutable(two.resolve("foo"))).isTrue();
  assertThat(Files.isExecutable(two.resolve("some/folder/bar"))).isFalse();
  assertThat(Files.readSymbolicLink(two.resolve("some/folder/baz")).toString())
      .isEqualTo(two.getFileSystem().getPath("../../foo").toString());
  // Symlink to a directory inside the root are symlinked
  assertThat(Files.isSymbolicLink(two.resolve("dot"))).isTrue();
  assertThat(Files.isSymbolicLink(two.resolve("some/multiple"))).isTrue();
  // Anything outside of one/... is copied as a regular file
  assertThat(Files.isSymbolicLink(two.resolve("some/folder/absolute"))).isFalse();
  assertThat(Files.isSymbolicLink(two.resolve("some/folder/absoluteSymlink"))).isFalse();
  assertThat(Files.isSymbolicLink(two.resolve("some/folder/absolute2"))).isFalse();
  assertThat(Files.isSymbolicLink(two.resolve("some/folder/absolute3"))).isFalse();
}
 
Example 18
Source File: AbstractAsciiDocMojo.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
/**
 * Processes the AsciiDoctor file using a previously-created Asciidoctor
 * instance.
 *
 * @param asciiDoctor Asciidoctor instance (reusable for multiple files)
 * @param inputDirectory Path for the directory where the input file resides
 * @param adocFilePath Full Path for the input file
 * @throws IOException in case of I/O errors working with the files
 * @throws MojoFailureException in case the post-processing finds a user-correctable error
 * @throws MojoExecutionException in case the post-processing encounters a system error
 */
void processFile(
        Asciidoctor asciiDoctor,
        Path inputDirectory,
        Path adocFilePath,
        AtomicBoolean isPrelim) throws IOException, MojoFailureException, MojoExecutionException {

    Path relativeInputPath = inputDirectory.relativize(adocFilePath);
    Path outputPath = outputDirectory.toPath().resolve(relativeInputPath);

    getLog().info(String.format("processing %s to format '%s' in %s",
            adocFilePath.toString(),
            outputType(),
            outputPath.toString()));

    /*
     * Process the document once, suppressing the preprocessing,
     * to gather attributes that might be needed to resolve include
     * references during the second, real AsciiDoctor processing.
     */
    Map<String, Object> attributes = projectPropertiesMap(project);
    isPrelim.set(true);
    Document doc = asciiDoctor.loadFile(adocFilePath.toFile(),
            asciiDoctorOptions(
                    attributes,
                    relativeInputPath,
                    outputDirectory,
                    inputDirectory.toAbsolutePath(),
                    false));

    attributes.putAll(doc.getAttributes());

    isPrelim.set(false);
    asciiDoctor.loadFile(adocFilePath.toFile(),
            asciiDoctorOptions(
                    attributes,
                    relativeInputPath,
                    outputDirectory,
                    inputDirectory.toAbsolutePath(),
                    true));
    /*
     * We do not need to convert the document because the
     * preprocessor has written the updated version of the .adoc
     * file already and we do not need any rendered output as a
     * result of invoking this mojo.
     */

    postProcessFile(adocFilePath, outputPath);

}
 
Example 19
Source File: SourceCompilationUnit.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Compiles Java source files and write to the pre-specified path to the output jar. */
Path compile() throws IOException, SourceCompilationException {
  Path compilationStdOut = Files.createTempFile("compilation_stdout_", ".txt");
  Path compilationStdErr = Files.createTempFile("compilation_stderr_", ".txt");
  Path compiledRootDir = Files.createTempDirectory("compilation_prodout_");
  ImmutableList<String> javacOptions =
      ImmutableList.<String>builder()
          .addAll(customJavacOptions)
          .add("-d " + compiledRootDir)
          .build();
  final List<Path> compiledFiles;
  try (OutputStream stdOutStream = Files.newOutputStream(compilationStdOut);
      OutputStream stdErrStream = Files.newOutputStream(compilationStdErr)) {
    Splitter splitter = Splitter.on(" ").trimResults().omitEmptyStrings();
    ImmutableList<String> compilationArguments =
        ImmutableList.<String>builder()
            .addAll(splitter.split(String.join(" ", javacOptions)))
            .addAll(sourceInputs.stream().map(Path::toString).collect(Collectors.toList()))
            .build();
    compiler.run(
        nullInputStream(),
        stdOutStream,
        stdErrStream,
        compilationArguments.toArray(new String[0]));
    int maxDepth = sourceInputs.stream().mapToInt(Path::getNameCount).max().getAsInt();
    try (Stream<Path> outputStream =
        Files.find(compiledRootDir, maxDepth, (path, fileAttr) -> true)) {
      compiledFiles = outputStream.collect(Collectors.toList());
    }
    try (JarOutputStream jarOutputStream =
        new JarOutputStream(Files.newOutputStream(outputJar))) {
      for (Path compiledFile : compiledFiles) {
        try (InputStream inputStream = Files.newInputStream(compiledFile)) {
          Path inArchivalPath = compiledRootDir.relativize(compiledFile);
          JarEntry jarEntry = new JarEntry(inArchivalPath.toString());
          jarOutputStream.putNextEntry(jarEntry);
          if (!Files.isDirectory(compiledFile)) {
            ByteStreams.copy(inputStream, jarOutputStream);
          }
          jarOutputStream.closeEntry();
        }
      }
    }
  }
  String compilationStandardErrorMessage =
      new String(Files.readAllBytes(compilationStdErr), Charset.defaultCharset());
  if (!compilationStandardErrorMessage.isEmpty()) {
    throw new SourceCompilationException(compilationStandardErrorMessage);
  }
  return outputJar;
}
 
Example 20
Source File: FileService.java    From jlineup with Apache License 2.0 4 votes vote down vote up
public String getRelativePathFromReportDirToScreenshotsDir() {
    Path screenshotDirectory = getScreenshotDirectory().toAbsolutePath();
    Path reportDirectory = getReportDirectory().toAbsolutePath();
    Path relative = reportDirectory.relativize(screenshotDirectory);
    return relative.toString().equals("") ? "" : relative.toString() + FILE_SEPARATOR;
}