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:io.lavagna.web.api.CardDataController.java

@ExpectPermission(Permission.CREATE_FILE)
@RequestMapping(value = "/api/card/{cardId}/file", method = RequestMethod.POST)
@ResponseBody//  w ww  . j  a va2 s.  c  o m
public List<String> uploadFiles(@PathVariable("cardId") int cardId,
        @RequestParam("files") List<MultipartFile> files, User user, HttpServletResponse resp)
        throws IOException {

    LOG.debug("Files uploaded: {}", files.size());

    if (!ensureFileSize(files)) {
        resp.setStatus(422);
        return Collections.emptyList();
    }

    List<String> digests = new ArrayList<>();
    for (MultipartFile file : files) {
        Path p = Files.createTempFile("lavagna", "upload");
        try (InputStream fileIs = file.getInputStream()) {
            Files.copy(fileIs, p, StandardCopyOption.REPLACE_EXISTING);
            String digest = DigestUtils.sha256Hex(Files.newInputStream(p));
            String contentType = file.getContentType() != null ? file.getContentType()
                    : "application/octet-stream";
            boolean result = cardDataService.createFile(file.getOriginalFilename(), digest, file.getSize(),
                    cardId, Files.newInputStream(p), contentType, user, new Date()).getLeft();
            if (result) {
                LOG.debug("file uploaded! size: {}, original name: {}, content-type: {}", file.getSize(),
                        file.getOriginalFilename(), file.getContentType());
                digests.add(digest);
            }
        } finally {
            Files.delete(p);
            LOG.debug("deleted temp file {}", p);
        }
    }
    eventEmitter.emitUploadFile(cardRepository.findBy(cardId).getColumnId(), cardId);
    return digests;
}

From source file:org.openecomp.sdnc.uebclient.SdncUebCallback.java

private void handleSuccessfulDownload(INotificationData data, String svcName, String resourceName,
        IArtifactInfo artifact, File spoolFile, File archiveDir) {

    if ((data != null) && (artifact != null)) {
        // Send Download Status
        IDistributionClientResult sendDownloadStatus = client.sendDownloadStatus(
                buildStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK));
    }/*from   w ww  .  ja va 2  s. com*/

    // If an override file exists, read that instead of the file we just downloaded
    ArtifactTypeEnum artifactEnum = ArtifactTypeEnum.YANG_XML;

    boolean toscaYamlType = false;
    if (artifact != null) {
        String artifactTypeString = artifact.getArtifactType();
        if (artifactTypeString.contains("TOSCA_TEMPLATE")) {
            toscaYamlType = true;
        }
    } else {
        if (spoolFile.toString().contains(".yml") || spoolFile.toString().contains(".csar")) {
            toscaYamlType = true;
        }
    }
    String overrideFileName = config.getOverrideFile();
    if ((overrideFileName != null) && (overrideFileName.length() > 0)) {
        File overrideFile = new File(overrideFileName);

        if (overrideFile.exists()) {
            artifactEnum = ArtifactTypeEnum.YANG_XML;
            spoolFile = overrideFile;
        }

    }

    if (toscaYamlType == true) {
        processToscaYaml(data, svcName, resourceName, artifact, spoolFile, archiveDir);

        try {
            Path source = spoolFile.toPath();
            Path targetDir = archiveDir.toPath();

            Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOG.warn("Could not move " + spoolFile.getAbsolutePath() + " to " + archiveDir.getAbsolutePath(),
                    e);
        }

        return;
    }

    // Process spool file
    Document spoolDoc = null;
    File transformedFile = null;

    // Apply XSLTs and get Doc object
    try {
        if (!spoolFile.isDirectory()) {
            transformedFile = applyXslts(spoolFile);
        }
    } catch (Exception e) {
        LOG.error("Caught exception trying to parse XML file", e);
    }

    if (transformedFile != null) {
        try {

            try {

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                spoolDoc = db.parse(transformedFile);
            } catch (Exception e) {
                LOG.error("Caught exception trying to parse transformed XML file "
                        + transformedFile.getAbsolutePath(), e);
            }

        } catch (Exception e) {
            LOG.error("Caught exception trying to deploy file", e);
        }
    }

    if (spoolDoc != null) {
        // Analyze file type
        SdncArtifactType artifactType = analyzeFileType(artifactEnum, spoolFile, spoolDoc);

        if (artifactType != null) {

            scheduleDeployment(artifactType, svcName, resourceName, artifact, spoolFile.getName(),
                    transformedFile);

        }

        // SDNGC-2660 : Move file to archive directory even if it is an unrecognized type so that
        // we do not keep trying and failing to process it.
        try {
            Path source = spoolFile.toPath();
            Path targetDir = archiveDir.toPath();

            Files.move(source, targetDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            LOG.warn("Could not move " + spoolFile.getAbsolutePath() + " to " + archiveDir.getAbsolutePath(),
                    e);
        }
    }

}

