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:hydrograph.ui.dataviewer.filemanager.DataViewerFileManager.java

private void copyFilteredFileToDataViewerStagingArea(JobDetails jobDetails, String csvFilterFileAbsolutePath,
        String dataViewerDebugFile) throws IOException, JSchException {
    if (!jobDetails.isRemote()) {
        String sourceFile = csvFilterFileAbsolutePath.trim();
        File file = new File(dataViewerDebugFile);
        Files.copy(Paths.get(sourceFile), Paths.get(dataViewerDebugFile), StandardCopyOption.REPLACE_EXISTING);
    } else {/*from www.  ja v  a2  s  . c o m*/
        File file = new File(dataViewerDebugFile);
        SCPUtility.INSTANCE.scpFileFromRemoteServer(jobDetails.getHost(), jobDetails.getUsername(),
                jobDetails.getPassword(), csvFilterFileAbsolutePath.trim(), getDataViewerDebugFilePath());
    }
}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

/**
 * This method is used to process the image to an OCR-friendly format.
 * @param streamingObject input image to be processed
 * @param config TesseractOCRconfig class to get ImageMagick properties
 * @throws IOException if an input error occurred
 * @throws TikaException if an exception timed out
 *//*  w ww  .j  a v  a  2s  . c  o  m*/
private void processImage(File streamingObject, TesseractOCRConfig config) throws IOException, TikaException {

    // fetch rotation script from resources
    InputStream in = getClass().getResourceAsStream("rotation.py");
    TemporaryResources tmp = new TemporaryResources();
    File rotationScript = tmp.createTemporaryFile();
    Files.copy(in, rotationScript.toPath(), StandardCopyOption.REPLACE_EXISTING);

    String cmd = "python " + rotationScript.getAbsolutePath() + " -f " + streamingObject.getAbsolutePath();
    String angle = "0";

    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);

    // determine the angle of rotation required to make the text horizontal
    CommandLine cmdLine = CommandLine.parse(cmd);
    if (hasPython()) {
        try {
            executor.execute(cmdLine);
            angle = outputStream.toString("UTF-8").trim();
        } catch (Exception e) {

        }
    }

    // process the image - parameter values can be set in TesseractOCRConfig.properties
    String line = "convert -density " + config.getDensity() + " -depth " + config.getDepth() + " -colorspace "
            + config.getColorspace() + " -filter " + config.getFilter() + " -resize " + config.getResize()
            + "% -rotate " + angle + " " + streamingObject.getAbsolutePath() + " "
            + streamingObject.getAbsolutePath();
    cmdLine = CommandLine.parse(line);
    try {
        executor.execute(cmdLine);
    } catch (Exception e) {

    }

    tmp.close();
}

From source file:org.apache.maven.plugin.cxx.UnpackDependenciesMojo.java

/**
 * flat copy the archive content.//  w  ww  . j av  a  2  s  . c o m
 * 
 * origin : derived from org.apache.maven.plugin.dependency.AbstractDependencyMojo::unpack()
 *
 * @param artifact File to be unpacked.
 * @param srcRoot  Location where the whole archive was unpacked.
 * @param location Location where to put the unpacked files.
 * @param includes Comma separated list of file patterns to include i.e. <code>**&#47;.xml,
 *                 **&#47;*.properties</code>
 * @param excludes Comma separated list of file patterns to exclude i.e. <code>**&#47;*.xml,
 *                 **&#47;*.properties</code>
 */
