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.esri.gpt.control.rest.ManageDocumentServlet.java

private boolean saveXml2Package(String xml, String uuid) throws IOException {
    uuid = UuidUtil.removeCurlies(uuid);
    //xml file/*from w  w  w  .  j ava  2  s.c o m*/
    String folder = Constant.UPLOAD_FOLDER;

    File temp = new File(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME);
    InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
    //InputStream in = doc.newInputStream();
    Path a = temp.toPath();
    Files.copy(in, a, java.nio.file.StandardCopyOption.REPLACE_EXISTING);

    //copy xml file into zip file
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    Path path = null;
    path = Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_ZIP_NAME);
    URI uri = URI.create("jar:" + path.toUri());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        Files.copy(Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME),
                fs.getPath(Constant.XML_OUTPUT_FILE_NAME), StandardCopyOption.REPLACE_EXISTING);
    }

    return true;
}

From source file:io.personium.core.model.impl.fs.DavCmpFsImpl.java

/**
 * process MOVE operation.// ww w. jav  a  2s  . c o m
 * @param etag
 *            ETag Value
 * @param overwrite
 *            whether or not overwrite the target resource
 * @param davDestination
 *            Destination information.
 * @return ResponseBuilder Response Object
 */
@Override
public ResponseBuilder move(String etag, String overwrite, DavDestination davDestination) {
    ResponseBuilder res = null;

    // 
    Lock lock = this.lock();
    try {
        // ??
        this.load();
        if (!this.exists()) {
            // ?(??)????
            // ??????404??
            throw getNotFoundException().params(this.getUrl());
        }
        // etag????????*??????????????
        if (etag != null && !"*".equals(etag) && !matchesETag(etag)) {
            throw PersoniumCoreException.Dav.ETAG_NOT_MATCH;
        }

        // ?DavNode?????DavNode??????????????
        // ???DavNode???????????
        // this.parent.nodeId = this.metaFile.getParentId();
        // this.parent.load();
        // if (this.parent.metaFile == null) {
        // throw getNotFoundException().params(this.parent.getUrl());
        // }

        // ?
        davDestination.loadDestinationHierarchy();
        // ??
        davDestination.validateDestinationResource(overwrite, this);

        // MOVE????Box?????????????
        // ??????Object?????
        // ?????????
        AccessContext ac = davDestination.getDestinationRsCmp().getAccessContext();
        // ??
        // ?????????????
        // 1.??ES???????????????????
        // 2.?????????????ES??????
        davDestination.getDestinationRsCmp().getParent().checkAccessContext(ac, BoxPrivilege.WRITE);

        File destDir = ((DavCmpFsImpl) davDestination.getDestinationCmp()).fsDir;
        if (!davDestination.getDestinationCmp().exists()) {
            Files.move(this.fsDir.toPath(), destDir.toPath());
            res = javax.ws.rs.core.Response.status(HttpStatus.SC_CREATED);
        } else {
            FileUtils.deleteDirectory(destDir);
            Files.move(this.fsDir.toPath(), destDir.toPath(), StandardCopyOption.REPLACE_EXISTING);
            res = javax.ws.rs.core.Response.status(HttpStatus.SC_NO_CONTENT);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        // UNLOCK
        lock.release();
        log.debug("unlock");
    }

    res.header(HttpHeaders.LOCATION, davDestination.getDestinationUri());
    res.header(HttpHeaders.ETAG, this.getEtag());
    return res;
}

From source file:ddf.catalog.impl.CatalogFrameworkImpl.java

private 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  . j  a  v a2 s.c  o  m*/
            Path tmpPath = null;
            long size;
            try {
                if (contentItem.getInputStream() != null) {
                    tmpPath = Files.createTempFile(FilenameUtils.getBaseName(contentItem.getFilename()),
                            FilenameUtils.getExtension(contentItem.getFilename()));
                    Files.copy(contentItem.getInputStream(), tmpPath, StandardCopyOption.REPLACE_EXISTING);
                    size = Files.size(tmpPath);
                    tmpContentPaths.put(contentItem.getId(), tmpPath);
                } else {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }
            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            } finally {
                IOUtils.closeQuietly(contentItem.getInputStream());
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, contentItem.getFilename(), tmpPath);

            String fileName = updateFileExtension(mimeTypeRaw, contentItem.getFilename());
            Metacard metacard = generateMetacard(mimeTypeRaw, contentItem.getId(), fileName, size,
                    (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().stream().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:misc.FileHandler.java

/**
 * Writes the given synchronization version to the version file which
 * belongs to the given file name. The version file is created, if it does
 * not exist yet. Returns whether the version file was successfully written.
 * /*w  w w .ja v  a  2s.  c o m*/
 * @param version
 *            the version number up to which all actions have been executed.
 *            Must be at least <code>0</code>.
 * @param clientRoot
 *            the complete path to the client's root directory. Must exist.
 * @param syncRoot
 *            the complete path to the synchronization root directory. Must
 *            exist.
 * @param pathLocal
 *            the local path to synchronize containing an access bundle.
 *            Must be relative to <code>clientRoot</code>. May not be
 *            <code>null</code>.
 * @return <code>true</code>, if the version file was successfully written.
 *         Otherwise, <code>false</code>.
 */
public static boolean writeVersion(int version, Path clientRoot, Path syncRoot, Path pathLocal) {
    if (version < 0) {
        throw new IllegalArgumentException("version must be at least 0!");
    }
    if ((clientRoot == null) || !Files.isDirectory(clientRoot)) {
        throw new IllegalArgumentException("clientRoot must be an existing directory!");
    }
    if ((syncRoot == null) || !Files.isDirectory(syncRoot)) {
        throw new IllegalArgumentException("syncRoot must be an existing directory!");
    }
    if (pathLocal == null) {
        throw new NullPointerException("pathLocal may not be null!");
    }

    boolean success = false;
    Path arbitraryFileName = Paths.get(pathLocal.toString(), "arbitrary");
    Path accessBundleDirectory = FileHandler.getAccessBundleDirectory(clientRoot, arbitraryFileName);

    if (accessBundleDirectory != null) {
        Path versionFile = Paths.get(syncRoot.toString(), accessBundleDirectory.toString(),
                SynchronizationExecutor.VERSION_FILE);
        FileHandler.makeParentDirs(versionFile);

        /*
         * Write the new version into a temporary file and rename it to the
         * version file.
         */
        Path tempFile = FileHandler.getTempFile(versionFile);

        if (tempFile != null) {
            try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Coder.CHARSET);) {
                writer.write(String.valueOf(version));
                writer.write('\n');
                writer.flush();
                Files.move(tempFile, versionFile, StandardCopyOption.REPLACE_EXISTING);
                success = true;
            } catch (IOException e) {
                Logger.logError(e);
            } finally {
                if (tempFile != null) {
                    try {
                        Files.deleteIfExists(tempFile);
                    } catch (IOException e) {
                        Logger.logError(e);
                    }
                }
            }
        }
    }

    return success;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*  w  w  w  . j av a  2 s.  com*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:adalid.util.velocity.BaseBuilder.java

private void copy(String source, String target) throws IOException {
    Path sourcePath = Paths.get(source);
    Path targetPath = Paths.get(target);
    //overwrite existing file, if exists
    CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES };
    Files.copy(sourcePath, targetPath, options);
}

From source file:org.deeplearning4j.models.embeddings.loader.WordVectorSerializer.java

/**
 * This method restores ParagraphVectors model previously saved with writeParagraphVectors()
 *
 * @return/*w ww.j  a v  a  2s  .c o  m*/
 */
public static ParagraphVectors readParagraphVectors(InputStream stream) throws IOException {
    File tmpFile = File.createTempFile("restore", "paravec");
    Files.copy(stream, Paths.get(tmpFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
    return readParagraphVectors(tmpFile);
}

From source file:ddf.test.itests.catalog.TestCatalog.java

@Test
public void testContentDirectoryMonitor() throws Exception {
    final String TMP_PREFIX = "tcdm_";
    Path tmpDir = Files.createTempDirectory(TMP_PREFIX);
    tmpDir.toFile().deleteOnExit();/*from  w w  w.  j  a  v a 2  s  .com*/
    Path tmpFile = Files.createTempFile(tmpDir, TMP_PREFIX, "_tmp.xml");
    tmpFile.toFile().deleteOnExit();
    Files.copy(this.getClass().getClassLoader().getResourceAsStream("metacard5.xml"), tmpFile,
            StandardCopyOption.REPLACE_EXISTING);

    Map<String, Object> cdmProperties = new HashMap<>();
    cdmProperties.putAll(getMetatypeDefaults("content-core-directorymonitor",
            "org.codice.ddf.catalog.content.monitor.ContentDirectoryMonitor"));
    cdmProperties.put("monitoredDirectoryPath", tmpDir.toString() + "/");
    createManagedService("org.codice.ddf.catalog.content.monitor.ContentDirectoryMonitor", cdmProperties);

    long startTime = System.nanoTime();
    ValidatableResponse response = null;
    do {
        response = executeOpenSearch("xml", "q=*SysAdmin*");
        if (response.extract().xmlPath().getList("metacards.metacard").size() == 1) {
            break;
        }
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
        }
    } while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) < TimeUnit.MINUTES.toMillis(1));
    response.body("metacards.metacard.size()", equalTo(1));
}

