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:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java

private void moveDirectory(final File existingDB, final File newDB) throws IOException {
    LOGGER.info("[" + getClass().getSimpleName() + "] Moving Location database from: " + newDB + ", to: "
            + existingDB);/*from w  w w. j a v a2  s .c  om*/

    for (final File file : existingDB.listFiles()) {
        file.setReadable(true, true);
        file.setWritable(true, false);
        file.delete();
    }

    existingDB.delete();
    Files.move(newDB.toPath(), existingDB.toPath(), StandardCopyOption.ATOMIC_MOVE);
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectory.java

/**
 * Saves the file to disk along with corresponding expiration date file.
 * @param fileName the name of the file to save
 * @param content the content of the file
 * @param expirationDate the file expiration date
 * @throws Exception if an error occurs//  w w w . j av a 2  s.c o m
 */
public static final void save(Path fileName, byte[] content, ConfigurationPartMetadata expirationDate)
        throws Exception {
    if (fileName == null) {
        return;
    }

    Path parent = fileName.getParent();
    if (parent != null) {
        Files.createDirectories(parent);
    }

    log.info("Saving content to file {}", fileName);

    // save the content to disk
    AtomicSave.execute(fileName.toString(), "conf", content, StandardCopyOption.ATOMIC_MOVE);

    // save the content metadata date to disk
    saveMetadata(fileName, expirationDate);
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDirectory.java

/**
 * Saves the expiration date for the given file.
 * @param fileName the file/*from   w  ww  .  j a v a  2 s  .c om*/
 * @param metadata the metadata
 * @throws Exception if an error occurs
 */
public static final void saveMetadata(Path fileName, ConfigurationPartMetadata metadata) throws Exception {
    AtomicSave.execute(fileName.toString() + METADATA_SUFFIX, "expires", metadata.toByteArray(),
            StandardCopyOption.ATOMIC_MOVE);
}

From source file:femr.business.services.PhotoService.java

private void saveNewEncounterImage(FilePart image, PatientEncounterItem patientEncounter,
        String descriptionText) {
    try {//  w w  w  . jav  a 2 s  .c  o m
        String imageFileName;

        //Create photo record:
        IPhoto pPhoto = new Photo();
        pPhoto.setDescription(descriptionText);
        pPhoto.setFilePath("");
        pPhoto = patientPhotoRepository.create(pPhoto);

        ExpressionList<Photo> findPhotoQuery = QueryProvider.getPhotoQuery().where().eq("id", pPhoto.getId());
        IPhoto editPhoto = patientPhotoRepository.findOne(findPhotoQuery);

        imageFileName = "Patient_" + patientEncounter.getPatientId() + "_Enc_" + patientEncounter.getId()
                + "_Photo_" + editPhoto.getId();
        editPhoto.setFilePath(imageFileName);

        //Since the record ID is part of the file name
        //  I am setting the filePath field after the record is created
        patientPhotoRepository.update(editPhoto);

        //Link photo record in photoEncounter table
        IPatientEncounterPhoto pep = new PatientEncounterPhoto();
        pep.setPhotoId(editPhoto.getId());
        pep.setPatientEncounterId(patientEncounter.getId());
        patientEncounterPhotoRepository.create(pep);

        //Save image to disk
        Path src = FileSystems.getDefault().getPath(image.getFile().getAbsolutePath());
        Path dest = FileSystems.getDefault().getPath(this._encounterPhotoPath + imageFileName);
        java.nio.file.Files.move(src, dest, StandardCopyOption.ATOMIC_MOVE);
    } catch (Exception ex) {
        String test = "uh oh";

    }
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected void copyFile(SyncFile sourceSyncFile, SyncFile targetSyncFile) throws Exception {

    if (_logger.isDebugEnabled()) {
        _logger.debug("Copying file {} to {}", sourceSyncFile.getFilePathName(),
                targetSyncFile.getFilePathName());
    }/*  w w  w  . j a  v a2 s.c  om*/

    Path tempFilePath = FileUtil.getTempFilePath(targetSyncFile);

    Files.copy(Paths.get(sourceSyncFile.getFilePathName()), tempFilePath, StandardCopyOption.REPLACE_EXISTING);

    FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(targetSyncFile.getSyncFileId()), false);

    FileUtil.setModifiedTime(tempFilePath, targetSyncFile.getModifiedTime());

    Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

    watcher.addDownloadedFilePathName(targetSyncFile.getFilePathName());

    boolean exists = FileUtil.exists(Paths.get(targetSyncFile.getFilePathName()));

    try {
        Files.move(tempFilePath, Paths.get(targetSyncFile.getFilePathName()), StandardCopyOption.ATOMIC_MOVE,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (AccessDeniedException ade) {
        _logger.error(ade.getMessage(), ade);

        targetSyncFile.setState(SyncFile.STATE_ERROR);
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL);

        SyncFileService.update(targetSyncFile);

        return;
    }

    targetSyncFile.setState(SyncFile.STATE_SYNCED);

    if (GetterUtil.getBoolean(targetSyncFile.getLocalExtraSettingValue("restoreEvent"))) {

        targetSyncFile.unsetLocalExtraSetting("restoreEvent");

        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE);
    } else if (exists) {
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE);
    } else {
        targetSyncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW);
    }

    SyncFileService.update(targetSyncFile);

    IODeltaUtil.copyChecksums(sourceSyncFile, targetSyncFile);
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/**
 * Uses the given `http_client` to download `url` into `out_tmp`.
 * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field.
 * Returns a path to the renamed file./*from  w w  w  .  j ava  2  s .co m*/
 *
 * @param http_client synchronous interruptible HTTP client.
 * @param out_tmp download destination file on disk (will be created if does not exist).
 * @param url what to download.
 * @return Path to file with its actual name.
 * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field
 *       Content-Disposition is missing).
 * @throws InterruptedException Thread has been interrupted.
 */
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url)
        throws IOException, InterruptedException {
    try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {

        HttpResponse response = http_client.interruptibleGet(url, output);

        // If the response's status code is not 200, something wrong happened
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Formatter ff = new Formatter();
            ff.format(
                    "Synchronizer#%d cannot download product at %s,"
                            + " remote dhus returned message '%s' (HTTP%d)",
                    getId(), url, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode());
            throw new IOException(ff.out().toString());
        }

        // Gets the filename from the HTTP header field `Content-Disposition'
        Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE);
        String contdis = response.getFirstHeader("Content-Disposition").getValue();
        Matcher m = pat.matcher(contdis);
        if (!m.find()) {
            throw new IOException("Synchronizer#" + getId()
                    + " Missing HTTP header field `Content-Disposition` that determines the filename");
        }
        String filename = m.group(1);
        if (filename == null || filename.isEmpty()) {
            throw new IOException(
                    "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`");
        }

        // Renames the downloaded file
        output.close();
        Path dest = out_tmp.getParent().resolve(filename);
        Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE);

        DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(),
                response.getEntity().getContentLength());

        return res;
    } finally {
        if (Files.exists(out_tmp)) {
            Files.delete(out_tmp);
        }
    }
}

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