From source file:cc.arduino.Compiler.java

private void saveHex(String compiledSketch, String copyOfCompiledSketch, PreferencesMap prefs)
        throws RunnerException {
    try {/*  w  w w  . jav  a  2  s.  com*/
        compiledSketch = StringReplacer.replaceFromMapping(compiledSketch, prefs);
        copyOfCompiledSketch = StringReplacer.replaceFromMapping(copyOfCompiledSketch, prefs);
        copyOfCompiledSketch = copyOfCompiledSketch.replaceAll(":", "_");

        Path compiledSketchPath;
        Path compiledSketchPathInSubfolder = Paths.get(prefs.get("build.path"), "sketch", compiledSketch);
        Path compiledSketchPathInBuildPath = Paths.get(prefs.get("build.path"), compiledSketch);
        if (Files.exists(compiledSketchPathInSubfolder)) {
            compiledSketchPath = compiledSketchPathInSubfolder;
        } else if (Files.exists(compiledSketchPathInBuildPath)) {
            compiledSketchPath = compiledSketchPathInBuildPath;
        } else {
            return;
        }

        Path copyOfCompiledSketchFilePath = Paths.get(this.sketch.getFolder().getAbsolutePath(),
                copyOfCompiledSketch);

        Files.copy(compiledSketchPath, copyOfCompiledSketchFilePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RunnerException(e);
    }
}

From source file:org.roda.core.storage.AbstractStorageServiceTest.java

@Test(enabled = false)
protected void testBinaryContent(Binary binary, ContentPayload providedPayload)
        throws IOException, GenericException {
    // check if content is the same
    assertTrue(IOUtils.contentEquals(providedPayload.createInputStream(),
            binary.getContent().createInputStream()));

    Path tempFile = Files.createTempFile("test", ".tmp");
    Files.copy(binary.getContent().createInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

    // check size in bytes
    assertEquals(Long.valueOf(Files.size(tempFile)), binary.getSizeInBytes());

    if (binary.getContentDigest() != null) {
        for (Entry<String, String> entry : binary.getContentDigest().entrySet()) {
            String digest = FSUtils.computeContentDigest(tempFile, entry.getKey());
            assertEquals(digest, entry.getValue());
        }/*from w w w.j  a  v a 2  s . co m*/
    }

    // delete temp file
    Files.delete(tempFile);
}

From source file:com.hpe.application.automation.tools.pc.PcClient.java

public boolean downloadTrendReportAsPdf(String trendReportId, String directory) throws PcException {

    try {/*w  ww  .j  a  v  a2 s  . c  o m*/
        logger.println("Downloading trend report: " + trendReportId + " in PDF format");
        InputStream in = restProxy.getTrendingPDF(trendReportId);
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = directory + IOUtils.DIR_SEPARATOR + "trendReport" + trendReportId + ".pdf";
        Path destination = Paths.get(filePath);
        Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
        logger.println("Trend report: " + trendReportId + " was successfully downloaded");
    } catch (Exception e) {

        logger.println("Failed to download trend report: " + e.getMessage());
        throw new PcException(e.getMessage());
    }

    return true;

}

From source file:org.bimserver.client.BimServerClient.java

public void downloadExtendedData(long edid, Path outputFile) throws IOException {
    try (InputStream downloadData = channel.getDownloadData(baseAddress, token, edid)) {
        Files.copy(downloadData, outputFile, StandardCopyOption.REPLACE_EXISTING);
    }//from   ww  w .j a v  a  2  s.  com
}

From source file:io.hops.hopsworks.api.zeppelin.server.ZeppelinConfig.java

private boolean copyBinDir() throws IOException {
    String source = settings.getZeppelinDir() + File.separator + "bin";
    File binDir = new File(binDirPath);
    File sourceDir = new File(source);
    if (binDir.list().length == sourceDir.list().length) {
        //should probably check if the files are the same
        return false;
    }//w  w w.ja  v  a2s  .  co m
    Path destinationPath;
    for (File file : sourceDir.listFiles()) {
        destinationPath = Paths.get(binDirPath + File.separator + file.getName());
        Files.copy(file.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
    }
    return binDir.list().length == sourceDir.list().length;
}

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

void copy(CryptoPath cleartextSource, CryptoPath cleartextTarget, CopyOption... options) throws IOException {
    if (cleartextSource.equals(cleartextTarget)) {
        return;//from  w  w  w. j  a v a2 s .  co m
    }
    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.copy(ciphertextSourceFile, ciphertextTargetFile, options);
    } else if (Files.exists(ciphertextSourceDirFile)) {
        // DIRECTORY (non-recursive as per contract):
        Path ciphertextTargetDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.DIRECTORY);
        if (!Files.exists(ciphertextTargetDirFile)) {
            // create new:
            createDirectory(cleartextTarget);
        } else if (ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING)) {
            // keep existing (if empty):
            Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
            try (DirectoryStream<Path> ds = Files.newDirectoryStream(ciphertextTargetDir)) {
                if (ds.iterator().hasNext()) {
                    throw new DirectoryNotEmptyException(cleartextTarget.toString());
                }
            }
        } else {
            throw new FileAlreadyExistsException(cleartextTarget.toString());
        }
        if (ArrayUtils.contains(options, StandardCopyOption.COPY_ATTRIBUTES)) {
            Path ciphertextSourceDir = cryptoPathMapper.getCiphertextDirPath(cleartextSource);
            Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
            copyAttributes(ciphertextSourceDir, ciphertextTargetDir);
        }
    } else {
        throw new NoSuchFileException(cleartextSource.toString());
    }
}

