Java Code Examples for java.nio.file.Files.createSymbolicLink()

The following are Jave code examples for showing how to use createSymbolicLink() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: openjdk-jdk10   File: SymLinkTest.java   Source Code and License Vote up 8 votes
void test(Path base, String name) throws IOException {
    Path file = base.resolve(name);
    Path javaFile = base.resolve("HelloWorld.java");
    tb.writeFile(file,
            "public class HelloWorld {\n"
            + "    public static void main(String... args) {\n"
            + "        System.err.println(\"Hello World!\");\n"
            + "    }\n"
            + "}");

    try {
        Files.createSymbolicLink(javaFile, file.getFileName());
    } catch (FileSystemException fse) {
        System.err.println("warning: test passes vacuously, sym-link could not be created");
        System.err.println(fse.getMessage());
        return;
    }

    Path classes = Files.createDirectories(base.resolve("classes"));
    new JavacTask(tb)
        .outdir(classes)
        .files(javaFile)
        .run()
        .writeAll();
}
 
Example 2
Project: openjdk-jdk10   File: LinksTest.java   Source Code and License Vote up 7 votes
public static void main(String... args) throws Exception {
    ToolBox tb = new ToolBox();
    tb.writeFile("tmp/B.java", BSrc);

    // Try to set up a symbolic link for the test.
    try {
        Files.createSymbolicLink(Paths.get("a"), Paths.get("tmp"));
        System.err.println("Created symbolic link");
    } catch (UnsupportedOperationException | IOException e) {
        System.err.println("Problem creating symbolic link: " + e);
        System.err.println("Test cannot continue; test passed by default");
        return;
    }

    // If symbolic link was successfully created,
    // try a compilation that will use it.
    new JavacTask(tb)
            .sourcepath(".")
            .outdir(".")
            .sources(TSrc)
            .run()
            .writeAll();
}
 
Example 3
Project: incubator-netbeans   File: FileObjectCyclicSymlinksTest.java   Source Code and License Vote up 7 votes
/**
 * Test directory tree with a indirect cyclic link.
 * <pre>
 *  a
 *    b
 *      c ( -> a)
 *    d
 *      e ( -> c)
 * </pre>
 *
 * @throws java.io.IOException
 */
public void testIndirectSymbolicLink() throws IOException {
    File a = new File(getWorkDir(), "a");
    File b = new File(a, "b");
    File c = new File(b, "c");
    File d = new File(a, "d");
    File e = new File(d, "e");
    assertTrue(b.mkdirs());
    assertTrue(d.mkdirs());
    try {
        Files.createSymbolicLink(c.toPath(), a.toPath());
        Files.createSymbolicLink(e.toPath(), c.toPath());
        FileObject fo = FileUtil.toFileObject(getWorkDir());
        assertEquals(3, countRecursiveChildren(fo));
    } catch (IOException ex) {
        printSkipped();
    }
}
 
Example 4
Project: guava-mock   File: MoreFilesTest.java   Source Code and License Vote up 6 votes
public void testEqual_links() throws IOException {
  try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) {
    Path fooPath = fs.getPath("foo");
    MoreFiles.asCharSink(fooPath, UTF_8).write("foo");

    Path fooSymlink = fs.getPath("symlink");
    Files.createSymbolicLink(fooSymlink, fooPath);

    Path fooHardlink = fs.getPath("hardlink");
    Files.createLink(fooHardlink, fooPath);

    assertThat(MoreFiles.equal(fooPath, fooSymlink)).isTrue();
    assertThat(MoreFiles.equal(fooPath, fooHardlink)).isTrue();
    assertThat(MoreFiles.equal(fooSymlink, fooHardlink)).isTrue();
  }
}
 
Example 5
Project: Open-DM   File: FileSystemAdapter.java   Source Code and License Vote up 6 votes
public void mkSymlink(String symlinkName, String symlinkTarget) throws StorageAdapterException {
    try {
        File link = new File(symlinkName);
        File target = new File(symlinkTarget);

        mkParentDirs(link); // make sure directory containing the link exists
        Files.createSymbolicLink(link.toPath(), target.toPath());
    } catch (Exception e) {
        String errMsg = e.getMessage();
        if (e instanceof FileAlreadyExistsException) {
            errMsg = "the file already exists";
        }
        errMsg = String.format("Error creating symlink %s to target %s: %s", symlinkName,
                               symlinkTarget, errMsg);
        LOG.log(Level.WARNING, errMsg, e);
        throw new StorageAdapterException(errMsg, e);
    }
}
 
