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.archiva.rest.services.DefaultRepositoriesService.java

private void copyFile(File sourceFile, File targetPath, String targetFilename, boolean fixChecksums)
        throws IOException {
    Files.copy(sourceFile.toPath(), new File(targetPath, targetFilename).toPath(),
            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

    if (fixChecksums) {
        fixChecksums(new File(targetPath, targetFilename));
    }/*from  w w  w. j ava2  s .c om*/
}

From source file:org.ligoj.app.plugin.prov.aws.ProvAwsTerraformService.java

private void copyFromTo(final Context context, final String from, final String... toFragments)
        throws IOException {
    Files.copy(toInput(from), utils.toFile(context.getSubscription(), toFragments).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Check for new versions of VirtMus.//from   www. j  a  v a 2 s .co  m
 * @param installId The random ID identifying this install.
 * @param prevVersion The previous version of VirtMus installed.
 * @param statsEnabled Set to true if the user is participating in stats collection.
 */
private static void checkForNewVersion(long installId, String prevVersion, UploadStats statsEnabled) {
    final String urlStr = pref.get(Options.OptCheckVersionUrl, CHECK_VERSION);

    // Catch redirects.
    HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() {
        @Override
        public void handlePermanentRedirect(HttpRequest request, HttpResponse response,
                HttpUriRequest redirect) {
            if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(urlStr)) {
                pref.put(Options.OptCheckVersionUrl, newUrl);
            }
        }
    };

    // TODO: Use http://wiki.fasterxml.com/JacksonHome to avoid warnings?
    String postData = new JSONStringer().object().key("version").value(MainApp.VERSION)
            /* installId MUST be sent as string since JS on the server
            side only has 64-bit float values and can't represent
            all long int values, leading to truncation of some digits
            since the JS float mantisa has only 53 bits (not 64).
            See: http://www.2ality.com/2012/07/large-integers.html
            */
            .key("installId").value(String.valueOf(installId)).key("prevVersion").value(prevVersion)
            .key("statsEnabled").value(statsEnabled.name()).endObject().toString();

    try {
        CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build();

        HttpPost post = new HttpPost(urlStr);
        addHttpHeaders(post);
        StringEntity entity = new StringEntity(postData, ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) { // 200
            if (statsEnabled == UploadStats.No) {
                // If the user doesn't want to participate, he probably doesn't
                // want to be checking for new releases either, so disable it.
                pref.putBoolean(Options.OptCheckVersion, false);
            }

            // This is used to notify the user that a newer version is available
            HttpEntity rspEntity = response.getEntity();
            if (rspEntity != null && statsEnabled != UploadStats.No) {
                File f = File.createTempFile("VersionPost", "html");
                f.deleteOnExit();
                Files.copy(rspEntity.getContent(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
                if (f.length() > 0) {
                    URL rspUrl = Utilities.toURI(f).toURL();
                    HtmlBrowser.URLDisplayer.getDefault().showURL(rspUrl);
                }
            }
        } else {
            Log.log(Level.INFO, "CheckVersion result: {0}", status);
        }

    } catch (MalformedURLException ex) {
        Log.log(ex);
    } catch (IOException ex) {
        Log.log(ex);
    }
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private void decodeBitmap(String filename) throws IOException {
    System.out.println("Decoding " + filename);

    File inputFile = new File(filename);
    File outputFile = new File(
            outputDirectory + File.separator + FilenameUtils.removeExtension(inputFile.getName()));

    FileInputStream fis = new FileInputStream(filename);
    //skip 6 bytes
    fis.skip(6);/*w w w  . j a v a  2 s . c  o  m*/
    //read the length we encoded
    int fileSize = EndianUtils.readSwappedInteger(fis);
    //skip the rest of the header
    fis.skip(44);
    Files.copy(fis, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    //truncate the file
    FileChannel outChan = new FileOutputStream(outputFile, true).getChannel();
    outChan.truncate(fileSize);
    outChan.close();

    //clean up
    if (isCleanUp()) {
        //delete the bitmap
        System.out.println("Deleting: " + inputFile);
        FileUtils.deleteQuietly(inputFile);
    }
}

From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java

/**
 * Logs to the logs directory a formatted CSV of the supplied list strings
 *///from  w ww . j a  v  a 2s .c o m
private void logIndexed(String repoName, List<String[]> reportList) {
    try {
        CSVWriter writer = new CSVWriter(
                new FileWriter(Singleton.getHelpers().getLogPath() + repoName + ".csv.tmp"));
        writer.writeAll(reportList);
        writer.flush();
        writer.close();

        Path source = Paths.get(Singleton.getHelpers().getLogPath() + repoName + ".csv.tmp");
        Files.move(source, source.resolveSibling(repoName + ".csv"), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " logIndexed for " + repoName + "\n with message: " + ex.getMessage());
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void move(CryptoPath cleartextSource, CryptoPath cleartextTarget, CopyOption... options) throws IOException {
    if (cleartextSource.equals(cleartextTarget)) {
        return;//from w  ww .  j av a 2  s .  com
    }
    Path ciphertextSourceFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.FILE);
    Path ciphertextSourceDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.DIRECTORY);
    if (Files.exists(ciphertextSourceFile)) {
        // FILE:
        Path ciphertextTargetFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.FILE);
        Files.move(ciphertextSourceFile, ciphertextTargetFile, options);
    } else if (Files.exists(ciphertextSourceDirFile)) {
        // DIRECTORY:
        Path ciphertextTargetDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.DIRECTORY);
        if (!ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING)) {
            // try to move, don't replace:
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        } else if (ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE)) {
            // replace atomically (impossible):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            throw new AtomicMoveNotSupportedException(cleartextSource.toString(), cleartextTarget.toString(),
                    "Replacing directories during move requires non-atomic status checks.");
        } else {
            // move and replace (if dir is empty):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            assert !ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE);
            if (Files.exists(ciphertextTargetDirFile)) {
                Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
                try (DirectoryStream<Path> ds = Files.newDirectoryStream(ciphertextTargetDir)) {
                    if (ds.iterator().hasNext()) {
                        throw new DirectoryNotEmptyException(cleartextTarget.toString());
                    }
                }
                Files.delete(ciphertextTargetDir);
            }
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        }
        dirIdProvider.move(ciphertextSourceDirFile, ciphertextTargetDirFile);
    } else {
        throw new NoSuchFileException(cleartextSource.toString());
    }
}

From source file:org.opencb.opencga.server.ws.FileWSServer.java

@GET
@Path("/{fileId}/set-header")
@ApiOperation(value = "Set file header", position = 10)
public Response setHeader(@PathParam(value = "fileId") @FormDataParam("fileId") int fileId,
        @ApiParam(value = "header", required = true) @DefaultValue("") @QueryParam("header") String header) {
    String content = "";
    DataInputStream stream;//from w  w w .ja v  a2  s .com
    QueryResult<File> fileQueryResult;
    InputStream streamBody = null;
    //        System.out.println("header: "+header);
    try {
        /** Obtain file uri **/
        File file = catalogManager.getFile(catalogManager.getFileId(String.valueOf(fileId)), sessionId)
                .getResult().get(0);
        URI fileUri = catalogManager.getFileUri(file);
        System.out.println("getUri: " + fileUri.getPath());

        /** Set header **/
        stream = catalogManager.downloadFile(fileId, sessionId);
        content = org.apache.commons.io.IOUtils.toString(stream);
        String lines[] = content.split(System.getProperty("line.separator"));
        StringBuilder body = new StringBuilder();
        body.append(header);
        body.append(System.getProperty("line.separator"));
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (!line.startsWith("#")) {
                body.append(line);
                if (i != lines.length - 1)
                    body.append(System.getProperty("line.separator"));
            }
        }
        /** Write/Copy  file **/
        streamBody = new ByteArrayInputStream(body.toString().getBytes(StandardCharsets.UTF_8));
        Files.copy(streamBody, Paths.get(fileUri), StandardCopyOption.REPLACE_EXISTING);

    } catch (Exception e) {
        return createErrorResponse(e);
    }
    //        createOkResponse(content, MediaType.TEXT_PLAIN)
    return createOkResponse(streamBody, MediaType.TEXT_PLAIN_TYPE);
}

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

