Example usage for java.nio.file LinkOption NOFOLLOW_LINKS

List of usage examples for java.nio.file LinkOption NOFOLLOW_LINKS

Introduction

In this page you can find the example usage for java.nio.file LinkOption NOFOLLOW_LINKS.

Prototype

LinkOption NOFOLLOW_LINKS

To view the source code for java.nio.file LinkOption NOFOLLOW_LINKS.

Click Source Link

Document

Do not follow symbolic links.

Usage

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiverTest.java

private PosixFileAttributes getPosixFileAttributes(File file) {
    try {//from  w ww .  j  a  va  2s  .c o m
        PosixFileAttributeView attributeView = Files.getFileAttributeView(file.toPath(),
                PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        return attributeView.readAttributes();
    } catch (Exception e) {
        Assume.assumeNoException("skip test on filesystems that do not support POSIX file attributes", e);
    }
    // never reached
    return null;
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java

/**
 * Creates test files with the given names in the specified directory resolved under ${ddf.home}
 * and adds their corresponding relativized from ${ddf.home} paths to the given list.
 *
 * <p><i>Note:</i> Each files will be created with the filename (no directory) as its content.
 *
 * @param paths a list of paths where to add all paths for the test files created
 * @param dir the directory where to create the test files
 * @param names the names of all test files to create in the specified directory
 * @return <code>paths</code> for chaining
 * @throws IOException if an I/O error occurs while creating the test files
 *//*from   ww  w  .  j a v  a  2  s  .  c  om*/
public List<Path> createFiles(List<Path> paths, Path dir, String... names) throws IOException {
    final File rdir = ddfHome.resolve(dir).toFile();

    rdir.mkdirs();
    for (final String name : names) {
        final File file = new File(rdir, name);

        FileUtils.writeStringToFile(file, name, Charsets.UTF_8);
        paths.add(ddfHome.relativize(file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS)));
    }
    return paths;
}

From source file:com.facebook.buck.util.unarchive.Unzip.java

private void extractDirectory(ExistingFileMode existingFileMode, SortedMap<Path, ZipArchiveEntry> pathMap,
        DirectoryCreator creator, Path target) throws IOException {
    ProjectFilesystem filesystem = creator.getFilesystem();
    if (filesystem.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) {
        // We have a pre-existing directory: delete its contents if they aren't in the zip.
        if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) {
            for (Path path : filesystem.getDirectoryContents(target)) {
                if (!pathMap.containsKey(path)) {
                    filesystem.deleteRecursivelyIfExists(path);
                }//from w ww .  j ava2 s.c  o m
            }
        }
    } else if (filesystem.exists(target, LinkOption.NOFOLLOW_LINKS)) {
        filesystem.deleteFileAtPath(target);
        creator.mkdirs(target);
    } else {
        creator.forcefullyCreateDirs(target);
    }
}

From source file:org.codice.ddf.configuration.migration.ExportMigrationContextImplTest.java

@Test
public void testGetSystemPropertyReferencedEntryWhenValueIsAbsoluteNotUnderDDFHome() throws Exception {
    final Path migratablePath = testFolder.newFile("test.cfg").toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);
    final String migratableName = FilenameUtils.separatorsToUnix(migratablePath.toString());

    System.setProperty(PROPERTY_NAME, migratablePath.toAbsolutePath().toString());

    final Optional<ExportMigrationEntry> oentry = context.getSystemPropertyReferencedEntry(PROPERTY_NAME,
            (r, v) -> true);//from w  w  w  . j a  v  a  2s .  c om

    Assert.assertThat(oentry, OptionalMatchers.isPresent());
    final ExportMigrationEntry entry = oentry.get();

    Assert.assertThat(entry.getId(), Matchers.equalTo(MIGRATABLE_ID));
    Assert.assertThat(entry.getName(), Matchers.equalTo(migratableName));
    Assert.assertThat(entry.getPath(), Matchers.equalTo(migratablePath));
    // now check that it is a system property referenced entry that references the proper property
    // name
    Assert.assertThat(entry, Matchers.instanceOf(ExportMigrationSystemPropertyReferencedEntryImpl.class));
    final ExportMigrationSystemPropertyReferencedEntryImpl sentry = (ExportMigrationSystemPropertyReferencedEntryImpl) entry;

    Assert.assertThat(sentry.getProperty(), Matchers.equalTo(PROPERTY_NAME));
    // finally make sure no warnings or errors were recorded
    Assert.assertThat(report.hasErrors(), Matchers.equalTo(false));
    Assert.assertThat(report.hasWarnings(), Matchers.equalTo(false));
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Recursively create directories for given user
 * //w  ww.j  ava2s.com
 * @param f
 * @param user
 * @param perms
 * @throws IOException
 */
