Example usage for java.nio.file StandardCopyOption REPLACE_EXISTING

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

Introduction

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

Prototype

StandardCopyOption REPLACE_EXISTING

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

Click Source Link

Document

Replace an existing file if it exists.

Usage

From source file:org.apache.pulsar.client.admin.internal.FunctionsImpl.java

@Override
public void downloadFunction(String destinationPath, String path) throws PulsarAdminException {
    try {// ww  w.  j a v a 2 s . c om
        InputStream response = request(functions.path("download").queryParam("path", path))
                .get(InputStream.class);
        if (response != null) {
            File targetFile = new File(destinationPath);
            java.nio.file.Files.copy(response, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (Exception e) {
        throw getApiException(e);
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeq2GraphicsTopComponent.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") {
        private static final long serialVersionUID = 1L;

        @Override//from w  w w.  j ava2  s .  c om
        public void save(String fileLocation) {
            ProgressHandle progressHandle = ProgressHandleFactory
                    .createHandle("Save plot to svg file: " + fileLocation);
            Path to = FileSystems.getDefault().getPath(fileLocation, "");
            DeSeq2AnalysisHandler.Plot selectedPlot = (DeSeq2AnalysisHandler.Plot) plotType.getSelectedItem();
            Path from = currentlyDisplayed.toPath();
            try {
                Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                messages.setText("SVG image saved to " + outputFile.toString());
            } catch (IOException ex) {
                Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                        currentTimestamp);
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.",
                        JOptionPane.WARNING_MESSAGE);
            } finally {
                progressHandle.switchToDeterminate(100);
                progressHandle.finish();
            }

        }

        @Override
        public void open(String fileLocation) {
        }
    };
    fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG);
}

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

public void copyFiles() {
    if (!core.getDataFolder().exists()) {
        core.getDataFolder().mkdirs();// w  w w  . j  a v a 2s  . co m
    }
    if (!messagesFolder.exists()) {
        messagesFolder.mkdirs();
    }
    {
        File[] files = core.getDataFolder().listFiles();
        for (File f : files) {
            if (f.isFile() && f.getName().startsWith("messages")) {
                try {
                    Files.move(f.toPath(), new File(messagesFolder, f.getName()).toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException ex) {
                    Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE,
                            "An error has ocurred while moving messages files to the new messages folder.", ex);
                }
            }
        }
    }
    messagesFiles.keySet().forEach(filename -> {
        File messages = messagesFiles.get(filename);
        if (!messages.exists()) {
            copy(core.getResource(messages.getName()), messages);
        }
    });
    if (!configFile.exists()) {
        copy(core.getResource("config.yml"), configFile);
    }

}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void unzip(@Nonnull Path zipFile, @Nonnull final Path destDir) throws RuntimeIOException {
    try {//w  ww.j a v a2 s  .  c  o  m
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath("/");

            //walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), file.toString());
                        logger.trace("Extract file {} to {}", file, destDir);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' to '" + destDir + "', ignore file",
                                e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        try {
                            Files.createDirectory(dirToCreate);
                        } catch (IOException e) {
                            logger.warn("Exception creating directory '" + dirToCreate + "' for '" + dir
                                    + "', ignore dir subtree", e);
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + " to " + destDir, e);
    }
}

From source file:net.rptools.maptool.util.PersistenceUtil.java