From source file:managedBean.MbVNotas.java

public void guardarPago() {
        try {/*  w  w w . j a v  a  2  s .  c  om*/
            if ((!file.getFileName().equals("") && valor != null) && valor.doubleValue() > 0) {
                PagosDao pDao = new PagosDao();
                if (!pDao.existeComprobante(idComprobante)) {
                    Matricula m = new Matricula();
                    pago = new Pago();
                    m.setId(selectedNota.getIdMatricula());
                    pago.setValor(valor);
                    pago.setIdComprobante(idComprobante);
                    pago.setEstado('E');
                    Date fecha = new Date();
                    pago.setFecha(fecha);
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date dateobj = new Date();
                    String nombreCarpeta = selectedNota.getNombresEstudiante().trim();
                    String maest = removeCaractEspeciales(selectedNota.getDescripMaestria()).trim();
                    File directorio = new File("c:/Postgrado/pagos/" + maest + "/" + selectedNota.getIdMatricula()
                            + "-" + nombreCarpeta + "/");
                    if (!directorio.exists()) {
                        directorio.mkdirs();
                    }
                    String filename = selectedNota.getIdMatricula()
                            + (df.format(dateobj).replaceAll(":", "-")).trim();
                    String extension = FilenameUtils.getExtension(file.getFileName());
                    Path ruta = Paths.get(directorio + "/" + filename + "." + extension);
                    InputStream input = file.getInputstream();
                    Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
                    pago.setMatricula(m);
                    pago.setTipoPago(pDao.getTipoPago(idTipoPago));
                    pago.setRutaComprobante(ruta.toString());
                    pDao.registrar(pago);

                    FacesMessage message = new FacesMessage("Succesful", "Datos Guardados correctamente");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                } else {
                    FacesMessage message = new FacesMessage("Error", "El nmero de comprobante ya existe");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                }
            } else {
                valor = BigDecimal.valueOf(0.00);
                FacesMessage message = new FacesMessage("Error", "Ingrese datos");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        } catch (IOException ex) {
            Logger.getLogger(MbVNotas.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage message = new FacesMessage("Error", ex.toString());
            System.out.println(ex.toString());
            FacesContext.getCurrentInstance().addMessage(null, message);
        } catch (Exception ex) {
            Logger.getLogger(MbVNotas.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage message = new FacesMessage("Error", ex.toString());
            System.out.println(ex.toString());
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        idComprobante = "";
        valor = BigDecimal.valueOf(0.00);
        file = null;
    }

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * copies the directories./* ww  w. ja va  2s .  c om*/
 * 
 * @param src
 *            source-directory
 * @param dest
 *            destination-directory
 * @throws IOException
 *             IOException
 */
private void copyFolder(Path src, Path dest) throws IOException {
    if (Files.isDirectory(src)) {
        // if directory not exists, create it
        if (!Files.exists(dest)) {
            Files.createDirectory(dest);
        }
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(src);
        for (Path path : directoryStream) {
            Path srcFile = path;
            Path destFile = Paths.get(dest.toString() + "/" + path.getFileName());
            copyFolder(srcFile, destFile);
        }
    } else {
        Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
    }
}