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:org.ng200.openolympus.cerberus.executors.JavaExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {

    final Path chrootRoot = this.storage.getPath().resolve("chroot");

    final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString());

    FileAccess.createDirectories(chrootedProgram);
    FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES);

    final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory");

    final Path policyFile = this.storage.getPath().resolve("olymp.policy");

    try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) {
        paths.forEach(path -> {/*from   ww  w .  j  av  a 2 s . com*/
            try {
                Files.setPosixFilePermissions(path,
                        new HashSet<PosixFilePermission>(
                                Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                                        PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE,
                                        PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
                                        PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    this.buildPolicy(chrootRoot, policyFile);

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

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument("--security=0");
    commandLine.addArgument("--jail=/");

    commandLine.addArgument("--");

    commandLine.addArgument("/usr/bin/java");

    commandLine.addArgument("-classpath");
    commandLine.addArgument(chrootedProgram.toAbsolutePath().toString());
    commandLine.addArgument("-Djava.security.manager");
    commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString());

    commandLine.addArgument("-Xmx" + this.getMemoryLimit());
    commandLine.addArgument("-Xms" + this.getMemoryLimit());

    commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}",
            outOfMemoryFile.toAbsolutePath().toString()), false);

    commandLine.addArgument("Main");

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete
    executor.setWorkingDirectory(chrootRoot.toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));
    try {
        executor.execute(commandLine);
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }
    final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt"));

    if (FileAccess.exists(outOfMemoryFile)) {
        readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT);
    }

    readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit());

    return readOlrunnerVerdict;
}

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

@Test(description = "Test for removing file/directory from system")
public void testFileRemove() throws IOException {
    Path tempSourceDirPath = null;
    try {//ww  w  . ja  v  a 2s  . c  o m
        tempSourceDirPath = tempDirPath.resolve("src-dir");
        FileUtils.copyDirectory(srcDirPath.toFile(), tempSourceDirPath.toFile());
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
        // Remove source file
        BValue[] args = { new BString(tempSourcePath.toString()), new BBoolean(false) };
        BRunUtil.invoke(compileResult, "testRemove", args);
        assertFalse(Files.exists(tempSourcePath));

        // Remove directory with recursive false
        BValue[] args1 = { new BString(tempSourceDirPath.toString()), new BBoolean(false) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testRemove", args1);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}OPERATION_FAILED");
        log.info("Ballerina error: " + error.getDetails().stringValue());

        // Remove directory with recursive true
        BValue[] args2 = { new BString(tempSourceDirPath.toString()), new BBoolean(true) };
        returns = BRunUtil.invoke(compileResult, "testRemove", args2);
        assertNull(returns[0]);
        assertFalse(Files.exists(tempSourceDirPath));

    } finally {
        Files.deleteIfExists(tempSourcePath);
        if (tempSourceDirPath != null) {
            FileUtils.deleteDirectory(tempSourceDirPath.toFile());
        }
    }
}

From source file:org.apache.beam.sdk.io.LocalFileSystem.java