public static void saveCampaign(Campaign campaign, File campaignFile) throws IOException {
    CodeTimer saveTimer; // FJE Previously this was 'private static' -- why?
    saveTimer = new CodeTimer("CampaignSave");
    saveTimer.setThreshold(5);/*from ww w .  j a  v a  2s  .c o m*/
    saveTimer.setEnabled(log.isDebugEnabled()); // Don't bother keeping track if it won't be displayed...

    // Strategy: save the file to a tmp location so that if there's a failure the original file
    // won't be touched. Then once we're finished, replace the old with the new.
    File tmpDir = AppUtil.getTmpDir();
    File tmpFile = new File(tmpDir.getAbsolutePath(), campaignFile.getName());
    if (tmpFile.exists())
        tmpFile.delete();

    PackedFile pakFile = null;
    try {
        pakFile = new PackedFile(tmpFile);
        // Configure the meta file (this is for legacy support)
        PersistedCampaign persistedCampaign = new PersistedCampaign();

        persistedCampaign.campaign = campaign;

        // Keep track of the current view
        ZoneRenderer currentZoneRenderer = MapTool.getFrame().getCurrentZoneRenderer();
        if (currentZoneRenderer != null) {
            persistedCampaign.currentZoneId = currentZoneRenderer.getZone().getId();
            persistedCampaign.currentView = currentZoneRenderer.getZoneScale();
        }
        // Save all assets in active use (consolidate duplicates between maps)
        saveTimer.start("Collect all assets");
        Set<MD5Key> allAssetIds = campaign.getAllAssetIds();
        for (MD5Key key : allAssetIds) {
            // Put in a placeholder; all we really care about is the MD5Key for now...
            persistedCampaign.assetMap.put(key, null);
        }
        saveTimer.stop("Collect all assets");

        // And store the asset elsewhere
        saveTimer.start("Save assets");
        saveAssets(allAssetIds, pakFile);
        saveTimer.stop("Save assets");

        try {
            saveTimer.start("Set content");
            pakFile.setContent(persistedCampaign);
            pakFile.setProperty(PROP_VERSION, MapTool.getVersion());
            pakFile.setProperty(PROP_CAMPAIGN_VERSION, CAMPAIGN_VERSION);
            saveTimer.stop("Set content");

            saveTimer.start("Save");
            pakFile.save();
            saveTimer.stop("Save");
        } catch (OutOfMemoryError oom) {
            /*
             * This error is normally because the heap space has been
             * exceeded while trying to save the campaign. Since MapTool
             * caches the images used by the current Zone, and since the
             * VersionManager must keep the XML for objects in memory in
             * order to apply transforms to them, the memory usage can spike
             * very high during the save() operation. A common solution is
             * to switch to an empty map and perform the save from there;
             * this causes MapTool to unload any images that it may have had
             * cached and this can frequently free up enough memory for the
             * save() to work. We'll tell the user all this right here and
             * then fail the save and they can try again.
             */
            saveTimer.start("OOM Close");
            pakFile.close(); // Have to close the tmpFile first on some OSes
            pakFile = null;
            tmpFile.delete(); // Delete the temporary file
            saveTimer.stop("OOM Close");
            if (log.isDebugEnabled()) {
                log.debug(saveTimer);
            }
            MapTool.showError("msg.error.failedSaveCampaignOOM");
            return;
        }
    } finally {
        saveTimer.start("Close");
        try {
            if (pakFile != null)
                pakFile.close();
        } catch (Exception e) {
        }
        saveTimer.stop("Close");
        pakFile = null;
    }

    /*
     * Copy to the new location. Not the fastest solution in the world if
     * renameTo() fails, but worth the safety net it provides. (Jamz had
     * issues with renameTo() keeping DropBox files locked on Windows.
     * Changed to use Files.move() from Java 7.)
     */
    saveTimer.start("Backup");
    File bakFile = new File(tmpDir.getAbsolutePath(), campaignFile.getName() + ".bak");
    bakFile.delete();
    if (campaignFile.exists()) {
        saveTimer.start("Backup campaign file: " + campaignFile);
        try {
            Files.move(campaignFile.toPath(), bakFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception ex) {
            try {
                FileUtil.copyFile(campaignFile, bakFile);
            } catch (Exception e) {
                MapTool.showError("msg.error.failedSaveCampaign");
                return;
            }
        } finally {
            saveTimer.stop("Backup campaign file: " + campaignFile);
        }
    }

    saveTimer.start("Backup tmpFile to campaign file");
    try {
        Files.move(tmpFile.toPath(), campaignFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        FileUtil.copyFile(campaignFile, bakFile);
        tmpFile.delete(); // Only delete if the copy didn't throw an exception
    }
    saveTimer.stop("Backup tmpFile to campaign file");
    bakFile.delete();
    saveTimer.stop("Backup");

    // Save the campaign thumbnail
    saveTimer.start("Thumbnail");
    saveCampaignThumbnail(campaignFile.getName());
    saveTimer.stop("Thumbnail");

    if (log.isDebugEnabled()) {
        log.debug(saveTimer);
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Test the reloading of SSLContext whose trust config is backed by PEM certificate files.
 */// w w w.  j a v  a2  s  .  co m
public void testReloadingPEMTrustConfig() throws Exception {
    Path tempDir = createTempDir();
    Path clientCertPath = tempDir.resolve("testnode.crt");
    Path keyStorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keyStorePath);
    //Our keystore contains two Certificates it can present. One build from the RSA keypair and one build from the EC keypair. EC is
    // used since it keyManager presents the first one in alias alphabetical order (and testnode_ec comes before testnode_rsa)
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_ec.crt"),
            clientCertPath);
    Settings settings = Settings.builder()
            .putList("xpack.ssl.certificate_authorities", clientCertPath.toString())
            .put("path.home", createTempDir()).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    // Create the MockWebServer once for both pre and post checks
    try (MockWebServer server = getSslServer(keyStorePath, "testnode")) {
        final Consumer<SSLContext> trustMaterialPreChecks = (context) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(context).build()) {
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                Path updatedCert = tempDir.resolve("updated.crt");
                Files.copy(getDataPath(
                        "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"),
                        updatedCert, StandardCopyOption.REPLACE_EXISTING);
                atomicMoveIfPossible(updatedCert, clientCertPath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // Client doesn't trust the Server certificate anymore so SSLHandshake should fail
        final Consumer<SSLContext> trustMaterialPostChecks = (updatedContext) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(updatedContext).build()) {
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path building failed"));
            } catch (Exception e) {
                throw new RuntimeException("Error closing CloseableHttpClient", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier,
                trustMaterialPostChecks);
    }
}

From source file:com.stimulus.archiva.store.MessageStore.java

public void backupMessage(File file) throws MessageStoreException {
    logger.debug("backupMessage()");
    File noArchiveFile = getNoArchiveFile();
    logger.warn("copying email to no archive queue {dest='" + noArchiveFile.getAbsolutePath() + "'}");

    //Mod start Seolhwa.kim 2017-04-13

    //boolean renamed = file.renameTo(noArchiveFile);

    boolean renamed;
    try {//from  w w  w  . j a v  a2  s  .  co  m
        Files.move(Paths.get(file.getAbsolutePath()), Paths.get(noArchiveFile.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING);
        renamed = true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        renamed = false;
        e.printStackTrace();
    }

    //Mod End Seolhwa.kim 2017-04-13

    if (!renamed) {
        throw new MessageStoreException("failed to copy message to noarchive queue", logger);
    }
}

From source file:de.fabianonline.telegram_backup.DownloadManager.java

private static boolean downloadFileFromDc(TelegramClient client, String target, TLAbsInputFileLocation loc,
        Integer dcID, int size) throws RpcErrorException, IOException {
    FileOutputStream fos = null;//from   ww w.jav a2 s  .  c  o  m
    try {
        String temp_filename = target + ".downloading";
        logger.debug("Downloading file {}", target);
        logger.trace("Temporary filename: {}", temp_filename);

        int offset = 0;
        if (new File(temp_filename).isFile()) {
            logger.info("Temporary filename already exists; continuing this file");
            offset = (int) new File(temp_filename).length();
            if (offset >= size) {
                logger.warn("Temporary file size is >= the target size. Assuming corrupt file & deleting it");
                new File(temp_filename).delete();
                offset = 0;
            }
        }
        logger.trace("offset before the loop is {}", offset);
        fos = new FileOutputStream(temp_filename, true);
        TLFile response;
        do {
            int block_size = size;
            logger.trace("offset: {} block_size: {} size: {}", offset, block_size, size);
            TLRequestUploadGetFile req = new TLRequestUploadGetFile(loc, offset, block_size);
            if (dcID == null) {
                response = (TLFile) download_client.executeRpcQuery(req);
            } else {
                response = (TLFile) download_client.executeRpcQuery(req, dcID);
            }

            offset += response.getBytes().getData().length;
            logger.trace("response: {} total size: {}", response.getBytes().getData().length, offset);

            fos.write(response.getBytes().getData());
            fos.flush();
            try {
                TimeUnit.MILLISECONDS.sleep(Config.DELAY_AFTER_GET_FILE);
            } catch (InterruptedException e) {
            }
        } while (offset < size && response.getBytes().getData().length > 0);
        fos.close();
        if (offset < size) {
            System.out.println("Requested file " + target + " with " + size + " bytes, but got only " + offset
                    + " bytes.");
            new File(temp_filename).delete();
            System.exit(1);
        }
        logger.trace("Renaming {} to {}", temp_filename, target);
        int rename_tries = 0;
        IOException last_exception = null;
        while (rename_tries <= Config.RENAMING_MAX_TRIES) {
            rename_tries++;
            try {
                Files.move(new File(temp_filename).toPath(), new File(target).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
                last_exception = null;
                break;
            } catch (IOException e) {
                logger.debug("Exception during move. rename_tries: {}. Exception: {}", rename_tries, e);
                last_exception = e;
                try {
                    TimeUnit.MILLISECONDS.sleep(Config.RENAMING_DELAY);
                } catch (InterruptedException e2) {
                }
            }
        }
        if (last_exception != null) {
            throw last_exception;
        }
        last_download_succeeded = true;
        return true;
    } catch (java.io.IOException ex) {
        if (fos != null)
            fos.close();
        System.out.println("IOException happened while downloading " + target);
        throw ex;
    } catch (RpcErrorException ex) {
        if (fos != null)
            fos.close();
        if (ex.getCode() == 500) {
            if (!last_download_succeeded) {
                System.out.println(
                        "Got an Internal Server Error from Telegram. Since the file downloaded before also happened to get this error, we will stop downloading now. Please try again later.");
                throw ex;
            }
            last_download_succeeded = false;
            System.out.println(
                    "Got an Internal Server Error from Telegram. Skipping this file for now. Next run of telegram_backup will continue to download this file.");
            logger.warn(ex.toString());
            return false;
        }
        System.out.println("RpcErrorException happened while downloading " + target);
        throw ex;
    }
}

From source file:fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.java

/**
 * Unzip a jar file/* www.jav a2s  . c  o m*/
 * @param jarFile Jar file url like file:/path/to/foo.jar
 * @param destination Directory where we want to extract the content to
 * @throws IOException In case of any IO problem
 */
public static void unzip(String jarFile, Path destination) throws IOException {
    Map<String, String> zipProperties = new HashMap<>();
    /* We want to read an existing ZIP File, so we set this to false */
    zipProperties.put("create", "false");
    zipProperties.put("encoding", "UTF-8");
    URI zipFile = URI.create("jar:" + jarFile);

    try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, zipProperties)) {
        Path rootPath = zipfs.getPath("/");
        Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetPath = destination.resolve(rootPath.relativize(dir).toString());
                if (!Files.exists(targetPath)) {
                    Files.createDirectory(targetPath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, destination.resolve(rootPath.relativize(file).toString()),
                        StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:edu.usu.sdl.openstorefront.service.SystemServiceImpl.java

@Override
public void saveGeneralMedia(GeneralMedia generalMedia, InputStream fileInput) {
    Objects.requireNonNull(generalMedia);
    Objects.requireNonNull(fileInput);
    Objects.requireNonNull(generalMedia.getName(), "Name must be set.");

    generalMedia.setFileName(generalMedia.getName());
    try (InputStream in = fileInput) {
        Files.copy(in, generalMedia.pathToMedia(), StandardCopyOption.REPLACE_EXISTING);
        generalMedia.populateBaseCreateFields();
        persistenceService.persist(generalMedia);
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to store media file.",
                "Contact System Admin.  Check file permissions and disk space ", ex);
    }/*w  w  w  .j  av  a2 s .co  m*/
}