Example 6
Project: googles-monorepo-demo   File: MoreFilesTest.java   Source Code and License Vote up 6 votes
public void testByteSource_size_ofSymlinkToRegularFile_nofollowLinks() throws IOException {
  try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) {
    Path file = fs.getPath("file");
    Files.write(file, new byte[10]);
    Path link = fs.getPath("link");
    Files.createSymbolicLink(link, file);

    ByteSource source = MoreFiles.asByteSource(link, NOFOLLOW_LINKS);

    assertThat(source.sizeIfKnown()).isAbsent();

    try {
      source.size();
      fail();
    } catch (IOException expected) {
    }
  }
}
 
Example 7
Project: incubator-netbeans   File: AddTest.java   Source Code and License Vote up 6 votes
public void testAddMissingSymlink () throws Exception {
    if (isWindows()) {
        return;
    }
    String path = "folder/file";
    File f = new File(workDir, path);
    
    // try with commandline client
    File link = new File(workDir, "link");
    Files.createSymbolicLink(Paths.get(link.getAbsolutePath()), Paths.get(path));
    getClient(workDir).add(new File[] { link }, NULL_PROGRESS_MONITOR);
    DirCacheEntry e = repository.readDirCache().getEntry(link.getName());
    assertEquals(FileMode.SYMLINK, e.getFileMode());
    assertEquals(0, e.getLength());
    ObjectReader reader = repository.getObjectDatabase().newReader();
    assertTrue(reader.has(e.getObjectId()));
    byte[] bytes = reader.open(e.getObjectId()).getBytes();
    assertEquals(path, RawParseUtils.decode(bytes));
    reader.release();
}
 
Example 8
Project: guava-mock   File: MoreFilesTest.java   Source Code and License Vote up 6 votes
public void testPredicates() throws IOException {
  Path file = createTempFile();
  Path dir = tempDir.resolve("dir");
  Files.createDirectory(dir);

  assertTrue(MoreFiles.isDirectory().apply(dir));
  assertFalse(MoreFiles.isRegularFile().apply(dir));

  assertFalse(MoreFiles.isDirectory().apply(file));
  assertTrue(MoreFiles.isRegularFile().apply(file));

  Path symlinkToDir = tempDir.resolve("symlinkToDir");
  Path symlinkToFile = tempDir.resolve("symlinkToFile");

  Files.createSymbolicLink(symlinkToDir, dir);
  Files.createSymbolicLink(symlinkToFile, file);

  assertTrue(MoreFiles.isDirectory().apply(symlinkToDir));
  assertFalse(MoreFiles.isRegularFile().apply(symlinkToDir));

  assertFalse(MoreFiles.isDirectory().apply(symlinkToFile));
  assertTrue(MoreFiles.isRegularFile().apply(symlinkToFile));

  assertFalse(MoreFiles.isDirectory(NOFOLLOW_LINKS).apply(symlinkToDir));
  assertFalse(MoreFiles.isRegularFile(NOFOLLOW_LINKS).apply(symlinkToFile));
}
 
Example 9
Project: incubator-netbeans   File: FileObjSymlinkTest.java   Source Code and License Vote up 6 votes
/**
 * Test isRecursiveSymbolicLink method. Use this folder tree:
 * <pre>
 * - workdir
 *   - a
 *     - b
 *       - c (symlink to d)
 *   - d (symlink to a)
 * </pre>
 *
 * @throws java.io.IOException
 */
public void testIsRecursiveSymbolicLinkIndirect() throws IOException {
    if (!checkSymlinksSupported()) {
        return;
    }
    File dir = getWorkDir();
    File a = new File(dir, "a");
    File b = new File(a, "b");
    File c = new File(b, "c");
    File d = new File(dir, "d");
    b.mkdirs();
    Files.createSymbolicLink(d.toPath(), a.toPath());
    Files.createSymbolicLink(c.toPath(), d.toPath());
    FileObject dirFO = FileUtil.toFileObject(dir);
    FileObject cFO = dirFO.getFileObject("a/b/c");
    assertTrue(FileUtil.isRecursiveSymbolicLink(cFO));
}
 
Example 10
Project: incubator-netbeans   File: FileObjSymlinkTest.java   Source Code and License Vote up 6 votes
public void testReadSymbolicLinkRelative() throws IOException {
    if (!checkSymlinksSupported()) {
        return;
    }
    File dir = getWorkDir();
    File folder = new File(dir, "folder");
    File link = new File(dir, "link");
    folder.mkdir();
    Path lp = Files.createSymbolicLink(link.toPath(), Paths.get("folder"));
    assertNotNull(lp);
    FileObject linkFO = FileUtil.toFileObject(link);
    assertNotNull(linkFO);
    FileObject dataFO = linkFO.readSymbolicLink();
    assertNotSame(linkFO, dataFO);
    assertNotNull(dataFO);
    assertEquals("folder", dataFO.getNameExt());
}
 
