Example usage for java.nio.file StandardCopyOption COPY_ATTRIBUTES

List of usage examples for java.nio.file StandardCopyOption COPY_ATTRIBUTES

Introduction

In this page you can find the example usage for java.nio.file StandardCopyOption COPY_ATTRIBUTES.

Prototype

StandardCopyOption COPY_ATTRIBUTES

To view the source code for java.nio.file StandardCopyOption COPY_ATTRIBUTES.

Click Source Link

Document

Copy attributes to the new file.

Usage

From source file:com.excelsiorjet.api.util.Utils.java

public static void copyFile(Path source, Path target) throws IOException {
    if (!target.toFile().exists()) {
        Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
    } else if (source.toFile().lastModified() != target.toFile().lastModified()) {
        //copy only files that were changed
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
    }/*from   w  w w .  jav  a2 s  . c om*/

}

From source file:com.reactive.hzdfs.dll.JarFileSharingService.java

@Override
protected FileChunkHandler newWriteHandler(String dirPath) throws IOException {
    return new BufferedStreamChunkHandler(dirPath) {
        /**//from  w  ww.j  ava2  s  .c  o  m
         * Override the default behaviour to keep a backup
         * @throws IOException 
         */
        @Override
        protected void moveExistingFile() throws IOException {
            //super.moveExistingFile();

            try {
                if (file.exists()) {
                    Path fp = file.toPath();
                    Path backupFile = Files.move(fp,
                            fp.resolveSibling(file.getName() + ".bkp."
                                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())),
                            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                    log.info("Backup file created- " + backupFile);
                }

                file.createNewFile();
            } catch (IOException e) {
                log.warn("Backup not taken. Going with default replace and copy. error => " + e.getMessage());
                log.debug("", e);
                super.moveExistingFile();
            }

        }
    };
}

From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {
    SandboxedExecutor.logger.debug("Copying program into jail");
    final Path chrootedProgram = this.storage.getPath().resolve("chroot")
            .resolve(program.getFileName().toString());
    chrootedProgram.getParent().toFile().mkdirs();
    FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument(MessageFormat.format("--jail={0}",
            this.storage.getPath().resolve("chroot").toAbsolutePath().toString()));

    commandLine.addArgument("--");
    commandLine/*from   w w w.j  ava 2  s .  c om*/
            .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString());

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the
    // sandbox to
    // complete

    executor.setWorkingDirectory(this.storage.getPath().toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));

    SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString());
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        SandboxedExecutor.logger.info("Execution failed: {}", e);
        throw e;
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }

    return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt"));
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for changing file path")
public void testFileRename() throws IOException {
    try {//from   w  ww . j  av  a  2s  .com
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);

        BValue[] args = { new BString(tempSourcePath.toString()), new BString(tempDestPath.toString()) };
        BRunUtil.invoke(compileResult, "testRename", args);
        Assert.assertTrue(Files.exists(tempDestPath));
        assertFalse(Files.exists(tempSourcePath));
    } finally {
        Files.deleteIfExists(tempSourcePath);
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Before
public void prepare() throws Exception {
    workDir = temp.newFolder().toPath();
    Path srcDir = Paths.get("src/test/resources/CSharpSensorTest");
    Files.walk(srcDir).forEach(path -> {
        if (Files.isDirectory(path)) {
            return;
        }/* w w  w  .j av a 2 s . com*/
        Path relativized = srcDir.relativize(path);
        try {
            Path destFile = workDir.resolve(relativized);
            if (!Files.exists(destFile.getParent())) {
                Files.createDirectories(destFile.getParent());
            }
            Files.copy(path, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    });
    File csFile = new File("src/test/resources/Program.cs").getAbsoluteFile();

    EncodingInfo msg = EncodingInfo.newBuilder().setEncoding("UTF-8").setFilePath(csFile.getAbsolutePath())
            .build();
    try (OutputStream output = Files.newOutputStream(workDir.resolve("output-cs\\encoding.pb"))) {
        msg.writeDelimitedTo(output);
    } catch (IOException e) {
        throw new IllegalStateException("could not save message to file", e);
    }

    Path roslynReport = workDir.resolve("roslyn-report.json");
    Files.write(roslynReport,
            StringUtils
                    .replace(new String(Files.readAllBytes(roslynReport), StandardCharsets.UTF_8), "Program.cs",
                            StringEscapeUtils.escapeJavaScript(csFile.getAbsolutePath()))
                    .getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.WRITE);

    tester = SensorContextTester.create(new File("src/test/resources"));
    tester.fileSystem().setWorkDir(workDir.toFile());

    inputFile = new DefaultInputFile(tester.module().key(), "Program.cs").setLanguage(CSharpPlugin.LANGUAGE_KEY)
            .initMetadata(new FileMetadata().readMetadata(new FileReader(csFile)));
    tester.fileSystem().add(inputFile);

    fileLinesContext = mock(FileLinesContext.class);
    fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(inputFile)).thenReturn(fileLinesContext);

    extractor = mock(SonarAnalyzerScannerExtractor.class);
    when(extractor.executableFile(CSharpPlugin.LANGUAGE_KEY))
            .thenReturn(new File(workDir.toFile(), SystemUtils.IS_OS_WINDOWS ? "fake.bat" : "fake.sh"));

    noSonarFilter = mock(NoSonarFilter.class);
    settings = new Settings();

    CSharpConfiguration csConfigConfiguration = new CSharpConfiguration(settings);
    sensor = new CSharpSensor(settings, extractor, fileLinesContextFactory, noSonarFilter,
            csConfigConfiguration,
            new EncodingPerFile(
                    ProjectDefinition.create().setProperty(CoreProperties.ENCODING_PROPERTY, "UTF-8"),
                    new SonarQubeVersion(tester.getSonarQubeVersion())));
}

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/*w ww  .  ja  va  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:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for changing file path to already existing file path")
public void testFileRenameWithInvalidPath() throws IOException {
    try {// w  w  w.  j  a  v a 2 s.c o m
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
        Files.copy(srcFilePath, tempDestPath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);

        BValue[] args = { new BString(tempSourcePath.toString()), new BString(tempDestPath.toString()) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testRename", args);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}OPERATION_FAILED");
        log.info("Ballerina error: " + error.getDetails().stringValue());
    } finally {
        Files.deleteIfExists(tempSourcePath);
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:misc.FileHandler.java

/**
 * Copies the source file with the given options to the target file. The
 * source is first copied to the system's default temporary directory and
 * the temporary copy is then moved to the target file. In order to avoid
 * performance problems, the file is directly copied from the source to a
 * temporary file in the target directory first, if the temporary directory
 * and the target file lie on a different <code>FileStore</code>. The
 * temporary file is also moved to the target file.
 * //from w ww. ja v  a2s . c o m
 * @param source
 *            the file to copy.
 * @param target
 *            the target location where the file should be stored. Must not
 *            be identical with source. The file might or might not exist.
 *            The parent directory must exist.
 * @param replaceExisting
 *            <code>true</code>, if the target file may be overwritten.
 *            Otherwise, <code>false</code>.
 * @return <code>true</code>, if the file was successfully copied.
 *         Otherwise, <code>false</code>.
 */
public static boolean copyFile(Path source, Path target, boolean replaceExisting) {
    if ((source == null) || !Files.isReadable(source)) {
        throw new IllegalArgumentException("source must exist and be readable!");
    }
    if (target == null) {
        throw new IllegalArgumentException("target may not be null!");
    }
    if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) {
        throw new IllegalArgumentException("source and target must not match!");
    }

    boolean success = false;
    Path tempFile = null;

    target = target.normalize();

    try {
        tempFile = FileHandler.getTempFile(target);

        if (tempFile != null) {
            Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
            if (replaceExisting) {
                Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.move(tempFile, target);
            }
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (tempFile != null) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException eDelete) {
                Logger.logError(eDelete);
            }
        }
    }

    return success;
}

