Example usage for java.nio.file StandardCopyOption ATOMIC_MOVE

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

Introduction

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

Prototype

StandardCopyOption ATOMIC_MOVE

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

Click Source Link

Document

Move the file as an atomic file system operation.

Usage

From source file:at.alladin.rmbt.controlServer.QualityOfServiceExportResource.java

@Get
public Representation request(final String entity) {
    //Before doing anything => check if a cached file already exists and is new enough
    String property = System.getProperty("java.io.tmpdir");
    final File cachedFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML));
    final File generatingFile = new File(
            property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp");
    if (cachedFile.exists()) {

        //check if file has been recently created OR a file is currently being created
        if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())
                || (generatingFile.exists()
                        && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) {

            //if so, return the cached file instead of a cost-intensive new one
            final OutputRepresentation result = new OutputRepresentation(
                    zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) {

                @Override/*from   w  w w.java 2  s .  c om*/
                public void write(OutputStream out) throws IOException {
                    InputStream is = new FileInputStream(cachedFile);
                    IOUtils.copy(is, out);
                    out.close();
                }

            };
            if (zip) {
                final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
                disposition.setFilename(FILENAME_ZIP);
                result.setDisposition(disposition);
            }
            return result;

        }
    }

    //final List<String> data = new ArrayList<String>();
    final StringBuilder sb = new StringBuilder();
    QoSTestObjectiveDao nnObjectiveDao = new QoSTestObjectiveDao(conn);
    QoSTestDescDao nnDescDao = new QoSTestDescDao(conn, null);

    try {
        Map<String, List<QoSTestObjective>> map = nnObjectiveDao.getAllToMap();
        Iterator<String> keys = map.keySet().iterator();
        sb.append("<h1>Contents:</h1>");
        sb.append("<ol>");
        sb.append("<li><a href=\"#table1\">qos_test_objective</a></li>");
        sb.append("<li><a href=\"#table2\">qos_test_desc</a></li>");
        sb.append("</ol><br>");

        sb.append("<h1 id=\"table1\">Test objectives table (qos_test_objective)</h1>");
        while (keys.hasNext()) {
            String testType = keys.next();
            List<QoSTestObjective> list = map.get(testType);
            sb.append("<h2>Test group: " + testType.toUpperCase() + "</h2><ul>");
            //data.add("<h2>Test group: " + testType.toUpperCase() + "</h2>");
            for (QoSTestObjective item : list) {
                //data.add(item.toHtml());
                sb.append("<li>");
                sb.append(item.toHtml());
                sb.append("</li>");
            }
            sb.append("</ul>");
        }

        Map<String, List<QoSTestDesc>> descMap = nnDescDao.getAllToMapIgnoreLang();
        keys = descMap.keySet().iterator();
        sb.append("<h1 id=\"table2\">Language table (qos_test_desc)</h1><ul>");
        while (keys.hasNext()) {
            String descKey = keys.next();
            List<QoSTestDesc> list = descMap.get(descKey);
            sb.append("<li><h4 id=\"" + descKey.replaceAll("[\\-\\+\\.\\^:,]", "_")
                    + "\">KEY (column: desc_key): <i>" + descKey + "</i></h4><ul>");
            //data.add("<h3>KEY: <i>" + descKey + "</i></h3><ul>");
            for (QoSTestDesc item : list) {
                sb.append("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>");
                //data.add("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>");
            }
            sb.append("</ul></li>");
            //data.add("</ul>");
        }
        sb.append("</ul>");

    } catch (final SQLException e) {
        e.printStackTrace();
        return null;
    }

    final OutputRepresentation result = new OutputRepresentation(
            zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) {
        @Override
        public void write(OutputStream out) throws IOException {
            //cache in file => create temporary temporary file (to 
            // handle errors while fulfilling a request)
            String property = System.getProperty("java.io.tmpdir");
            final File cachedFile = new File(
                    property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp");
            OutputStream outf = new FileOutputStream(cachedFile);

            if (zip) {
                final ZipOutputStream zos = new ZipOutputStream(outf);
                final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt");
                zos.putNextEntry(zeLicense);
                final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt");
                IOUtils.copy(licenseIS, zos);
                licenseIS.close();

                final ZipEntry zeCsv = new ZipEntry(FILENAME_HTML);
                zos.putNextEntry(zeCsv);
                outf = zos;
            }

            try (OutputStreamWriter osw = new OutputStreamWriter(outf)) {
                osw.write(sb.toString());
                osw.flush();
            }

            if (zip)
                outf.close();

            //if we reach this code, the data is now cached in a temporary tmp-file
            //so, rename the file for "production use2
            //concurrency issues should be solved by the operating system
            File newCacheFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML));
            Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE,
                    StandardCopyOption.REPLACE_EXISTING);

            FileInputStream fis = new FileInputStream(newCacheFile);
            IOUtils.copy(fis, out);
            fis.close();
            out.close();
        }
    };
    if (zip) {
        final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(FILENAME_ZIP);
        result.setDisposition(disposition);
    }

    return result;
}