@Override
protected void copy(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds)
        throws IOException {
    checkArgument(srcResourceIds.size() == destResourceIds.size(),
            "Number of source files %s must equal number of destination files %s", srcResourceIds.size(),
            destResourceIds.size());//from www .java2s .co  m
    int numFiles = srcResourceIds.size();
    for (int i = 0; i < numFiles; i++) {
        LocalResourceId src = srcResourceIds.get(i);
        LocalResourceId dst = destResourceIds.get(i);
        LOG.debug("Copying {} to {}", src, dst);
        File parent = dst.getCurrentDirectory().getPath().toFile();
        if (!parent.exists()) {
            checkArgument(parent.mkdirs() || parent.exists(),
                    "Unable to make output directory %s in order to copy into file %s", parent, dst.getPath());
        }
        // Copy the source file, replacing the existing destination.
        // Paths.get(x) will not work on Windows OSes cause of the ":" after the drive letter.
        Files.copy(src.getPath(), dst.getPath(), StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
    }
}

From source file:org.openstreetmap.gui.persistence.JSONPersistence.java

/**
 * Make a backup of pFileName by copying it to the same directory, overriding any file of the same name. The backup
 * has the same name as the original file, with the extension .backup.
 * /*from ww w . j  av a  2 s  .  c o  m*/
 * @param pFileName
 *            The name of the file to back up.
 * @throws PersistenceException
 *             If the backup is not successful.
 */
public static void backup(String pFileName) {
    try {
        Files.copy(Paths.get(pFileName), Paths.get(pFileName + ".backup"), StandardCopyOption.COPY_ATTRIBUTES,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        throw new PersistenceException(exception);
    }
}

From source file:org.transitime.gtfs.GtfsUpdatedModule.java

/**
 * Copies the specified file to a directory at the same directory level but
 * with the directory name that is the last modified date of the file (e.g.
 * 03-28-2015).//from ww  w  .  j  a v  a  2 s . c  o  m
 * 
 * @param fullFileName
 *            The full name of the file to be copied
 */
private static void archive(String fullFileName) {
    // Determine name of directory to archive file into. Use date of
    // lastModified time of file e.g. MM-dd-yyyy.
    File file = new File(fullFileName);
    Date lastModified = new Date(file.lastModified());
    String dirName = Time.dateStr(lastModified);

    // Copy the file to the sibling directory with the name that is the
    // last modified date (e.g. 03-28-2015)
    Path source = Paths.get(fullFileName);
    Path target = source.getParent().getParent().resolve(dirName).resolve(source.getFileName());

    logger.info("Archiving file {} to {}", source.toString(), target.toString());

    try {
        // Create the directory where file is to go
        String fullDirName = target.getParent().toString();
        new File(fullDirName).mkdir();

        // Copy the file to the directory
        Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
    } catch (IOException e) {
        logger.error("Was not able to archive GTFS file {} to {}", source.toString(), target);
    }
}

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

@Test
public void testInstallCustomExtensionTwiceOverwrite() 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, "y");

    _testJarsDiff(sampleCommandFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"Overwrite\"\n" + output, output.contains("Overwrite"));
    boolean assertCorrect = output.contains(" installed successfully");

    if (!assertCorrect) {
        Assert.assertTrue("Expected output to contain \"installed successfully\"\n" + output, assertCorrect);
    }//from  ww w  .ja  va2s  .c o m

    File extensionFile = extensionPath.toFile();

    Assert.assertEquals(sampleCommandFile.lastModified(), extensionFile.lastModified());
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

@Override
public void copy(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx)
        throws BadContentException {

    String srcPathName = metadata.getAbsolutePath();
    Path srcPath = this.generateFileObj(srcPathName);
    Path dstPath = this.generateFileObj(dstDir);

    logger.debug("copy: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {/*  w w  w. j  av a 2 s .  co m*/
        Files.copy(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.COPY_ATTRIBUTES,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

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

@Override
public void getFile(final String name, final Path destination) throws IOException {
    FileAccess.copy(this.storage.getPath().resolve("chroot").resolve(name), destination,
            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}

From source file:de.dentrassi.rpm.builder.YumMojo.java

private void addSinglePackage(final Path path, final Context context) throws IOException {
    final String checksum = makeChecksum(path);
    final String fileName = path.getFileName().toString();
    final String location = "packages/" + fileName;
    final FileInformation fileInformation = new FileInformation(Files.getLastModifiedTime(path).toInstant(),
            Files.size(path), location);

    final RpmInformation rpmInformation;
    try (RpmInputStream ris = new RpmInputStream(Files.newInputStream(path))) {
        rpmInformation = RpmInformations.makeInformation(ris);
    }//from   w ww .ja  v a2  s  . com

    context.addPackage(fileInformation, rpmInformation, singletonMap(SHA256, checksum), SHA256);

    Files.copy(path, this.packagesPath.toPath().resolve(fileName), StandardCopyOption.COPY_ATTRIBUTES);
}

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

@Override
public void provideFile(final Path file) throws IOException {
    JavaExecutor.logger.info("Providing file {}", file);
    FileAccess.copy(file, this.storage.getPath().resolve("chroot").resolve(file.getFileName()),
            StandardCopyOption.COPY_ATTRIBUTES);
    this.readFiles.add(file.getFileName().toString());
}