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:nz.co.fortytwo.signalk.processor.UploadProcessor.java

private void processUpload(Exchange exchange) throws Exception {
    logger.debug("Begin import:" + exchange.getIn().getHeaders());
    if (exchange.getIn().getBody() != null) {
        logger.debug("Body class:" + exchange.getIn().getBody().getClass());
    } else {//from  ww  w  .  ja  v  a2 s . co m
        logger.debug("Body class is null");
    }
    //logger.debug("Begin import:"+ exchange.getIn().getBody());
    MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
    InputRepresentation representation = new InputRepresentation((InputStream) exchange.getIn().getBody(),
            mediaType);
    logger.debug("Found MIME:" + mediaType + ", length:"
            + exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, Integer.class));
    //make a reply
    Json reply = Json.read("{\"files\": []}");
    Json files = reply.at("files");

    try {
        List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory())
                .parseRepresentation(representation);
        logger.debug("Begin import files:" + items);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                InputStream inputStream = item.getInputStream();

                Path destination = Paths.get(
                        Util.getConfigProperty(STATIC_DIR) + Util.getConfigProperty(MAP_DIR) + item.getName());
                logger.debug("Save import file:" + destination);
                long len = Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
                Json f = Json.object();
                f.set("name", item.getName());
                f.set("size", len);
                files.add(f);
                install(destination);
            }
        }
    } catch (FileUploadException | IOException e) {
        logger.error(e.getMessage(), e);
    }
    exchange.getIn().setBody(reply);
}

From source file:com.ikanow.aleph2.security.utils.LdifExportUtil.java

public void exportToLdif(String outPath) {
    // copy Template
    Path pOutPath = Paths.get(outPath);

    try {//  ww  w .  j a  va2s  . co m
        Files.copy(this.getClass().getResourceAsStream("aleph2_template.ldif"), pOutPath,
                StandardCopyOption.REPLACE_EXISTING);
        String userEntries = createUserEntries();

        Files.write(pOutPath, userEntries.getBytes(), StandardOpenOption.APPEND);
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:com.seleniumtests.reporter.logger.Snapshot.java

/**
 * Rename HTML and PNG files so that they do not present an uuid
 * New name is <test_name>_<step_idx>_<snapshot_idx>_<step_name>_<uuid>
 * @param testStep/* w w  w. jav a 2s  . co m*/
 * @param stepIdx         number of this step
 * @param snapshotIdx   number of this snapshot for this step
 * @param userGivenName   name specified by user, rename to this name
 */
public void rename(final TestStep testStep, final int stepIdx, final int snapshotIdx,
        final String userGivenName) {
    String newBaseName;
    if (userGivenName == null) {
        newBaseName = String.format("%s_%d-%d_%s-",
                StringUtility.replaceOddCharsFromFileName(CommonReporter.getTestName(testStep.getTestResult())),
                stepIdx, snapshotIdx, StringUtility.replaceOddCharsFromFileName(testStep.getName()));
    } else {
        newBaseName = StringUtility.replaceOddCharsFromFileName(userGivenName);
    }

    if (screenshot.getHtmlSourcePath() != null) {
        String oldFullPath = screenshot.getFullHtmlPath();
        String oldPath = screenshot.getHtmlSourcePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());

        // if file cannot be moved, go back to old name
        try {
            oldFile = new File(oldFullPath);
            if (SeleniumTestsContextManager.getGlobalContext().getOptimizeReports()) {
                screenshot.setHtmlSourcePath(folderName + newName + ".zip");
                oldFile = FileUtility.createZipArchiveFromFiles(Arrays.asList(oldFile));
            } else {
                screenshot.setHtmlSourcePath(folderName + newName);
            }

            FileUtils.copyFile(oldFile, new File(screenshot.getFullHtmlPath()));
            new File(oldFullPath).delete();

        } catch (IOException e) {
            screenshot.setHtmlSourcePath(oldPath);
        }
    }
    if (screenshot.getImagePath() != null) {
        String oldFullPath = screenshot.getFullImagePath();
        String oldPath = screenshot.getImagePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());
        screenshot.setImagePath(folderName + newName);

        // if file cannot be moved, go back to old name
        try {
            Files.move(Paths.get(oldFullPath), Paths.get(screenshot.getFullImagePath()),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            screenshot.setImagePath(oldPath);
        }
    }
}

From source file:org.eclipse.cdt.arduino.core.internal.board.Platform.java

public IStatus install(IProgressMonitor monitor) throws CoreException {
    try {//w  ww . j a  va 2s  .  c o m
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(get)) {
                if (response.getStatusLine().getStatusCode() >= 400) {
                    return new Status(IStatus.ERROR, Activator.getId(),
                            response.getStatusLine().getReasonPhrase());
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity == null) {
                        return new Status(IStatus.ERROR, Activator.getId(), Messages.ArduinoBoardManager_1);
                    }
                    // the archive has the version number as the root
                    // directory
                    Path installPath = getInstallPath().getParent();
                    Files.createDirectories(installPath);
                    Path archivePath = installPath.resolve(archiveFileName);
                    Files.copy(entity.getContent(), archivePath, StandardCopyOption.REPLACE_EXISTING);

                    // extract
                    ArchiveInputStream archiveIn = null;
                    try {
                        String compressor = null;
                        String archiver = null;
                        if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.BZIP2;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                            compressor = CompressorStreamFactory.GZIP;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.XZ;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                            archiver = ArchiveStreamFactory.ZIP;
                        }

                        InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                        if (compressor != null) {
                            in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                        }
                        archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                        for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                                .getNextEntry()) {
                            if (entry.isDirectory()) {
                                continue;
                            }

                            // TODO check for soft links in tar files.
                            Path entryPath = installPath.resolve(entry.getName());
                            Files.createDirectories(entryPath.getParent());
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                    } finally {
                        if (archiveIn != null) {
                            archiveIn.close();
                        }
                    }
                }
            }
        }
        return Status.OK_STATUS;
    } catch (IOException | CompressorException | ArchiveException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.getId(), "Installing Platform", e));
    }
}