protected void listAndFlatCopy(Artifact artifact, File srcRoot, File location, String includes, String excludes)
        throws MojoExecutionException {
    File file = artifact.getFile();
    try {
        //logUnpack( file, location, includes, excludes );

        location.mkdirs();

        if (file.isDirectory()) {
            // usual case is a future jar packaging, but there are special cases: classifier and other packaging
            throw new MojoExecutionException(
                    "Artifact has not been packaged yet. When used on reactor artifact, "
                            + "unpack should be executed after packaging: see MDEP-98.");
        }

        ArchiveContentLister archiveContentLister;

        try {
            archiveContentLister = archiveContentListerManager.getArchiveContentLister(artifact.getType());
            getLog().debug("Found archiveContentLister by type: " + archiveContentLister);
        } catch (NoSuchArchiverException e) {
            archiveContentLister = archiveContentListerManager.getArchiveContentLister(file);
            getLog().debug("Found unArchiver by extension: " + archiveContentLister);
        }

        //unArchiver.setUseJvmChmod( useJvmChmod );

        //unArchiver.setIgnorePermissions( ignorePermissions );

        archiveContentLister.setSourceFile(file);

        //unArchiver.setDestDirectory( location );

        if (StringUtils.isNotEmpty(excludes) || StringUtils.isNotEmpty(includes)) {
            // Create the selectors that will filter
            // based on include/exclude parameters
            // MDEP-47
            IncludeExcludeFileSelector[] selectors = new IncludeExcludeFileSelector[] {
                    new IncludeExcludeFileSelector() };

            if (StringUtils.isNotEmpty(excludes)) {
                selectors[0].setExcludes(excludes.split(","));
            }

            if (StringUtils.isNotEmpty(includes)) {
                selectors[0].setIncludes(includes.split(","));
            }

            archiveContentLister.setFileSelectors(selectors);
        }
        if (this.silent) {
            silenceArchiveContentLister(archiveContentLister);
        }

        List<ArchiveContentEntry> contents = archiveContentLister.list();

        for (ArchiveContentEntry content : contents) {
            if (content.getType() == ArchiveContentEntry.FILE) {
                String sSubFileName = (new File(content.getName())).getName();
                String src = srcRoot.getAbsolutePath() + File.separator + content.getName();
                String dst = location + File.separator + sSubFileName;
                try {
                    Files.copy(Paths.get(src), Paths.get(dst), StandardCopyOption.REPLACE_EXISTING);
                    getLog().debug("Copy " + src + " to " + dst);
                } catch (IOException e) {
                    getLog().error("Copy of " + src + " to " + dst + " failed : " + e);
                }
            }
        }

    } catch (NoSuchArchiverException e) {
        throw new MojoExecutionException("Unknown archiver type", e);
    } catch (ArchiverException e) {
        throw new MojoExecutionException(
                "Error unpacking file: " + file + " to: " + location + "\r\n" + e.toString(), e);
    }
}

From source file:co.marcin.novaguilds.manager.ConfigManager.java