From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java

@Override
public void move(DavResource dest) throws DavException {
    final Path src = ResourcePathUtils.getPhysicalPath(this);
    final Path dst = ResourcePathUtils.getPhysicalPath(dest);
    try {// w w  w.  j a v  a  2  s  . c om
        // check for conflicts:
        if (Files.exists(dst)
                && Files.getLastModifiedTime(dst).toMillis() > Files.getLastModifiedTime(src).toMillis()) {
            throw new DavException(DavServletResponse.SC_CONFLICT,
                    "File at destination already exists: " + dst.toString());
        }

        // move:
        try {
            Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException e) {
            Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        LOG.error("Error moving file from " + src.toString() + " to " + dst.toString());
        throw new IORuntimeException(e);
    }
}

From source file:org.jahia.services.render.filter.StaticAssetsFilter.java

private static void atomicMove(File src, File dest) throws IOException {
    if (src.exists()) {
        // perform the file move
        try {//from w w  w .java  2s .co m
            Files.move(Paths.get(src.toURI()), Paths.get(dest.toURI()), StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception e) {
            logger.warn("Unable to move the file {} into {}. Copying it instead.", src, dest);
            try {
                FileUtils.copyFile(src, dest);
            } finally {
                FileUtils.deleteQuietly(src);
            }
        }
    }
}

From source file:org.artifactory.storage.db.binstore.service.DoubleFileBinaryProviderImpl.java

@Override
@Nonnull/*from  www  .ja  v  a2s .c  o  m*/
public BinaryInfo addStream(InputStream in) throws IOException {
    ProviderAndTempFile[] providerAndTempFiles = null;
    Sha1Md5ChecksumInputStream checksumStream = null;
    try {
        // first save to a temp file and calculate checksums while saving
        if (in instanceof Sha1Md5ChecksumInputStream) {
            checksumStream = (Sha1Md5ChecksumInputStream) in;
        } else {
            checksumStream = new Sha1Md5ChecksumInputStream(in);
        }
        providerAndTempFiles = writeToTempFile(checksumStream);
        BinaryInfo bd = new BinaryInfoImpl(checksumStream);
        log.trace("Inserting {} in file binary provider", bd);

        String sha1 = bd.getSha1();
        for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
            File tempFile = providerAndTempFile.tempFile;
            if (tempFile != null && providerAndTempFile.somethingWrong == null) {
                long fileLength = tempFile.length();
                if (fileLength != checksumStream.getTotalBytesRead()) {
                    throw new IOException("File length is " + fileLength + " while total bytes read on"
                            + " stream is " + checksumStream.getTotalBytesRead());
                }
                File file = providerAndTempFile.provider.getFile(sha1);
                Path target = file.toPath();
                if (!java.nio.file.Files.exists(target)) {
                    // move the file from the pre-filestore to the filestore
                    java.nio.file.Files.createDirectories(target.getParent());
                    try {
                        log.trace("Moving {} to {}", tempFile.getAbsolutePath(), target);
                        java.nio.file.Files.move(tempFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE);
                        log.trace("Moved  {} to {}", tempFile.getAbsolutePath(), target);
                    } catch (FileAlreadyExistsException ignore) {
                        // May happen in heavy concurrency cases
                        log.trace("Failed moving {} to {}. File already exist", tempFile.getAbsolutePath(),
                                target);
                    }
                    providerAndTempFile.tempFile = null;
                } else {
                    log.trace("File {} already exist in the file store. Deleting temp file: {}", target,
                            tempFile.getAbsolutePath());
                }
            }
        }
        return bd;
    } finally {
        IOUtils.closeQuietly(checksumStream);
        if (providerAndTempFiles != null) {
            for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
                File file = providerAndTempFile.tempFile;
                if (file != null && file.exists()) {
                    if (!file.delete()) {
                        log.error("Could not delete temp file {}", file.getAbsolutePath());
                    }
                }
            }
        }
    }
}

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