From source file:com.netflix.genie.agent.execution.statemachine.actions.SetUpJobAction.java

private File createJobEnvironmentFile(final File jobDirectory, final List<File> setUpFiles,
        final Map<String, String> serverProvidedEnvironment, final Map<String, String> extraEnvironment)
        throws SetUpJobException {
    final Path genieDirectory = PathUtils.jobGenieDirectoryPath(jobDirectory);
    final Path envScriptPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE);
    final Path envScriptLogPath = PathUtils.composePath(genieDirectory, JobConstants.LOGS_PATH_VAR,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_LOG_FILE_NAME);
    final Path envScriptOutputPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_OUTPUT_FILE_NAME);

    // Copy env script from resources to genie directory
    try {/*from  ww w .j a v  a2 s  .  c  o m*/
        Files.copy(new ClassPathResource(JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE).getInputStream(),
                envScriptPath, StandardCopyOption.REPLACE_EXISTING);
        // Make executable
        envScriptPath.toFile().setExecutable(true, true);
    } catch (final IOException e) {
        throw new SetUpJobException("Could not copy environment script resource: ", e);
    }

    // Set up process that executes the script
    final ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

    processBuilder.environment().putAll(serverProvidedEnvironment);
    processBuilder.environment().putAll(extraEnvironment);

    final List<String> commandArgs = Lists.newArrayList(envScriptPath.toString(),
            envScriptOutputPath.toString(), envScriptLogPath.toString());

    setUpFiles.forEach(f -> commandArgs.add(f.getAbsolutePath()));

    processBuilder.command(commandArgs);

    // Run the setup script
    final int exitCode;
    try {
        exitCode = processBuilder.start().waitFor();
    } catch (final IOException e) {
        throw new SetUpJobException("Could not execute environment setup script", e);
    } catch (final InterruptedException e) {
        throw new SetUpJobException("Interrupted while waiting for environment setup script", e);
    }

    if (exitCode != 0) {
        throw new SetUpJobException("Non-zero exit code from environment setup script: " + exitCode);
    }

    // Check and return the output file
    final File envScriptOutputFile = envScriptOutputPath.toFile();

    if (!envScriptOutputFile.exists()) {
        throw new SetUpJobException("Expected output file does not exist: " + envScriptOutputPath.toString());
    }

    return envScriptOutputFile;
}

From source file:controladores.InscripcionBean.java

public void guardarArchivos() {

    try {/*from w  w  w  .  j a  v  a2s. co m*/

        for (SelectItem i : items) {
            if (i.getValue().toString().equals(idMaestria)) {
                descripcionMaetria = i.getLabel();
            }
        }
        PromocionDao pD = new PromocionDao();
        descripcionPromo = pD.getPromocion(idPromo).getDescripcion().toString();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateobj = new Date();
        String nombreCarpeta = (descripcionMaetria + "-" + descripcionPromo + "-" + estudiante.getApellidos()
                + " " + estudiante.getNombres() + "-" + df.format(dateobj).replaceAll(":", "-")).trim();
        File directorio = new File("c:/Postgrado/inscripciones/requisitos/" + nombreCarpeta + "/");
        if (!directorio.exists()) {
            directorio.mkdirs();
        }
        int cont = 0;
        ArchivosDao aDao = new ArchivosDao();
        for (UploadedFile f : files) {
            filename = reqPro.get(cont).getRequisitos().getFormato();
            extension = FilenameUtils.getExtension(f.getFileName());
            Path ruta = Paths.get(directorio + "/" + filename + "." + extension);
            InputStream input = f.getInputstream();
            Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
            archivos = new Archivos();
            archivos.setRuta(ruta.toString());
            archivos.setRequisitosPromo(reqPro.get(cont));
            archivos.setSolicitudInscripcion(sInscripcion);
            aDao.insertar(archivos);
            cont++;
        }

        // resultado= "/faces/index?faces-redirect=true";
    } catch (IOException ex) {
        Logger.getLogger(InscripcionBean.class.getName()).log(Level.SEVERE, null, ex);
        FacesMessage message = new FacesMessage("Error", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
        //resultado ="";
    } catch (Exception ex) {
        Logger.getLogger(InscripcionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    files.clear();

}