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:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java

/**
 * Take screen shot.//from  www.  j  a v  a  2  s.c  om
 * @param fileNames the file names
 * @throws DeviceException the device exception
 * @see com.ecofactor.qa.automation.mobile.ops.DriverOperations#takeScreenShot(java.lang.String[])
 */
@Override
public void takeScreenShot(final String... fileNames) throws DeviceException {

    try {
        final Path screenshot = ((TakesScreenshot) getDeviceDriver()).getScreenshotAs(OutputType.FILE).toPath();
        final Path screenShotFile = getTargetScreenshotPath(fileNames);
        Files.copy(screenshot, screenShotFile, StandardCopyOption.REPLACE_EXISTING);
        if (Files.exists(screenShotFile)) {
            LOGGER.info("Saved screenshot for " + fileNames + AT_STRING + screenShotFile);
        } else {
            LOGGER.info("Unable to save screenshot for " + fileNames + AT_STRING + screenShotFile);
        }
    } catch (WebDriverException | IOException e) {
        LOGGER.error("Error taking screenshot for " + fileNames, e);
    }
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {/*  w  ww.  ja v  a2s . c om*/
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java

private void downloadToFile(URI source, Path destination) throws DownloadException {
    try {//from w  w  w  .ja  v  a2  s . c om
        // We want to handle http/https with HTTPClient
        if (source.getScheme().equalsIgnoreCase("http") || source.getScheme().equalsIgnoreCase("https")) {
            Request.Get(source).userAgent(getUserAgent()).connectTimeout(TIMEOUT).socketTimeout(TIMEOUT)
                    .execute().saveContent(destination.toFile());
        } else {
            // Try as a supported Path, e.g. file: or relative path
            try {
                Path path = Paths.get(source);
                Files.copy(path, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (FileSystemNotFoundException e) {
                throw new DownloadException("Unsupported URL scheme: " + source.getScheme());
            }
        }
    } catch (IOException e) {
        throw new DownloadException(String.format("Error downloading %1$s to %2$s.", source, destination), e);
    }
}

From source file:jfix.zk.Mediafield.java

public void copyToFile(File target) {
    if (target == null) {
        return;// ww  w .java 2s . c om
    }
    try {
        if (codemirror.isVisible()) {
            FileUtils.writeStringToFile(target, codemirror.getValue(), "UTF-8");
            codemirror.setSyntax(FilenameUtils.getExtension(target.getName()));
        } else {
            if (media != null) {
                Files.move(Medias.asFile(media).toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

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

public void copyTo(String fileId, File destPath, boolean replaceExisting) throws IOException {
    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (replaceExisting)
        Files.copy(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
    else/*from   ww  w . j  a  v a  2  s.c  o m*/
        Files.copy(dataFile.toPath(), destPath.toPath());
}

From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

@Test
public void testInstallCustomExtensionTwiceOverwrite() throws Exception {
    String jarName = _sampleCommandJarFile.getName();

    File extensionJar = new File(_extensionsDir, jarName);

    String[] args = { "extension", "install", _sampleCommandJarFile.getAbsolutePath() };

    Path extensionPath = extensionJar.toPath();

    BladeTestResults bladeTestResults = TestUtil.runBlade(_rootDir, _extensionsDir, args);

    String output = bladeTestResults.getOutput();

    _testJarsDiff(_sampleCommandJarFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"successful\"\n" + output, output.contains(" successful"));
    Assert.assertTrue(output.contains(jarName));

    File tempDir = temporaryFolder.newFolder("overwrite");

    Path tempPath = tempDir.toPath();

    Path sampleCommandPath = tempPath.resolve(_sampleCommandJarFile.getName());

    Files.copy(_sampleCommandJarFile.toPath(), sampleCommandPath, StandardCopyOption.COPY_ATTRIBUTES,
            StandardCopyOption.REPLACE_EXISTING);

    File sampleCommandFile = sampleCommandPath.toFile();

    sampleCommandFile.setLastModified(0);

    args = new String[] { "extension", "install", sampleCommandFile.getAbsolutePath() };

    output = _testBladeWithInteractive(_rootDir, _extensionsDir, args, "y");

    _testJarsDiff(sampleCommandFile, extensionJar);

    Assert.assertTrue("Expected output to contain \"Overwrite\"\n" + output, output.contains("Overwrite"));
    boolean assertCorrect = output.contains(" installed successfully");

    if (!assertCorrect) {
        Assert.assertTrue("Expected output to contain \"installed successfully\"\n" + output, assertCorrect);
    }// w  w  w . j ava 2  s .  co m

    File extensionFile = extensionPath.toFile();

    Assert.assertEquals(sampleCommandFile.lastModified(), extensionFile.lastModified());
}

From source file:com.skynetcomputing.skynetclient.persistence.PersistenceManager.java

/**
 * Saves jar file to file system. Name is its MD5 checksum
 *
 * @param jarFile/*w w  w .  j a  va  2 s  .c  o  m*/
 * @return
 * @throws IOException
 */
public File saveJar(File jarFile) throws IOException {
    File outputFile = null;
    try (FileInputStream fis = new FileInputStream(jarFile)) {
        String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
        outputFile = new File(String.format("%s%s%s%s", rootDir, JAR_DIR, md5, SrzJar.EXT));
        Files.copy(jarFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    return outputFile;
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

private static boolean generateAppfromXML(String fn) {

    long starttime = System.currentTimeMillis();

    // fn must not be null or empty
    if (fn == null || fn.isEmpty()) {
        log.error("Empty filename!");
        return false;
    }/*from   w  w  w . j a v a2  s . co  m*/
    // fn must be a valid file and readable
    File runnableitem = new File(fn);
    if (!runnableitem.exists() || !runnableitem.canRead()) {
        log.error("{} doesn't exists or can't be read! ", fn);
        return false;
    }
    // load as xml file, validate it, and ...
    Document doc;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        //dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(runnableitem);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("{} occured: {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }
    // extract project id, name  and version from it.
    String projectid = doc.getDocumentElement().getAttribute("id");
    if ((projectid == null) || projectid.isEmpty()) {
        log.error("Missing project id in description file!");
        return false;
    }
    String projectname;
    try {
        projectname = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "name").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.error("Missing project name in description file!");
        return false;
    }

    String projectversion = "unknown";
    try {
        projectversion = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "version").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.warn("Missing project version in description file!");

    }

    File projectdir = new File(
            config.getProperty("project.dir", config.getProperty("target.dir") + "/" + projectid));

    mkdirs(projectdir + "/src/main/java");
    mkdirs(projectdir + "/src/main/config");
    mkdirs(projectdir + "/src/main/libs");
    mkdirs(projectdir + "/src/main/pages");
    mkdirs(projectdir + "/src/main/resources");
    mkdirs(projectdir + "/src/main/downloads");

    // place runnableitem in config dir
    try {
        Files.copy(runnableitem.toPath(), new File(projectdir + "/src/main/config/runnableitem.xml").toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error("{} occurred : {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }

    // copy files from SKELETON to projectdir and replace wildcard expression
    String[] SKELETON_INPUT_ARRAY = { "/pom.xml", "/src/main/config/log4j-tool.properties" };
    String SKELETON_INPUT = null;
    try {
        for (int c = 0; c < SKELETON_INPUT_ARRAY.length; c++) {
            SKELETON_INPUT = SKELETON_INPUT_ARRAY[c];

            InputStream in = Main.class.getResourceAsStream("/SKELETON" + SKELETON_INPUT);
            if (in == null) {
                throw new IOException();
            }

            CopyAndReplace(in, new FileOutputStream(new File(projectdir, SKELETON_INPUT)), projectid,
                    projectname, projectversion);
        }

    } catch (IOException e) {
        log.error("Exception occurred while calling 'copyAndReplace(/SKELETON{},{}/{},{},{},{})'",
                SKELETON_INPUT, projectdir, SKELETON_INPUT, projectid, projectname, projectversion);
        return false;
    }

    log.info("Empty project created! ");

    try {
        // _base 

        generate(CodeGen_Implementation.class, runnableitem, projectdir);
        log.info("Implementation generated!");

        generate(CodeGen_Implementation_Threadworker.class, runnableitem, projectdir);
        log.info("Implementation_Threadworker generated!");

        generate(CodeGen_Utilities.class, runnableitem, projectdir);
        log.info("Utilities generated!");

        generate(CodeGen_Common.class, runnableitem, projectdir, "/templates/common", RESOURCETYPE.isDirectory);

        log.info("Common generated!");

        // _REST
        generate(CodeGen_REST.class, runnableitem, projectdir);
        generate(CodeGen_REST_general.class, runnableitem, projectdir);

        log.info("REST generated!");

        //_HTML
        generate(CodeGen_WebSubmissionPage.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Visualization.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Formatchooser.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Function.class, runnableitem, projectdir);
        generate(CodeGen_Session_Reset.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Controller.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_Webstart.class, runnableitem, projectdir); // can be removed ???
        generate(CodeGen_WebToolBeanContextConfig.class, runnableitem, projectdir);
        generate(CodeGen_WebManual.class, runnableitem, projectdir);
        generate(CodeGen_WebPage.class, runnableitem, projectdir, "/templates/pages", RESOURCETYPE.isDirectory);

        log.info("XHTML pages generated!");

        long time = (System.currentTimeMillis() - starttime) / 1000;

        log.info("Project \"{}\" (id:{}, version:{}) created at '{}' in {} seconds.", projectname, projectid,
                projectversion, projectdir, time);

    } catch (CodeGenParserException e) {
        log.error("CodeGenParserException occurred :", e);
        return false;
    }
    return true;
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

private void moveOrCopyFile(File originNodeFile, File targetNodeFile) throws IOException {
    try {//from  w  ww  .  ja  va 2 s . c  o m
        Files.move(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
    } catch (AtomicMoveNotSupportedException amnse) {
        logger.warn(
                "Could not perform atomic move: " + amnse.getMessage() + ". Trying regular copy and delete...");
        Files.copy(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        deleteFile(originNodeFile);
    }
}

From source file:com.sonar.it.scanner.msbuild.TestUtils.java

private static void replaceInZip(URI zipUri, Path src, String dest) {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    // locate file system by using the syntax
    // defined in java.net.JarURLConnection
    URI uri = URI.create("jar:" + zipUri);
    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Path pathInZipfile = zipfs.getPath(dest);
        LOG.info("Replacing the file " + pathInZipfile + " in the zip " + zipUri + " with " + src);
        Files.copy(src, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }//from  w  w  w. j a v  a 2  s. c  o  m
}