@Override
public void move(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("move: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath());

    try {//from w ww  .  j ava 2  s  .  c  o  m
        Files.move(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new GenericResourceException("cannot copy file", e);
    }
}

From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java

@Override
public void copy(DavResource dest, boolean shallow) throws DavException {
    final Path src = ResourcePathUtils.getPhysicalPath(this);
    final Path dst = ResourcePathUtils.getPhysicalPath(dest);
    try {/* w  w  w.  j av  a  2  s . com*/
        // check for conflicts:
        if (Files.exists(dst)
                && Files.getLastModifiedTime(dst).toMillis() > Files.getLastModifiedTime(src).toMillis()) {
            throw new DavException(DavServletResponse.SC_CONFLICT,
                    "File at destination already exists: " + dst.toString());
        }

        // copy:
        try {
            Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException e) {
            Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        LOG.error("Error copying file from " + src.toString() + " to " + dst.toString());
        throw new IORuntimeException(e);
    }
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public void deploy(String name) throws XMLConfigException, FileNotFoundException {

    Path configurationArchivePath = getConfigurationPath(name);

    Path current = Paths.get(XMLConfig.getBaseConfigPath());
    Path staging = current.getParent().resolve("deploy");
    Path destination = current.getParent().resolve(name);

    if (LOCK.tryLock()) {

        if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) {

            try {

                ZipInputStream configurationArchive = new ZipInputStream(
                        Files.newInputStream(configurationArchivePath, StandardOpenOption.READ));

                LOG.debug("Starting deploy of configuration " + name);
                ZipEntry zipEntry = null;

                for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) {

                    if (!Files.isDirectory(cfgFile)) {

                        Path target = staging.resolve(current.relativize(cfgFile));
                        Files.createDirectories(target);

                        Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING);
                    }//from w  ww  . j  a v  a 2  s  .  c  om

                }

                LOG.debug("Staging new config " + name);

                while ((zipEntry = configurationArchive.getNextEntry()) != null) {

                    Path entryPath = staging.resolve(zipEntry.getName());

                    LOG.debug("Adding resource: " + entryPath);
                    if (zipEntry.isDirectory()) {
                        entryPath.toFile().mkdirs();
                    } else {

                        Path parent = entryPath.getParent();
                        if (!Files.exists(parent)) {
                            Files.createDirectories(parent);
                        }

                        Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }

                }

                //**** Deleting old config dir
                LOG.debug("Removing old config: " + current);
                Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(java.nio.file.Path::toFile).forEach(File::delete);

                LOG.debug("Deploy new config " + name + " in path " + destination);
                Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE);

                setXMLConfigBasePath(destination.toString());
                LOG.debug("Deploy complete");
                deployListeners.forEach(l -> l.onDeploy(destination));

            } catch (Exception e) {

                if (Objects.nonNull(staging) && Files.exists(staging)) {
                    LOG.error("Deploy failed, rollback to previous configuration", e);
                    try {
                        Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                                .map(java.nio.file.Path::toFile).forEach(File::delete);

                        setXMLConfigBasePath(current.toString());
                    } catch (IOException | InvalidSyntaxException rollbackException) {
                        LOG.error("Failed to delete old configuration", e);
                    }
                } else {
                    LOG.error("Deploy failed", e);
                }

                throw new XMLConfigException("Deploy failed", e);
            } finally {
                LOCK.unlock();
            }
        } else {
            throw new FileNotFoundException(configurationArchivePath.toString());
        }
    } else {
        throw new IllegalStateException("A deploy is already in progress");
    }

}

From source file:password.pwm.config.stored.ConfigurationReader.java