Example 11
Project: incubator-netbeans   File: FileObjectCyclicSymlinksTest.java   Source Code and License Vote up 6 votes
/**
 * Test allowed (non-cyclic) symlink.
 * <pre>
 * a
 *   b
 *     c ( -> d)
 *   d
 *     e
 *       f
 * </pre>
 *
 * @throws java.io.IOException
 */
public void testAllowedSymbolicLink() throws IOException {
    File a = new File(getWorkDir(), "a");
    File b = new File(a, "b");
    File c = new File(b, "c");
    File d = new File(a, "d");
    File e = new File(d, "e");
    File f = new File(e, "f");
    assertTrue(b.mkdirs());
    assertTrue(f.mkdirs());
    try {
        Files.createSymbolicLink(c.toPath(), d.toPath());
        assertEquals(3, countRecursiveChildren(FileUtil.toFileObject(b)));
    } catch (IOException ex) {
        printSkipped();
    }
}
 
Example 12
Project: googles-monorepo-demo   File: MoreFilesTest.java   Source Code and License Vote up 5 votes
public void testByteSource_size_ofSymlinkToRegularFile() throws IOException {
  try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) {
    Path file = fs.getPath("file");
    Files.write(file, new byte[10]);
    Path link = fs.getPath("link");
    Files.createSymbolicLink(link, file);

    ByteSource source = MoreFiles.asByteSource(link);

    assertEquals(10L, (long) source.sizeIfKnown().get());
    assertEquals(10L, source.size());
  }
}
 
Example 13
Project: cyberduck   File: DefaultSymlinkFeature.java   Source Code and License Vote up 5 votes
@Override
public void symlink(final Local file, final String target) throws AccessDeniedException {
    try {
        Files.createSymbolicLink(Paths.get(file.getAbsolute()), Paths.get(target));
    }
    catch(IOException | UnsupportedOperationException e) {
        throw new AccessDeniedException(String.format("%s %s",
                LocaleFactory.localizedString("Cannot create file", "Error"), file.getAbsolute()), e);
    }
}
 
Example 14
Project: openjdk-jdk10   File: FaultyFileSystem.java   Source Code and License Vote up 5 votes
@Override
public void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs)
    throws IOException
{
    triggerEx(target, "createSymbolicLink");
    Files.createSymbolicLink(unwrap(link), unwrap(target), attrs);
}
 
Example 15
Project: guava-mock   File: MoreFilesTest.java   Source Code and License Vote up 5 votes
public void testByteSource_size_ofSymlinkToRegularFile() throws IOException {
  try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) {
    Path file = fs.getPath("file");
    Files.write(file, new byte[10]);
    Path link = fs.getPath("link");
    Files.createSymbolicLink(link, file);

    ByteSource source = MoreFiles.asByteSource(link);

    assertEquals(10L, (long) source.sizeIfKnown().get());
    assertEquals(10L, source.size());
  }
}
 