@Override
@Nonnull/*from   ww  w.  j a  v  a 2  s  .  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();
        boolean oneGoodMove = false;
        for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
            File tempFile = providerAndTempFile.tempFile;
            if (tempFile != null && providerAndTempFile.somethingWrong == null) {
                try {
                    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;
                        oneGoodMove = true;
                    } else {
                        log.trace("File {} already exist in the file store. Deleting temp file: {}", target,
                                tempFile.getAbsolutePath());
                    }
                } catch (IOException e) {
                    providerAndTempFile.somethingWrong = e;
                    providerAndTempFile.provider.markInactive(e);
                }
            }
        }
        if (!oneGoodMove) {
            StringBuilder msg = new StringBuilder("Could not move checksum file ").append(sha1)
                    .append(" to any filestore:\n");
            IOException oneEx = null;
            for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
                DynamicFileBinaryProviderImpl provider = providerAndTempFile.provider;
                msg.append("\t'").append(provider.getBinariesDir().getAbsolutePath()).append("' actif=")
                        .append(provider.isActive()).append("\n");
                if (providerAndTempFile.somethingWrong != null) {
                    oneEx = providerAndTempFile.somethingWrong;
                    msg.append("\t\tWith Exception:").append(providerAndTempFile.somethingWrong.getMessage());
                }
                msg.append("\n");
            }
            if (oneEx != null) {
                throw new IOException(msg.toString(), oneEx);
            } else {
                throw new IOException(msg.toString());
            }
        }
        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:at.alladin.rmbt.statisticServer.export.ExportResource.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 String filename_zip;
    final String filename_csv;

    //allow filtering by month/year
    int year = -1;
    int month = -1;
    int hours = -1;
    boolean hoursExport = false;
    boolean dateExport = false;

    if (getRequest().getAttributes().containsKey("hours")) { // export by hours
        try {//www  .jav  a  2s .  co  m
            hours = Integer.parseInt(getRequest().getAttributes().get("hours").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (hours <= 7 * 24 && hours >= 1) { //limit to 1 week (avoid DoS)
            hoursExport = true;
        }
    } else if (!hoursExport && getRequest().getAttributes().containsKey("year")) { // export by month/year 
        try {
            year = Integer.parseInt(getRequest().getAttributes().get("year").toString());
            month = Integer.parseInt(getRequest().getAttributes().get("month").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (year < 2099 && month > 0 && month <= 12 && year > 2000) {
            dateExport = true;
        }
    }

    if (hoursExport) {
        filename_zip = FILENAME_ZIP_HOURS.replace("%HOURS%", String.format("%03d", hours));
        filename_csv = FILENAME_CSV_HOURS.replace("%HOURS%", String.format("%03d", hours));
        cacheThresholdMs = 5 * 60 * 1000; //5 minutes
    } else if (dateExport) {
        filename_zip = FILENAME_ZIP.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        filename_csv = FILENAME_CSV.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        cacheThresholdMs = 23 * 60 * 60 * 1000; //23 hours
    } else {
        filename_zip = FILENAME_ZIP_CURRENT;
        filename_csv = FILENAME_CSV_CURRENT;
        cacheThresholdMs = 3 * 60 * 60 * 1000; //3 hours
    }

    final File cachedFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv));
    final File generatingFile = new File(
            property + File.separator + ((zip) ? filename_zip : filename_csv) + "_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_CSV) {

                @Override
                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 String timeClause;

    if (dateExport)
        timeClause = " AND (EXTRACT (month FROM t.time AT TIME ZONE 'UTC') = " + month
                + ") AND (EXTRACT (year FROM t.time AT TIME ZONE 'UTC') = " + year + ") ";
    else if (hoursExport)
        timeClause = " AND time > now() - interval '" + hours + " hours' ";
    else
        timeClause = " AND time > current_date - interval '31 days' ";

    final String sql = "SELECT" + " ('P' || t.open_uuid) open_uuid,"
            + " ('O' || t.open_test_uuid) open_test_uuid,"
            + " to_char(t.time AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') time_utc,"
            + " nt.group_name cat_technology," + " nt.name network_type,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_lat" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_lat*1111)/1111" + " ELSE null"
            + " END) lat,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_long" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_long*741)/741 " + " ELSE null"
            + " END) long," + " (CASE WHEN ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN"
            + " 'rastered'" + //make raster transparent
            " ELSE t.geo_provider" + " END) loc_src,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') "
            + " THEN round(t.geo_accuracy::float * 10)/10 "
            + " WHEN (t.geo_accuracy < 100) AND ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN 100"
            + // limit accuracy to 100m
            " WHEN (t.geo_accuracy < ?) THEN round(t.geo_accuracy::float * 10)/10"
            + " ELSE null END) loc_accuracy, "
            + " (CASE WHEN (t.zip_code < 1000 OR t.zip_code > 9999) THEN null ELSE t.zip_code END) zip_code,"
            + " t.gkz gkz," + " t.country_location country_location," + " t.speed_download download_kbit,"
            + " t.speed_upload upload_kbit," + " round(t.ping_median::float / 100000)/10 ping_ms,"
            + " t.lte_rsrp," + " t.lte_rsrq," + " ts.name server_name," + " duration test_duration,"
            + " num_threads," + " t.plattform platform," + " COALESCE(adm.fullname, t.model) model,"
            + " client_software_version client_version," + " network_operator network_mcc_mnc,"
            + " network_operator_name network_name," + " network_sim_operator sim_mcc_mnc," + " nat_type,"
            + " public_ip_asn asn," + " client_public_ip_anonymized ip_anonym,"
            + " (ndt.s2cspd*1000)::int ndt_download_kbit," + " (ndt.c2sspd*1000)::int ndt_upload_kbit,"
            + " COALESCE(t.implausible, false) implausible," + " t.signal_strength" + " FROM test t"
            + " LEFT JOIN network_type nt ON nt.uid=t.network_type"
            + " LEFT JOIN device_map adm ON adm.codename=t.model"
            + " LEFT JOIN test_server ts ON ts.uid=t.server_id" + " LEFT JOIN test_ndt ndt ON t.uid=ndt.test_id"
            + " WHERE " + " t.deleted = false" + timeClause + " AND status = 'FINISHED'" + " ORDER BY t.uid";

    final String[] columns;
    final List<String[]> data = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(sql);

        //insert filter for accuracy
        double accuracy = Double.parseDouble(settings.getString("RMBT_GEO_ACCURACY_DETAIL_LIMIT"));
        ps.setDouble(1, accuracy);
        ps.setDouble(2, accuracy);
        ps.setDouble(3, accuracy);
        ps.setDouble(4, accuracy);
        ps.setDouble(5, accuracy);
        ps.setDouble(6, accuracy);

        if (!ps.execute())
            return null;
        rs = ps.getResultSet();

        final ResultSetMetaData meta = rs.getMetaData();
        final int colCnt = meta.getColumnCount();
        columns = new String[colCnt];
        for (int i = 0; i < colCnt; i++)
            columns[i] = meta.getColumnName(i + 1);

        while (rs.next()) {
            final String[] line = new String[colCnt];

            for (int i = 0; i < colCnt; i++) {
                final Object obj = rs.getObject(i + 1);
                line[i] = obj == null ? null : obj.toString();
            }

            data.add(line);
        }
    } catch (final SQLException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }

    final OutputRepresentation result = new OutputRepresentation(
            zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) {
        @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_csv) + "_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_csv);
                zos.putNextEntry(zeCsv);
                outf = zos;
            }

            final OutputStreamWriter osw = new OutputStreamWriter(outf);
            final CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

            for (final String c : columns)
                csvPrinter.print(c);
            csvPrinter.println();

            for (final String[] line : data) {
                for (final String f : line)
                    csvPrinter.print(f);
                csvPrinter.println();
            }
            csvPrinter.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_csv));
            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:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java

private Path renameToTmpFilePath(Path sourceFilePath) throws IOException {
    String tmp_name = UUID.randomUUID() + "_" + sourceFilePath.getFileName().toString();
    Path new_path = sourceFilePath.resolveSibling(tmp_name);
    Files.move(sourceFilePath, new_path, StandardCopyOption.ATOMIC_MOVE);

    return new_path;
}

From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java

private Path renameFile(Path src, Path target) throws IOException {
    if (!target.equals(src)) {
        logger.info("Rename file from " + src + " to " + target);
        Files.move(src, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    }// w w w .j a va 2  s  .com

    return target;
}