public void saveConfiguration(final StoredConfigurationImpl storedConfiguration,
        final PwmApplication pwmApplication, final SessionLabel sessionLabel)
        throws IOException, PwmUnrecoverableException, PwmOperationalException {
    File backupDirectory = null;/*from  w ww.  ja  va2s .  c  o  m*/
    int backupRotations = 0;
    if (pwmApplication != null) {
        final Configuration configuration = new Configuration(storedConfiguration);
        final String backupDirSetting = configuration.readAppProperty(AppProperty.BACKUP_LOCATION);
        if (backupDirSetting != null && backupDirSetting.length() > 0) {
            final File pwmPath = pwmApplication.getPwmEnvironment().getApplicationPath();
            backupDirectory = FileSystemUtility.figureFilepath(backupDirSetting, pwmPath);
        }
        backupRotations = Integer.parseInt(configuration.readAppProperty(AppProperty.BACKUP_CONFIG_COUNT));
    }

    { // increment the config epoch
        String epochStrValue = storedConfiguration.readConfigProperty(ConfigurationProperty.CONFIG_EPOCH);
        try {
            final BigInteger epochValue = epochStrValue == null || epochStrValue.length() < 0 ? BigInteger.ZERO
                    : new BigInteger(epochStrValue);
            epochStrValue = epochValue.add(BigInteger.ONE).toString();
        } catch (Exception e) {
            LOGGER.error(sessionLabel,
                    "error trying to parse previous config epoch property: " + e.getMessage());
            epochStrValue = "0";
        }
        storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_EPOCH, epochStrValue);
    }

    if (backupDirectory != null && !backupDirectory.exists()) {
        if (!backupDirectory.mkdirs()) {
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN,
                    "unable to create backup directory structure '" + backupDirectory.toString() + "'"));
        }
    }

    try {
        final File tempWriteFile = new File(configFile.getAbsoluteFile() + ".new");
        LOGGER.info(sessionLabel, "beginning write to configuration file " + tempWriteFile);
        saveInProgress = true;

        storedConfiguration.toXml(new FileOutputStream(tempWriteFile, false));
        LOGGER.info("saved configuration " + JsonUtil.serialize(storedConfiguration.toJsonDebugObject()));
        if (pwmApplication != null) {
            final String actualChecksum = storedConfiguration.settingChecksum();
            pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.CONFIG_HASH, actualChecksum);
        }

        LOGGER.trace(
                "renaming file " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath());
        try {
            Files.move(tempWriteFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception e) {
            final String errorMsg = "unable to rename temporary save file from "
                    + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath() + "; error: "
                    + e.getMessage();
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
        }

        if (backupDirectory != null) {
            final String configFileName = configFile.getName();
            final String backupFilePath = backupDirectory.getAbsolutePath() + File.separatorChar
                    + configFileName + "-backup";
            final File backupFile = new File(backupFilePath);
            FileSystemUtility.rotateBackups(backupFile, backupRotations);
            storedConfiguration.toXml(new FileOutputStream(backupFile, false));
        }
    } finally {
        saveInProgress = false;
    }
}

From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java

private void createMavenInstallation(List<Repository> repositories, String version, File localrepo,
        File targetdir) throws Exception {
    String versionDir = "org/apache/maven/apache-maven/" + version + "/";
    String filename = "apache-maven-" + version + "-bin.tar.gz";
    File archive = new File(localrepo, versionDir + filename);
    if (archive.canRead()) {
        unarchive(archive, targetdir);/* w ww .  jav  a  2 s . com*/
        return;
    }
    Exception cause = null;
    for (Repository repository : repositories) {
        setHttpCredentials(repository.credentials);
        String effectiveVersion;
        if (isSnapshot(version)) {
            try {
                effectiveVersion = getQualifiedVersion(repository.url, versionDir);
            } catch (FileNotFoundException e) {
                continue;
            } catch (IOException e) {
                cause = e;
                continue;
            }
            if (effectiveVersion == null) {
                continue;
            }
        } else {
            effectiveVersion = version;
        }
        filename = "apache-maven-" + effectiveVersion + "-bin.tar.gz";
        archive = new File(localrepo, versionDir + filename);
        if (archive.canRead()) {
            unarchive(archive, targetdir);
            return;
        }
        URL resource = new URL(repository.url, versionDir + filename);
        try (InputStream is = openStream(resource)) {
            archive.getParentFile().mkdirs();
            File tmpfile = File.createTempFile(filename, ".tmp", archive.getParentFile());
            try {
                copy(is, tmpfile);
                unarchive(tmpfile, targetdir);
                Files.move(tmpfile.toPath(), archive.toPath(), StandardCopyOption.ATOMIC_MOVE,
                        StandardCopyOption.REPLACE_EXISTING);
            } finally {
                tmpfile.delete();
            }
            return;
        } catch (FileNotFoundException e) {
            // ignore the exception. this is expected to happen quite often and not a failure by iteself
        } catch (IOException e) {
            cause = e;
        }
    }
    Exception exception = new FileNotFoundException(
            "Could not download maven version " + version + " from any configured repository");
    exception.initCause(cause);
    throw exception;
}

From source file:com.twentyn.bioreactor.sensors.Sensor.java

private void atomicWrite(SensorData sensorData) throws IOException {
    // Write a sensor reading to a temporary file
    objectMapper.writeValue(sensorReadingTmp, sensorData);
    // Atomically move the temporary file once written to the location
    Files.move(sensorReadingTmp.toPath(), sensorReadingFilePath, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
    // Append sensor reading to log file
    objectMapper.writeValue(jsonGenerator, sensorData);
}