Example 16
Project: elasticsearch_my   File: PidFileTests.java   Source Code and License Vote up 5 votes
public void testPidFile() throws IOException {
    Path dir = createTempDir();
    Path parent = dir.resolve("foo");
    if (randomBoolean()) {
        Files.createDirectories(parent);
        if (randomBoolean()) {
            try {
                Path link = dir.resolve("link_to_real_path");
                Files.createSymbolicLink(link, parent.getFileName());
                parent = link;
            } catch (UnsupportedOperationException | IOException | SecurityException ex) {
               // fine - no links on this system
            }

        }
    }
    Path pidFile = parent.resolve("foo.pid");
    long pid = randomLong();
    if (randomBoolean() && Files.exists(parent)) {
        try (BufferedWriter stream = Files.newBufferedWriter(pidFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) {
            stream.write("foo");
        }
    }

    final PidFile inst = PidFile.create(pidFile, false, pid);
    assertEquals(pidFile, inst.getPath());
    assertEquals(pid, inst.getPid());
    assertFalse(inst.isDeleteOnExit());
    assertTrue(Files.exists(pidFile));
    assertEquals(pid, Long.parseLong(new String(Files.readAllBytes(pidFile), StandardCharsets.UTF_8)));
}
 
Example 17
Project: openjdk-jdk10   File: DefaultImageBuilder.java   Source Code and License Vote up 5 votes
private void writeSymLinkEntry(Path dstFile, Path target) throws IOException {
    Objects.requireNonNull(dstFile);
    Objects.requireNonNull(target);
    Files.createDirectories(Objects.requireNonNull(dstFile.getParent()));
    if (!isWindows() && root.getFileSystem()
                            .supportedFileAttributeViews()
                            .contains("posix")) {
        Files.createSymbolicLink(dstFile, target);
    } else {
        try (BufferedWriter writer = Files.newBufferedWriter(dstFile)) {
            writer.write(String.format("Please see %s%n", target.toString()));
        }
    }
}
 
Example 18
Project: openjdk-jdk10   File: DeleteOnClose.java   Source Code and License Vote up 4 votes
public static void runTest(Path path) throws Exception {
    // check temporary file has been deleted after jvm termination
    if (Files.exists(path)) {
        throw new RuntimeException("Temporary file was not deleted");
    }

    // check temporary file has been deleted after closing it
    Path file = Files.createTempFile("blep", "tmp");
    Files.newByteChannel(file, READ, WRITE, DELETE_ON_CLOSE).close();
    if (Files.exists(file))
        throw new RuntimeException("Temporary file was not deleted");

    Path dir = Files.createTempDirectory("blah");
    try {
        // check that DELETE_ON_CLOSE fails when file is a sym link
        if (TestUtil.supportsLinks(dir)) {
            file = dir.resolve("foo");
            Files.createFile(file);
            Path link = dir.resolve("link");
            Files.createSymbolicLink(link, file);
            try {
                Files.newByteChannel(link, READ, WRITE, DELETE_ON_CLOSE);
                throw new RuntimeException("IOException expected");
            } catch (IOException ignore) { }
        }

        // check that DELETE_ON_CLOSE works with files created via open
        // directories
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            if (stream instanceof SecureDirectoryStream) {
                SecureDirectoryStream<Path> secure = (SecureDirectoryStream<Path>)stream;
                file = Paths.get("foo");

                Set<OpenOption> opts = new HashSet<>();
                opts.add(WRITE);
                opts.add(DELETE_ON_CLOSE);
                secure.newByteChannel(file, opts).close();

                if (Files.exists(dir.resolve(file)))
                    throw new RuntimeException("File not deleted");
            }
        }
    } finally {
        TestUtil.removeAll(dir);
    }
}
 
Example 19
Project: googles-monorepo-demo   File: MoreFilesTest.java   Source Code and License Vote up 4 votes
public void testCreateParentDirectories_symlinkParentExists() throws IOException {
  Path symlink = tempDir.resolve("linkToDir");
  Files.createSymbolicLink(symlink, root());
  Path file = symlink.resolve("foo");
  MoreFiles.createParentDirectories(file);
}
 
Example 20
Project: incubator-netbeans   File: StatusTest.java   Source Code and License Vote up 4 votes
public void testSymlinkedFolder () throws Exception {
    File folder1 = new File(workDir, "boo");
    File file1 = new File(workDir, "old_file");
    File folder2 = new File(workDir, "some_dir");
    File file2_1 = new File(folder2, "some_file");
    
    folder1.mkdirs();
    folder2.mkdirs();
    file1.createNewFile();
    file2_1.createNewFile();
    add(workDir);
    commit(workDir);
    
    GitClient client = getClient(workDir);
    Map<File, GitStatus> statuses = client.getStatus(new File[0], NULL_PROGRESS_MONITOR);
    assertEquals(2, statuses.size());
    assertStatus(statuses, workDir, file1, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    assertStatus(statuses, workDir, file2_1, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
 
    // create a symlink, not added to index
    String relPath = "../some_dir";
    File link = new File(folder1, folder2.getName());
    Files.createSymbolicLink(Paths.get(link.getAbsolutePath()), Paths.get(relPath));
    assertTrue(Files.isSymbolicLink(Paths.get(link.getAbsolutePath())));
    statuses = client.getStatus(new File[] { link }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, link, false, Status.STATUS_NORMAL, Status.STATUS_ADDED, Status.STATUS_ADDED, false);
    
    // symlink is added to index, not yet committed
    client.add(new File[] { link }, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(new File[] { link }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, link, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    
    // symlink is committed
    client.commit(new File[] { link }, "commit symlink", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(new File[] { link }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, link, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // symlink is deleted on disk
    Files.delete(Paths.get(link.getAbsolutePath()));
    assertFalse(Files.isSymbolicLink(Paths.get(link.getAbsolutePath())));
    statuses = client.getStatus(new File[] { link }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, link, true, Status.STATUS_NORMAL, Status.STATUS_REMOVED, Status.STATUS_REMOVED, false);
    
    // symlink is also deleted from index
    client.remove(new File[] { link }, true, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(new File[] { link }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, link, true, Status.STATUS_REMOVED, Status.STATUS_NORMAL, Status.STATUS_REMOVED, false);
}