public void mkdir(File f, UserPrincipal user, GroupPrincipal group, Set<PosixFilePermission> perms)
        throws IOException {
    if (!f.getParentFile().exists()) {
        mkdir(f.getParentFile(), user, group, perms);
    }

    logger.info("Create directory: " + f.getPath());
    f.mkdir();
    Files.setOwner(f.toPath(), user);
    Files.getFileAttributeView(f.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
            .setGroup(group);
    Files.setPosixFilePermissions(f.toPath(), perms);
}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public final File renameGrabbedDatafile(File file) throws QueueFileException {
    String extension = FilenameUtils.getExtension(file.toString());
    if (!extension.isEmpty()) {
        extension = "." + extension;
    }/*from   ww  w  .  j  a va2 s .com*/
    for (int i = 0; i < RETRY; i++) {
        File newFile = generateUniqueFile(extension, false);
        if (!file.renameTo(newFile)) {
            if (!Files.exists(newFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
                throw new QueueFileException("Unable to rename file or symlink " + file + " to " + newFile);
            }
        } else {
            return newFile;
        }
    }
    throw new QueueFileException(RETRY + " attempts to rename file / symlink failed!");
}

From source file:org.glite.authz.pep.pip.provider.InInfoFileIssuerDNMatcher.java

/**
 * Adds all .info files from the grid-security/certificates folder to the
 * variable infoFilesAll. As last the method returns a list containing
 * Strings. The Strings contain all *.info files.
 * //w w  w  .  j a v a 2  s .c  o  m
 * @return A list of strings. The strings represent *.info file.
 */
private List<String> findAllInfoFiles() throws IOException {
    List<String> infoFilesAll = new ArrayList<String>();
    DirectoryStream<Path> stream = null;
    try {
        stream = Files.newDirectoryStream(Paths.get(acceptedtrustInfoDir), "*.info");
    } catch (Exception e) {
        log.error(e.getMessage());
        return infoFilesAll;
    }

    try {
        for (Path entry : stream) {
            if (Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)) {
                infoFilesAll.add(entry.getFileName().toString());
            }
        }

    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        stream.close();
    }

    return infoFilesAll;
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 * //from  w  ww. j  a  va  2s  .  co  m
 * @param pathToProgramFile
 *            Where to look for the main file that will be compiled.
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @return List of string with the command for the process builder.
 */
private List<String> createCompilerInvocation(Path pathToProgramFile, String compilerName,
        List<String> compilerFlags) throws BadCompilerSpecifiedException, FileNotFoundException {

    List<String> compilerInvocation = new LinkedList<>();
    // We need a compiler name. Without it we cannot compile anything and
    // abort.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        // search for a makefile
        Path programDirectory = null;
        if (!Files.isDirectory(pathToProgramFile)) {
            programDirectory = pathToProgramFile.getParent();
        } else {
            programDirectory = pathToProgramFile;
        }
        Collection<File> fileList = FileUtils.listFiles(programDirectory.toFile(),
                FileFilterUtils.fileFileFilter(), null);

        boolean hasMakefile = false;
        for (File f : fileList) {
            if (f.getName().matches("[Mm][Aa][Kk][Ee][Ff][Ii][Ll][Ee]")) {
                hasMakefile = true;
            }
        }

        if (hasMakefile) {
            // add the necessary flags for make and return the invocation -
            // we don't need more flags or parameters
            LOGGER.info("Found make-file. Compiling c-code with make.");
            compilerInvocation.add("make");
            compilerInvocation.add("-k");
            compilerInvocation.add("-s");
            return compilerInvocation;
        } else {
            compilerInvocation.add(compilerName);
            LOGGER.info("Compiling c-code with " + compilerName);
        }
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing.
    if ((compilerFlags != null) && !(compilerFlags.isEmpty())) {
        if (!compilerFlags.contains("-c")) {
            compilerFlags.add("-c");
        }
        compilerInvocation.addAll(compilerFlags);
    }

    // Check for the existance of the program file we are trying to
    // compile.
    if ((pathToProgramFile == null) || (pathToProgramFile.compareTo(Paths.get("")) == 0)) {
        throw new FileNotFoundException("No file to compile specified");
    } else {

        if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // we have to be able to compile several .c files at the same
            // time so we need to find them
            RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.[Cc][Pp]?[Pp]?");
            try {
                Files.walkFileTree(pathToProgramFile, dirWalker);
            } catch (IOException e) {
                LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                        + " while building compiler invocation: " + e.getMessage());
            }
            for (Path matchedFile : dirWalker.getFoundFiles()) {
                compilerInvocation
                        .add(matchedFile.toString().substring(pathToProgramFile.toString().length() + 1));
            }
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToProgramFile.toString() + "\"");
        }
    }
    return compilerInvocation;
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }// w  ww.j  ava2  s  . c  om

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java

/**
 * Creates a test file with the given name in the specified directory resolved under ${ddf.home}.
 *
 * <p><i>Note:</i> The file will be created with the filename (no directory) as its content.
 *
 * @param dir the directory where to create the test file
 * @param name the name of the test file to create in the specified directory
 * @return a path corresponding to the test file created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test file
 *///from w  ww  . j a  v  a  2s.c o  m
public Path createFile(Path dir, String name) throws IOException {
    final File file = new File(ddfHome.resolve(dir).toFile(), name);

    dir.toFile().mkdirs();
    FileUtils.writeStringToFile(file, name, Charsets.UTF_8);
    final Path path = file.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS);

    return path.startsWith(ddfHome) ? ddfHome.relativize(path) : path;
}