public void quarantineMessages() {
    String notarchiveddir = Config.getFileSystem().getNoArchivePath();
    logger.debug("quarantineEmails {noarchivedpath='" + notarchiveddir + "'}");
    File noarchiveDir = new File(notarchiveddir);
    if (!noarchiveDir.exists())
        return;//from  w  w w.  ja  v a  2  s .c  om
    if (noarchiveDir.isDirectory()) {
        String[] children = noarchiveDir.list();
        if (children.length > 0)
            logger.warn("there are messages that require rearchival {notarchiveddirectory='" + notarchiveddir
                    + "'}");
        for (int i = 0; i < children.length; i++) {
            String filepath = notarchiveddir + File.separatorChar + children[i];
            logger.debug("attempting to quarantine file {path='" + filepath + "'}");
            try {
                copyEmailToQuarantine(new File(filepath));
            } catch (Exception e) {
                logger.error("failed to quarantine email (filepath='" + filepath + "'}", e);
                continue;
            }
            try {
                File delFile = new File(filepath);
                boolean deleted;
                deleted = delFile.delete();
                File tmpfile = null;
                if (!deleted)
                    //Mod start Seolhwa.kim 2017-04-13
                    //delFile.renameTo(File.createTempFile("oldrecovery", "tmp"));

                    tmpfile = File.createTempFile("oldrecovery", "tmp");

                try {
                    Files.move(Paths.get(delFile.getAbsolutePath()), Paths.get(tmpfile.getAbsolutePath()),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //Mod end Seolhwa.kim 2017-04-13

                delFile.deleteOnExit();
            } catch (IOException io) {
                logger.error("failed to delete email {filepath='" + filepath + "'");
            }
        }
    }
}

From source file:org.apache.archiva.web.api.DefaultFileUploadService.java

private void copyFile(File sourceFile, File targetPath, String targetFilename, boolean fixChecksums)
        throws IOException {

    Files.copy(sourceFile.toPath(), new File(targetPath, targetFilename).toPath(),
            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

    if (fixChecksums) {
        fixChecksums(new File(targetPath, targetFilename));
    }//from  ww  w.ja v a 2s. c o m
}

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

/**
 * Pull data files (pdb and images) for a given experiment
 * @param fileTreeXmlPath Path to XML file representing the project file tree
 * @param workflowXmlPath Path to XML file representing the experiment workflow
 * @param dataDirPath Path to directory used to store data files
 * @throws SAXException/*w  ww.j a  v a  2  s.c  o  m*/
 * @throws IOException
 * @throws XPathExpressionException 
 * @throws ParserConfigurationException 
 * @throws TransformerException 
 */
private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath)
        throws SAXException, IOException, XPathExpressionException, ParserConfigurationException,
        TransformerException {

    if (outputToConsole)
        System.out.println("Copying analysis data files...");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath);
    fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc);

    Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0);
    String dirPath = fileTreeRootElt.getAttribute("absolutePath");

    XPathReader xreader = new XPathReader(fileTreeDoc);

    //load XML representation of experiment workflow
    Document docWorkflow = docBuilder.parse(workflowXmlPath);
    docWorkflow = Utils.normalizeXmlDoc(docWorkflow);
    Element workflowRootElt = (Element) docWorkflow.getDocumentElement();

    //find main structure for display in Jmol
    Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath);
    if (jmolElt != null)
        workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true));

    //find analysis data
    NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS
            + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]",
            XPathConstants.NODESET);

    //add publication information
    //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild();
    //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher"));
    //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate"));

    //analysis data
    if (matchingFiles != null && matchingFiles.getLength() > 0) {
        Element dataElt = docWorkflow.createElement("analysis");
        workflowRootElt.appendChild(dataElt);

        Element imgElt = docWorkflow.createElement("images");
        Element pdbElt = docWorkflow.createElement("structures");
        Element csvElts = docWorkflow.createElement("spreadsheets");
        Element otherDataElts = docWorkflow.createElement("unknowns");

        dataElt.appendChild(imgElt);
        dataElt.appendChild(csvElts);
        dataElt.appendChild(pdbElt);
        dataElt.appendChild(otherDataElts);

        PlotGenerator plotTool = new PlotGenerator();

        for (int f = 0; f < matchingFiles.getLength(); f++) {
            Element fileNode = (Element) matchingFiles.item(f);
            String dataFilePath = fileNode.getAttribute("absolutePath");
            //copy file
            String dataFileNewName = dataFilePath.substring(dirPath.length() + 1)
                    .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
            String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
            Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath),
                    StandardCopyOption.REPLACE_EXISTING);
            //set read permissions
            if (!Utils.isWindows()) {
                HashSet<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                permissions.add(PosixFilePermission.OWNER_EXECUTE);
                permissions.add(PosixFilePermission.GROUP_READ);
                permissions.add(PosixFilePermission.OTHERS_READ);
                Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
            }
            //read file AVUs
            NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU",
                    XPathConstants.NODESET);
            MetadataAVUList avuList = new MetadataAVUList();
            if (avuNodes != null) {
                for (int a = 0; a < avuNodes.getLength(); a++) {
                    Element avuNode = (Element) avuNodes.item(a);
                    avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                            avuNode.getFirstChild().getNodeValue()));
                }
            }

            //add reference in XML doc
            String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
            String format = fileNode.getAttribute("format");
            if (IBIOMESFileGroup.isJmolFile(format)) {
                Element jmolFileElt = docWorkflow.createElement("structure");
                jmolFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    jmolFileElt.setAttribute("description", description);
                pdbElt.appendChild(jmolFileElt);
            } else if (format.equals(LocalFile.FORMAT_CSV)) {
                Element csvElt = docWorkflow.createElement("spreadsheet");
                csvElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    csvElt.setAttribute("description", description);
                csvElts.appendChild(csvElt);
                //try to generate plot and save image
                try {
                    String imgPath = dataFileNewName + "_plot.png";
                    String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList,
                            dataFileDestPath + "_plot", "png");
                    csvElt.setAttribute("plotPath", imgPath);
                    if (outputToConsole) {
                        if (plotType == null)
                            plotType = "";
                        else
                            plotType += " ";
                        System.out.println("\t" + plotType + "plot generated for " + dataFileNewName);
                    }

                } catch (Exception e) {
                    if (outputToConsole)
                        System.out.println(
                                "Warning: Plot for '" + dataFileDestPath + "' could not be generated.");
                    try {
                        if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole())
                            e.printStackTrace();
                    } catch (Exception e1) {
                    }
                }
            } else if (IBIOMESFileGroup.isImageFile(format)) {
                Element imgFileElt = docWorkflow.createElement("image");
                imgFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    imgFileElt.setAttribute("description", description);
                imgElt.appendChild(imgFileElt);
            } else {
                Element otherFileElt = docWorkflow.createElement("unknown");
                otherFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    otherFileElt.setAttribute("description", description);
                imgElt.appendChild(otherDataElts);
            }
        }
    }

    //update XML files
    File outputXmlAvusFile = new File(fileTreeXmlPath);
    if (outputXmlAvusFile.exists())
        outputXmlAvusFile.delete();

    File outputXmlWorkflowFile = new File(workflowXmlPath);
    if (outputXmlWorkflowFile.exists())
        outputXmlWorkflowFile.delete();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(fileTreeDoc);
    StreamResult result = null;
    result = new StreamResult(fileTreeXmlPath);
    transformer.transform(source, result);

    source = new DOMSource(docWorkflow);
    result = null;
    result = new StreamResult(outputXmlWorkflowFile);
    transformer.transform(source, result);
}