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.virtualAsylum.spriggan.data.Addon.java

public State doInstall() {
    log("Installing %s (%s)", getDisplayName(), getID());
    State result = State.IDLE;
    State error = State.ERROR;
    setState(State.INSTALLING);//from   ww w  .  j  av  a  2s.  c o m
    setStateProgress(-1);
    boolean didError = false;
    try {
        //<editor-fold desc="Dependencies">
        Collection<String> dependencyIDs = getDependencies();
        ArrayList<Addon> dependencies = new ArrayList();
        if (dependencyIDs.size() > 0) {
            setState(State.INSTALLING_DEPENDENCIES);
            for (String dependencyIDString : dependencyIDs) {
                Addon dependency = Database.find_ID(dependencyIDString);
                if (dependency == null) {
                    throw new Exception(String.format("Dependency %s was missing for %s(%s)",
                            dependencyIDString, getDisplayName(), getID()));
                }
                if (!dependency.getInstalled()) {
                    dependencies.add(dependency);
                }
            }
            if (dependencies.size() > 0) {
                SimpleObjectProperty<Boolean> popupResult = new SimpleObjectProperty(null);
                runLater(() -> {
                    DependencyPopup popup = new DependencyPopup(this, dependencies, popupResult);
                    Stage stage = popup.popup(StageStyle.UTILITY, Modality.WINDOW_MODAL,
                            MainInterface.current.getWindow(), getDisplayName());
                    stage.setOnCloseRequest(e -> popupResult.set(false));
                    stage.show();
                });

                while (popupResult.get() == null) {
                    sleep(500);
                }
                if (!popupResult.get()) {
                    error = State.IDLE;
                    throw new Exception(String.format("Did not install dependencies for %s (%s)",
                            getDisplayName(), getID()));
                }
                double perDep = 1.0 / dependencies.size();
                setStateProgress(0.0);
                for (Addon dependency : dependencies) {
                    boolean downloaded = Database.getCurrent().getRepository().contains(dependency);
                    State depResult = State.IDLE;
                    if (!downloaded) {
                        depResult = dependency.doDownloadAndInstall();
                    } else if (!dependency.getInstalled()) {
                        depResult = dependency.doInstall();
                    }
                    if (depResult != State.IDLE) {
                        throw new Exception(
                                String.format("Dependency %s (%s) failed to download and/or install",
                                        dependency.getDisplayName(), dependency.getID()));
                    }
                    incrementStateProgress(perDep);
                }
                setState(State.INSTALLING);
            }

        }
        //</editor-fold>

        error = State.ERROR;

        final File repositoryDirectory = getRepositoryDirectory(this);
        final File installDirectory = getInstallDirectory(this);

        ArrayList<File> files = getRepositoryFiles();

        double perFile = 1.0 / files.size();
        setStateProgress(0.0);
        for (File inputFile : files) {
            File outputFile = new File(installDirectory,
                    repositoryDirectory.toPath().relativize(inputFile.toPath()).toString());
            outputFile.getParentFile().mkdirs();
            Files.copy(inputFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            incrementStateProgress(perFile);
        }

    } catch (Exception ex) {
        if (error == State.ERROR) {
            handleException(ex);
        }
        result = error;
        didError = true;
    }

    if (!didError) {
        setInstalled(true);
    }
    log("Installing %s (%s): %s", getDisplayName(), getID(), result);
    setStateProgress(0);
    setState(result);
    return result;
}

From source file:it.baeyens.arduino.managers.Manager.java

/**
 * This method takes a json boards file url and downloads it and parses it
 * for usage in the boards manager/*from   w w  w  .  j a v  a  2  s  .c o m*/
 * 
 * @param url
 *            the url of the file to download and load
 * @param forceDownload
 *            set true if you want to download the file even if it is
 *            already available locally
 */
static private void loadPackageIndex(String url, boolean forceDownload) {
    File packageFile = getLocalFileName(url);
    if (packageFile == null) {
        return;
    }
    if (!packageFile.exists() || forceDownload) {
        packageFile.getParentFile().mkdirs();
        try {
            Files.copy(new URL(url.trim()).openStream(), packageFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            Common.log(new Status(IStatus.ERROR, Activator.getId(), "Unable to download " + url, e)); //$NON-NLS-1$
        }
    }
    if (packageFile.exists()) {
        try (Reader reader = new FileReader(packageFile)) {
            PackageIndex index = new Gson().fromJson(reader, PackageIndex.class);
            index.setOwners(null);
            packageIndices.add(index);
        } catch (Exception e) {
            Common.log(new Status(IStatus.ERROR, Activator.getId(),
                    "Unable to parse " + packageFile.getAbsolutePath(), e)); //$NON-NLS-1$
            packageFile.delete();// Delete the file so it stops damaging
        }
    }
}

From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java

private void copyInternal(DavNode destination, boolean shallow) throws DavException {
    assert exists();
    assert attr.isPresent();
    if (!Files.isDirectory(destination.path.getParent())) {
        throw new DavException(DavServletResponse.SC_CONFLICT, "Destination's parent doesn't exist.");
    }/*from w w w  .j  a  va2  s.  c  o  m*/

    try {
        if (shallow && destination instanceof DavFolder) {
            // http://www.webdav.org/specs/rfc2518.html#copy.for.collections
            Files.createDirectory(destination.path);
            BasicFileAttributeView attrView = Files.getFileAttributeView(destination.path,
                    BasicFileAttributeView.class);
            if (attrView != null) {
                BasicFileAttributes a = attr.get();
                attrView.setTimes(a.lastModifiedTime(), a.lastAccessTime(), a.creationTime());
            }
        } else {
            Files.walkFileTree(path,
                    new CopyingFileVisitor(path, destination.path, StandardCopyOption.REPLACE_EXISTING));
        }
    } catch (IOException e) {
        throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    }
}

From source file:org.pieShare.pieShareApp.service.shareService.ShareService.java

@Override
public void localFileTransferComplete(PieFile file, boolean source) {
    try {//from w  w  w .j  a v  a 2  s.c o m
        File localTmpFile = this.fileService.getAbsoluteTmpPath(file).toFile();
        File localTmpFileParent = this.fileService.getAbsoluteTmpPath(file).toFile().getParentFile();
        File localEncTmpFile = new File(localTmpFileParent, file.getFileName() + ".enc");

        if (!source) {
            File localFile = this.fileService.getAbsolutePath(file).toFile();

            //todo: does this belong into the fileService?
            if (!localFile.getParentFile().exists()) {
                localFile.getParentFile().mkdirs();
            }

            this.fileEncryptionService.decryptFile(localEncTmpFile, localTmpFile);

            this.fileWatcherService.addPieFileToModifiedList(file);
            Files.move(localTmpFile.toPath(), localFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            //this.fileWatcherService.addPieFileToModifiedList(file);
            //FileUtils.moveFile(localTmpFile, localFile);
            //todo: this i wrong here!
            //todo: has to move to the according task
            this.fileWatcherService.removePieFileFromModifiedList(file);

            this.fileWatcherService.addPieFileToModifiedList(file);
            this.fileService.setCorrectModificationDate(file);

            //todo: is it better to delete the enc file or not?
        }

        //localTmpFile.delete();

        this.manipulatePieFileState(file, -1);
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error!", ex);
    }
}

From source file:org.nuxeo.github.Analyzer.java

protected void load() {
    if (input == null) {
        input = Paths.get(System.getProperty("java.io.tmpdir"), "contributors.csv");
    }/*from  ww  w. j av a2s .  c om*/
    if (!Files.isReadable(input)) {
        return;
    }
    try (CSVReader reader = new CSVReader(Files.newBufferedReader(input, Charset.defaultCharset()), '\t')) {
        // Check header
        String[] header = reader.readNext();
        if (!ArrayUtils.isEquals(CSV_HEADER, header)) {
            log.warn("Header mismatch " + Arrays.toString(header));
            return;
        }
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            Developer dev = parse(nextLine);
            if (dev.isAnonymous()) {
                developersByName.put(dev.getName(), dev);
            } else {
                developersByLogin.put(dev.getLogin(), dev);
            }
        }
        for (Developer dev : developersByLogin.values()) {
            for (String alias : dev.getAliases()) {
                if (developersByLogin.containsKey(alias)) {
                    developersByLogin.get(alias).updateWith(dev);
                }
            }
        }
        for (Developer dev : developersByName.values()) {
            for (String alias : dev.getAliases()) {
                if (developersByLogin.containsKey(alias)) {
                    developersByLogin.get(alias).updateWith(dev);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        try {
            Files.copy(input, input.resolveSibling(input.getFileName() + ".bak"),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e1) {
            log.error(e1.getMessage(), e1);
        }
    }
}

From source file:ddf.catalog.impl.operations.OperationsCrudSupport.java

void generateMetacardAndContentItems(StorageRequest storageRequest, List<ContentItem> incomingContentItems,
        Map<String, Metacard> metacardMap, List<ContentItem> contentItems, Map<String, Path> tmpContentPaths)
        throws IngestException {
    for (ContentItem contentItem : incomingContentItems) {
        try {/*from   ww w  .java  2s  .  c  o  m*/
            Path tmpPath = null;
            long size;
            try (InputStream inputStream = contentItem.getInputStream()) {
                if (inputStream == null) {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }

                String sanitizedFilename = InputValidation.sanitizeFilename(contentItem.getFilename());
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename),
                        FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);
                tmpContentPaths.put(contentItem.getId(), tmpPath);
            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath);

            if (!InputValidation.checkForClientSideVulnerableMimeType(mimeTypeRaw)) {
                throw new IngestException("Unsupported mime type.");
            }

            String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename());
            Metacard metacard = generateMetacard(mimeTypeRaw, contentItem.getId(), fileName,
                    (Subject) storageRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT), tmpPath);
            metacardMap.put(metacard.getId(), metacard);

            ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(),
                    com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size,
                    metacard);
            contentItems.add(generatedContentItem);
        } catch (Exception e) {
            tmpContentPaths.values().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java

public Path copyBundle(final Path extractedGitBundle, final Map<String, String> metadata) throws IOException {

    final Path bundleDestination = buildBundleDestination(metadata);

    LOGGER.debug("Copying received bundle from temporary location " + extractedGitBundle + " to "
            + bundleDestination);/*from   ww  w.ja v  a2 s  .c  o  m*/
    if (Files.exists(bundleDestination)) {
        Files.copy(extractedGitBundle, bundleDestination, StandardCopyOption.REPLACE_EXISTING);
    } else {
        Files.createDirectories(bundleDestination.getParent());
        Files.copy(extractedGitBundle, bundleDestination);
    }

    registerCreatedFile(extractedGitBundle.toFile());
    registerCreatedFile(bundleDestination.toFile());

    return bundleDestination;
}

From source file:com.datastax.loader.CqlDelimLoadTask.java

private void cleanup(boolean success) throws IOException {
    if (null != badParsePrinter) {
        if (format.equalsIgnoreCase("jsonarray"))
            badParsePrinter.println("]");
        badParsePrinter.close();/*from   w  ww  . j  a  va  2s  .c o  m*/
    }
    if (null != badInsertPrinter) {
        if (format.equalsIgnoreCase("jsonarray"))
            badInsertPrinter.println("]");
        badInsertPrinter.close();
    }
    if (null != logPrinter)
        logPrinter.close();
    if (success) {
        if (null != successDir) {
            Path src = infile.toPath();
            Path dst = Paths.get(successDir);
            Files.move(src, dst.resolve(src.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        if (null != failureDir) {
            Path src = infile.toPath();
            Path dst = Paths.get(failureDir);
            Files.move(src, dst.resolve(src.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java

@Override
public void getFile(final String name, final Path destination) throws IOException {
    FileAccess.copy(this.storage.getPath().resolve("chroot").resolve(name), destination,
            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}

From source file:org.tallison.cc.CCGetter.java

private void fetch(CCIndexRecord r, Path rootDir, BufferedWriter writer) throws IOException {
    Path targFile = rootDir.resolve(r.getDigest().substring(0, 2) + "/" + r.getDigest());

    if (Files.isRegularFile(targFile)) {
        writeStatus(r, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        logger.info("already retrieved:" + targFile.toAbsolutePath());
        return;//w  w w . j a  v a2  s .  c  om
    }

    String url = AWS_BASE + r.getFilename();
    URI uri = null;
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        logger.warn("Bad url: " + url);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpHost target = new HttpHost(uri.getHost());
    String urlPath = uri.getRawPath();
    if (uri.getRawQuery() != null) {
        urlPath += "?" + uri.getRawQuery();
    }
    HttpGet httpGet = null;
    try {
        httpGet = new HttpGet(urlPath);
    } catch (Exception e) {
        logger.warn("bad path " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.BAD_URL, writer);
        return;
    }
    if (proxyHost != null && proxyPort > -1) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
    }
    httpGet.addHeader("Range", r.getOffsetHeader());
    HttpCoreContext coreContext = new HttpCoreContext();
    CloseableHttpResponse httpResponse = null;
    URI lastURI = null;
    try {
        httpResponse = httpClient.execute(target, httpGet, coreContext);
        RedirectLocations redirectLocations = (RedirectLocations) coreContext
                .getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
        if (redirectLocations != null) {
            for (URI redirectURI : redirectLocations.getAll()) {
                lastURI = redirectURI;
            }
        } else {
            lastURI = httpGet.getURI();
        }
    } catch (IOException e) {
        logger.warn("IOException for " + uri.toString(), e);
        writeStatus(r, FETCH_STATUS.FETCHED_IO_EXCEPTION, writer);
        return;
    }
    lastURI = uri.resolve(lastURI);

    if (httpResponse.getStatusLine().getStatusCode() != 200
            && httpResponse.getStatusLine().getStatusCode() != 206) {
        logger.warn("Bad status for " + uri.toString() + " : " + httpResponse.getStatusLine().getStatusCode());
        writeStatus(r, FETCH_STATUS.FETCHED_NOT_200, writer);
        return;
    }
    Path tmp = null;
    Header[] headers = null;
    boolean isTruncated = false;
    try {
        //this among other parts is plagiarized from centic9's CommonCrawlDocumentDownload
        //probably saved me hours.  Thank you, Dominik!
        tmp = Files.createTempFile("cc-getter", "");
        try (InputStream is = new GZIPInputStream(httpResponse.getEntity().getContent())) {
            WARCRecord warcRecord = new WARCRecord(new FastBufferedInputStream(is), "", 0);
            ArchiveRecordHeader archiveRecordHeader = warcRecord.getHeader();
            if (archiveRecordHeader.getHeaderFields().containsKey(WARCConstants.HEADER_KEY_TRUNCATED)) {
                isTruncated = true;
            }
            headers = LaxHttpParser.parseHeaders(warcRecord, "UTF-8");

            Files.copy(warcRecord, tmp, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        writeStatus(r, null, headers, 0L, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_READING_ENTITY,
                writer);
        deleteTmp(tmp);
        return;
    }

    String digest = null;
    long tmpLength = 0l;
    try (InputStream is = Files.newInputStream(tmp)) {
        digest = base32.encodeAsString(DigestUtils.sha1(is));
        tmpLength = Files.size(tmp);
    } catch (IOException e) {
        writeStatus(r, null, headers, tmpLength, isTruncated, FETCH_STATUS.FETCHED_IO_EXCEPTION_SHA1, writer);
        logger.warn("IOException during digesting: " + tmp.toAbsolutePath());
        deleteTmp(tmp);
        return;
    }

    if (Files.exists(targFile)) {
        writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ALREADY_IN_REPOSITORY, writer);
        deleteTmp(tmp);
        return;
    }
    try {
        Files.createDirectories(targFile.getParent());
        Files.copy(tmp, targFile);
    } catch (IOException e) {
        writeStatus(r, digest, headers, tmpLength, isTruncated,
                FETCH_STATUS.FETCHED_EXCEPTION_COPYING_TO_REPOSITORY, writer);
        deleteTmp(tmp);

    }
    writeStatus(r, digest, headers, tmpLength, isTruncated, FETCH_STATUS.ADDED_TO_REPOSITORY, writer);
    deleteTmp(tmp);
}