From source file:com.github.thorqin.webapi.FileManager.java

public void moveTo(String fileId, File destPath, boolean replaceExisting) throws IOException {
    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (replaceExisting)
        Files.move(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
    else/*from  w  ww.jav a 2 s  . com*/
        Files.move(dataFile.toPath(), destPath.toPath());
    deleteFile(fileId);
}

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  w  ww.  j a  va  2s.  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.getmansky.Cache.java

public static Playlist pushToPlaylist(List<File> files, Playlist p, EventHandler<Track> handler) {
    List<Playlist> pls = new ArrayList(playlists());

    File fullTracksPath = new File(Settings.storagePath + "/" + TRACKS_PATH);
    fullTracksPath.mkdirs();/*from  ww w  .j a v  a2s .co m*/

    files.stream().forEach((file) -> {
        Track t = new Track();
        t.setOffline(Boolean.TRUE);
        try {
            String md5 = DigestUtils.md5Hex(new FileInputStream(file));
            String newFilename = md5 + "-" + file.length() + ".mp3";
            Files.copy(file.toPath(), Paths.get(Settings.storagePath, TRACKS_PATH, newFilename),
                    StandardCopyOption.REPLACE_EXISTING);
            t.setId(newFilename);
            String nameFromTags = getNameFromTags(file);
            if (nameFromTags != null) {
                t.setTitle(nameFromTags);
            } else {
                t.setTitle(file.getName().substring(0, file.getName().length() - 4)); //remove ".mp3" at the end
            }
            t.setDuration(getDuration(file));
            p.getTracks().remove(t);
            p.getTracks().add(t);
            handler.handle(t);
        } catch (IOException | UnsupportedAudioFileException ex) {
            log.fatal(ex, ex);
        }
    });
    pls.remove(p);
    pls.add(p);

    savePlaylists(pls);
    return p;
}

From source file:org.tinymediamanager.core.movie.MovieExporter.java

/**
 * exports movie list according to template file.
 * //w ww .  ja  v a2  s .c o m
 * @param moviesToExport
 *          list of movies
 * @param exportDir
 *          the path to export
 * @throws Exception
 *           the exception
 */
@Override
public <T extends MediaEntity> void export(List<T> moviesToExport, Path exportDir) throws Exception {
    LOGGER.info("preparing movie export; using " + properties.getProperty("name"));

    // register own renderers
    engine.registerNamedRenderer(new NamedDateRenderer());
    engine.registerNamedRenderer(new MovieFilenameRenderer());
    engine.registerNamedRenderer(new ArtworkCopyRenderer(exportDir));

    // prepare export destination
    if (!Files.exists(exportDir)) {
        try {
            Files.createDirectories(exportDir);
        } catch (Exception e) {
            throw new Exception("error creating export directory");
        }
    }

    // prepare listfile
    Path listExportFile = null;
    if (fileExtension.equalsIgnoreCase("html")) {
        listExportFile = exportDir.resolve("index.html");
    }
    if (fileExtension.equalsIgnoreCase("xml")) {
        listExportFile = exportDir.resolve("movielist.xml");
    }
    if (fileExtension.equalsIgnoreCase("csv")) {
        listExportFile = exportDir.resolve("movielist.csv");
    }
    if (listExportFile == null) {
        throw new Exception("error creating movie list file");
    }

    // create list
    LOGGER.info("generating movie list");
    Utils.deleteFileSafely(listExportFile);

    Map<String, Object> root = new HashMap<>();
    root.put("movies", new ArrayList<>(moviesToExport));

    String output = engine.transform(listTemplate, root);

    Utils.writeStringToFile(listExportFile, output);
    LOGGER.info("movie list generated: " + listExportFile);

    // create details for
    if (StringUtils.isNotBlank(detailTemplate)) {
        Path detailsDir = exportDir.resolve("movies");
        if (Files.isDirectory(detailsDir)) {
            Utils.deleteDirectoryRecursive(detailsDir);
        }
        Files.createDirectory(detailsDir);

        for (MediaEntity me : moviesToExport) {
            Movie movie = (Movie) me;
            LOGGER.debug("processing movie " + movie.getTitle());
            // get preferred movie name like set up in movie renamer
            String detailFilename = MovieRenamer.createDestinationForFilename(
                    MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerFilename(), movie);
            if (StringUtils.isBlank(detailFilename)) {
                detailFilename = movie.getVideoBasenameWithoutStacking();
                // FilenameUtils.getBaseName(Utils.cleanStackingMarkers(movie.getMediaFiles(MediaFileType.VIDEO).get(0).getFilename()));
            }
            Path detailsExportFile = detailsDir.resolve(detailFilename + "." + fileExtension);

            root = new HashMap<>();
            root.put("movie", movie);

            output = engine.transform(detailTemplate, root);
            Utils.writeStringToFile(detailsExportFile, output);

        }

        LOGGER.info("movie detail pages generated: " + exportDir);
    }

    // copy all non .jtme/template.conf files to destination dir
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(templateDir)) {
        for (Path path : directoryStream) {
            if (Utils.isRegularFile(path)) {
                if (path.getFileName().toString().endsWith(".jmte")
                        || path.getFileName().toString().endsWith("template.conf")) {
                    continue;
                }
                Files.copy(path, exportDir.resolve(path.getFileName()), StandardCopyOption.REPLACE_EXISTING);
            } else if (Files.isDirectory(path)) {
                Utils.copyDirectoryRecursive(path, exportDir.resolve(path.getFileName()));
            }
        }
    } catch (IOException ex) {
        LOGGER.error("could not copy resources: ", ex);
    }
}

From source file:org.sonar.java.it.JavaRulingTest.java

private static void copyDumpSubset(Path srcProjectDir, Path dstProjectDir) {
    Try.of(() -> Files.createDirectory(dstProjectDir)).orElseThrow(Throwables::propagate);
    SUBSET_OF_ENABLED_RULES.stream().map(ruleKey -> srcProjectDir.resolve("squid-" + ruleKey + ".json"))
            .filter(p -> p.toFile().exists())
            .forEach(srcJsonFile -> Try.of(() -> Files.copy(srcJsonFile,
                    dstProjectDir.resolve(srcJsonFile.getFileName()), StandardCopyOption.REPLACE_EXISTING))
                    .orElseThrow(Throwables::propagate));
}