From source file:com.reactive.hzdfs.dll.JarFileSharingService.java

private void moveToExtLibDir(File file) throws IOException {
    Files.move(file.toPath(), Paths.get(extLib).resolve(file.getName()), StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.ATOMIC_MOVE);

}

From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

@Test
public void testInstallCustomExtensionTwiceDontOverwrite() throws Exception {
    String jarName = _sampleCommandJarFile.getName();

    File extensionJar = new File(_extensionsDir, jarName);

    String[] args = { "extension", "install", _sampleCommandJarFile.getAbsolutePath() };

    Path extensionPath = extensionJar.toPath();

    BladeTestResults bladeTestResults = TestUtil.runBlade(_rootDir, _extensionsDir, args);

    String output = bladeTestResults.getOutput();

    _testJarsDiff(_sampleCommandJarFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"successful\"\n" + output, output.contains(" successful"));
    Assert.assertTrue(output.contains(jarName));

    File tempDir = temporaryFolder.newFolder("overwrite");

    Path tempPath = tempDir.toPath();

    Path sampleCommandPath = tempPath.resolve(_sampleCommandJarFile.getName());

    Files.copy(_sampleCommandJarFile.toPath(), sampleCommandPath, StandardCopyOption.COPY_ATTRIBUTES,
            StandardCopyOption.REPLACE_EXISTING);

    File sampleCommandFile = sampleCommandPath.toFile();

    sampleCommandFile.setLastModified(0);

    args = new String[] { "extension", "install", sampleCommandFile.getAbsolutePath() };

    output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "n");

    Assert.assertTrue("Expected output to contain \"already exists\"\n" + output,
            output.contains(" already exists"));
    Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output,
            output.contains(" installed successfully"));

    Assert.assertTrue(sampleCommandFile.lastModified() == 0);

    File extensionFile = extensionPath.toFile();

    Assert.assertFalse(extensionFile.lastModified() == 0);

    output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "defaultShouldBeNo");

    Assert.assertFalse(extensionFile.lastModified() == 0);
    Assert.assertTrue("Expected output to contain \"already exists\"\n" + output,
            output.contains(" already exists"));
    Assert.assertFalse("Expected output to not contain \"Overwriting\"\n" + output,
            output.contains("Overwriting"));
    Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output,
            output.contains(" installed successfully"));
}