public void backupFile() throws IOException {
    File backupFile = new File(getConfigFile().getParentFile(), "config.yml.backup");
    Files.copy(getConfigFile().toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.jenkinsci.plugins.lsf.LSFBuilder.java

/**
 * sends the selected files to the slave machine
 *
 * @param build//from  www .  j a  v  a 2  s . c  om
 * @param launcher
 * @param listener
 * @return shell commands for sending files to batch system
 * @throws IOException
 * @throws InterruptedException
 */
protected String sendFiles(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws IOException, InterruptedException {
    String sendFilesShellCommands = "";
    String filesWithoutPaths = "";
    for (String file : filesToSend.split(",")) {
        File fileToSend = new File(file.trim());
        sendFilesShellCommands = sendFilesShellCommands + "cp \"" + slaveWorkingDirectory + "/"
                + fileToSend.getName() + "\" .\n";
        Files.copy(fileToSend.toPath(), new File(masterWorkingDirectory + fileToSend.getName()).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
        filesWithoutPaths = fileToSend.getName() + "," + filesWithoutPaths;
    }
    for (String file : uploadedFiles.split(",")) {
        sendFilesShellCommands = sendFilesShellCommands + "cp \"" + slaveWorkingDirectory + "/" + file
                + "\" .\n";
    }
    CopyToSlaveBuildWrapper copyToSlave = new CopyToSlaveBuildWrapper(filesWithoutPaths + uploadedFiles, "",
            false, false, CopyToSlaveBuildWrapper.RELATIVE_TO_WORKSPACE, false);
    copyToSlave.setUp(build, launcher, listener);
    return sendFilesShellCommands;
}

From source file:org.jenkinsci.plugins.lsf.BatchBuilder.java

/**
 * sends the selected files to the slave machine
 *
 * @param build/*from   w  w  w  .  j a va2  s  .c  o  m*/
 * @param launcher
 * @param listener
 * @return shell commands for sending files to batch system
 * @throws IOException
 * @throws InterruptedException
 */
protected String sendFiles(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws IOException, InterruptedException {
    String sendFilesShellCommands = "";
    String filesWithoutPaths = "";
    if (!filesToSend.isEmpty()) {
        for (String file : filesToSend.split(",")) {
            File fileToSend = new File(file.trim());
            sendFilesShellCommands = sendFilesShellCommands + "cp \"" + slaveWorkingDirectory + "/"
                    + fileToSend.getName() + "\" .\n";
            Files.copy(fileToSend.toPath(), new File(masterWorkingDirectory + fileToSend.getName()).toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
            filesWithoutPaths = build.getProject().getName() + "/" + fileToSend.getName() + ","
                    + filesWithoutPaths;
        }
    }
    if (!uploadedFiles.isEmpty()) {
        for (String file : uploadedFiles.split(",")) {
            sendFilesShellCommands = sendFilesShellCommands + "cp \"" + slaveWorkingDirectory + "/" + file
                    + "\" .\n";
            filesWithoutPaths = build.getProject().getName() + "/" + file + "," + filesWithoutPaths;
        }
    }
    if (!filesToSend.isEmpty() || !uploadedFiles.isEmpty()) {
        CopyToSlaveBuildWrapper copyToSlave = new CopyToSlaveBuildWrapper(filesWithoutPaths, "", true, false,
                CopyToSlaveBuildWrapper.RELATIVE_TO_HOME, false);
        copyToSlave.setUp(build, launcher, listener);
    }
    return sendFilesShellCommands;
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Publish experiment. Parse corresponding directory if descriptor files does not exist yet.
 * @param experimentDirPath Path to experiment directory
 * @param software Software context/*from  w w w  .  j  av  a2s.com*/
 * @param xmlDescPath Path to XML file containing metadata generation rules
 * @param depth 
 * @throws Exception 
 */
public void publishExperiment(String experimentDirPath, String software, String xmlDescPath,
        boolean isForceDescUpdate, int depth) throws Exception {
    Locker experimentLocker = null;
    Locker webdirLocker = null;
    try {
        //lock directory being parsed
        experimentLocker = new Locker(experimentDirPath);
        webdirLocker = new Locker(publicHtmlFolder);
        //check lock ... 
        boolean isLocked = experimentLocker.lock();
        if (isLocked) {
            File experimentDesc = new File(
                    experimentDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_DESC_FILE_TREE_FILE_NAME);
            if (!experimentDesc.exists() || isForceDescUpdate) {
                //parse directory
                this.parse(experimentDirPath, software, xmlDescPath, depth);
            } else {
                if (outputToConsole)
                    System.out.println("Using existing descriptors (use -f option to force parsing)...");
            }
            //lock web directory for updates
            if (outputToConsole)
                System.out.println("Wating for other users to finish publishing...");
            isLocked = webdirLocker.waitAndLock();

            //update XML file representing experiment list
            XmlExperimentFile experimentXml = new XmlExperimentFile(experimentDesc.getAbsolutePath());
            int id = experimentListXml.addNewExperiment(experimentXml);
            experimentListXml.saveXml();

            //create new directory for this experiment
            String liteDirPath = publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                    + PATH_FOLDER_SEPARATOR + id;
            if (Files.exists(Paths.get(liteDirPath)))
                Utils.removeDirectoryRecursive(Paths.get(liteDirPath));
            Files.createDirectory(Paths.get(liteDirPath));

            //copy experiment XML descriptors
            String newFileTreeXmlPath = liteDirPath + "/index.xml";
            String newWorkflowXmlPath = liteDirPath + "/index-details.xml";
            Files.copy(Paths.get(experimentDesc.getAbsolutePath()), Paths.get(newFileTreeXmlPath),
                    StandardCopyOption.REPLACE_EXISTING);
            Files.copy(Paths.get(experimentDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_DESC_WORKFLOW_FILE_NAME),
                    Paths.get(newWorkflowXmlPath), StandardCopyOption.REPLACE_EXISTING);

            //pull data files (csv, pdb, and images)
            String dataDirPath = liteDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_DATA_DIR;
            Files.createDirectory(Paths.get(dataDirPath));
            this.pullDataFilesForExperiment(newFileTreeXmlPath, newWorkflowXmlPath,
                    liteDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_DATA_DIR);

            //generate HTML pages
            if (outputToConsole)
                System.out.println("Generating HTML...");
            //experiment summary
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "index.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_SUMMARY_XSL_PATH);
            //experiment workflow (tree view)
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "details.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_WORKFLOW_XSL_PATH);
            //experiment runs (timings, resources)
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "runs.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_RUNS_XSL_PATH);
            //experiment file browser
            this.transformXmlToHtml(newFileTreeXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "files.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_FILE_TREE_XSL_PATH);
            //list of experiments
            experimentListXml.saveToHTML(publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_HTML_INDEX,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_SET_XSL_PATH);
        } else {
            System.out.println("Could not lock " + experimentDirPath + " for parsing.");
            System.out.println(
                    "Another user might be publishing this experiment right now. If you believe this is not the case, delete the "
                            + Locker.LOCK_FILE_NAME + " file in the experiment directory and re-try.");
        }

        //unlock directories
        experimentLocker.unlock();
        webdirLocker.unlock();

    } catch (Exception e) {
        if (experimentLocker != null)
            experimentLocker.unlock();
        if (webdirLocker != null)
            webdirLocker.unlock();
        throw e;
    }
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Moves a file to a destination. /*from w  w  w.ja  v a 2s .  c om*/
 * 
 * @param file the path to the file to move 
 * @param destination the destination path 
 * @throws IOException  if an I/O error occurs
 * @throws IllegalArgumentException if file is null or not exists, destination is null
 */
public static void moveFile(Path file, Path destination) throws IOException, IllegalArgumentException {
    if ((file == null) || !Files.exists(file, LinkOption.NOFOLLOW_LINKS) || (destination == null)) {
        throw new IllegalArgumentException("The filepath is null or points to an invalid location! " + file);
    }

    Files.move(file, destination, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.n52.wps.server.database.PostgresDatabase.java

@Override
public synchronized void updateResponse(String id, InputStream stream) {
    Path tempFilePath = null;/*w  w w  . ja v  a 2s . c  om*/
    FileInputStream fis = null;
    try {
        tempFilePath = Files.createTempFile(UUID.randomUUID().toString(), null);
        Files.copy(stream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
        fis = new FileInputStream(tempFilePath.toFile());

        AbstractDatabase.updateSQL.setString(UPDATE_COLUMN_REQUEST_ID, id);
        AbstractDatabase.updateSQL.setAsciiStream(UPDATE_COLUMN_RESPONSE, fis,
                (int) tempFilePath.toFile().length());
        AbstractDatabase.updateSQL.executeUpdate();
        getConnection().commit();
    } catch (SQLException e) {
        LOGGER.error("Could not insert Response into database", e);
    } catch (IOException e) {
        LOGGER.error("Could not insert Response into database", e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LOGGER.error("Could not close file input stream", e);
            }
        }
        if (tempFilePath != null) {
            try {
                Files.deleteIfExists(tempFilePath);
            } catch (IOException e) {
                LOGGER.error("Could not delete file: " + tempFilePath.toString(), e);
            }
        }
    }
}

From source file:de.elomagic.maven.http.HTTPMojo.java

/**
 * @todo Must may be refactored. Only a prototype
 * @param file/*from www .  jav a  2s .c om*/
 * @param destDirectory
 * @throws MojoExecutionException
 */
private void unzipToFile(final File file, final File destDirectory) throws Exception {
    getLog().info("Extracting downloaded file to folder \"" + destDirectory + "\".");

    int filesCount = 0;

    // create the destination directory structure (if needed)
    destDirectory.mkdirs();

    // open archive for reading
    try (ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ)) {
        // For every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = zipFileEntries.nextElement();
            getLog().debug("Extracting entry: " + entry);

            //create destination file
            // TODO Check entry path on path injections
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream bufIS = new BufferedInputStream(zipFile.getInputStream(entry));

                // write the current file to disk
                Files.copy(bufIS, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                filesCount++;
            }
        }
    }

    getLog().info(filesCount + " files extracted.");
}