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.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

/**
 * ?aapt`declared here is not defined`/*from   w ww . j av a 2  s . c  om*/
 * @param errInfo
 * @param rootDir
 */
private boolean fuckNotDefinedRes(String errInfo, String rootDir) {
    if (ShakaBuildOption.getInstance().isFuckNotDefinedRes()) {
        //Public symbol drawable/? declared here is not defined.
        Pattern patternRes = Pattern.compile("Public symbol (.+?) declared here is not defined");
        Matcher matcherRes = patternRes.matcher(errInfo);
        while (matcherRes.find()) {
            String res = matcherRes.group(1);
            String fileName = "res/" + res + ".xml";
            LogHelper.warning("Add temp res : " + fileName);
            notDefinedRes.add(fileName);
        }

        if (notDefinedRes.size() > 0) {
            for (String resName : notDefinedRes) {
                Path des = Paths.get(rootDir + File.separator + resName);
                // ??
                des.toFile().getParentFile().mkdirs();
                InputStream is = this.getClass().getResourceAsStream(SHAKA_XML);
                try {
                    Files.copy(is, des, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                IOUtils.closeQuietly(is);
            }

            return true;
        }
    }
    return false;
}

From source file:org.apdplat.superword.tools.WordClassifier.java

public static void parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override/*from w  w w  .  j  a  va2 s.  c o  m*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
}

From source file:controladores.prueba.java

public void handleFileUpload(FileUploadEvent event) {

    UploadedFile file = event.getFile();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date dateobj = new Date();
    String nombreFecha = (df.format(dateobj).replaceAll(":", "-"));
    Path path = Paths.get("D:\\Postgrado\\inscripciones\\requisitos\\" + nombreFecha.trim());
    //if directory exists?
    if (!Files.exists(path)) {
        try {/*from  w w  w  .java2  s  . c  om*/
            Files.createDirectories(path);
        } catch (IOException e) {
            //fail to create directory
            e.printStackTrace();
        }
    }
    String filename = file.getFileName();
    //         String extension = f.getContentType();
    Path ruta = Paths.get(path + "\\" + filename);

    try (InputStream input = file.getInputstream()) {
        Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
        FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, message);
    } catch (IOException ex) {
        Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
        FacesMessage message = new FacesMessage("Succesful", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}

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

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

                if (!InputValidation.isFileNameClientSideSafe(fileName)) {
                    throw new IngestException("Ignored filename found.");
                }

                String sanitizedFilename = InputValidation.sanitizeFilename(fileName);
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename),
                        FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);

                final String key = contentItem.getId();
                Map<String, Path> pathAndQualifiers = tmpContentPaths.get(key);

                if (pathAndQualifiers == null) {
                    pathAndQualifiers = new HashMap<>();
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                    tmpContentPaths.put(key, pathAndQualifiers);
                } else {
                    pathAndQualifiers.put(contentItem.getQualifier(), 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, fileName, tmpPath);

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

            // If any sanitization was done, rename file name to sanitized file name.
            if (!InputValidation.sanitizeFilename(fileName).equals(fileName)) {
                fileName = InputValidation.sanitizeFilename(fileName);
            } else {
                fileName = updateFileExtension(mimeTypeRaw, fileName);
            }

            Metacard metacard;
            boolean qualifiedContent = StringUtils.isNotEmpty(contentItem.getQualifier());
            if (qualifiedContent) {
                metacard = contentItem.getMetacard();
            } else {
                metacard = metacardFactory.generateMetacard(mimeTypeRaw, contentItem.getId(), fileName,
                        tmpPath);
            }
            metacardMap.put(metacard.getId(), metacard);

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

From source file:org.opencb.opencga.storage.core.variant.VariantStorageBaseTest.java

public static URI getResourceUri(String resourceName) throws IOException {
    Path rootDir = getTmpRootDir();
    Path resourcePath = rootDir.resolve(resourceName);
    if (!resourcePath.getParent().toFile().exists()) {
        Files.createDirectory(resourcePath.getParent());
    }//w  w  w  .  jav  a  2  s.co m
    if (!resourcePath.toFile().exists()) {
        Files.copy(VariantStorageManagerTest.class.getClassLoader().getResourceAsStream(resourceName),
                resourcePath, StandardCopyOption.REPLACE_EXISTING);
    }
    return resourcePath.toUri();
}

From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java

private void flush() {
    // Age out old state
    final DateTime now = DateTime.now();
    final DateTime oldest = now.minus(_retention);
    final long sizeBefore = _state.size();
    final Iterator<Map.Entry<String, Descriptor>> iterator = _state.entrySet().iterator();
    while (iterator.hasNext()) {
        final Map.Entry<String, Descriptor> entry = iterator.next();
        if (!oldest.isBefore(entry.getValue().getLastUpdated())) {
            // Remove old descriptors
            iterator.remove();//  w  ww  .j av a 2s . c  o m
        } else {
            // Mark retained descriptors as flushed
            entry.getValue().flush();
        }
    }
    final long sizeAfter = _state.size();
    if (sizeBefore != sizeAfter) {
        LOGGER.debug().setMessage("Removed old entries from file position store")
                .addData("sizeBefore", sizeBefore).addData("sizeAfter", sizeAfter).log();
    }

    // Persist the state to disk
    try {
        final Path temporaryFile = Paths.get(_file.toAbsolutePath().toString() + ".tmp");
        OBJECT_MAPPER.writeValue(temporaryFile.toFile(), _state);
        Files.move(temporaryFile, _file, StandardCopyOption.REPLACE_EXISTING);

        LOGGER.debug().setMessage("Persisted file position state to disk").addData("size", _state.size())
                .addData("file", _file).log();
    } catch (final IOException ioe) {
        throw Throwables.propagate(ioe);
    } finally {
        _lastFlush = now;
    }
}

From source file:com.netflix.nicobar.example.groovy2.GroovyModuleLoaderExample.java

private static void deployTestArchive(ArchiveRepository repository) throws IOException {
    InputStream archiveJarIs = GroovyModuleLoaderExample.class.getClassLoader()
            .getResourceAsStream(ARCHIVE_JAR_NAME);
    Path archiveToDeploy = Files.createTempFile(SCRIPT_MODULE_ID, ".jar");
    Files.copy(archiveJarIs, archiveToDeploy, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(archiveJarIs);/*from  w w  w .  ja v  a  2s  .  c om*/
    JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(archiveToDeploy).build();
    repository.insertArchive(jarScriptArchive);
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {//w w  w  .  jav  a  2s  .  c o  m
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:com.tocsi.images.ReceivedImageController.java

public void handleFileUpload(FileUploadEvent event) {
    if (event.getFile() != null) {
        try {/* w  ww  .j  a  v a  2 s. c  o  m*/
            UploadedFile uf = (UploadedFile) event.getFile();
            File folder = new File(GlobalsBean.destOriginal);
            //File folderThumb = new File(destThumbnail);
            String filename = FilenameUtils.getBaseName(uf.getFileName());
            String extension = FilenameUtils.getExtension(uf.getFileName());
            File file = File.createTempFile(filename + "-", "." + extension, folder);
            //File fileThumb = File.createTempFile(filename + "-", "." + extension, folderThumb);

            //resize image here
            BufferedImage originalImage = ImageIO.read(uf.getInputstream());
            InputStream is = uf.getInputstream();
            if (originalImage.getWidth() > 700) { //resize image if image's width excess 700px
                BufferedImage origImage = Scalr.resize(originalImage, Scalr.Method.QUALITY,
                        Scalr.Mode.FIT_TO_WIDTH, 640,
                        (int) ((originalImage.getHeight() / ((double) (originalImage.getWidth() / 700.0)))),
                        Scalr.OP_ANTIALIAS);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(origImage, extension, os);
                is = new ByteArrayInputStream(os.toByteArray());
            }

            //create thumbnail
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(uf.getInputstream()), 150);
            ByteArrayOutputStream osThumb = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, extension, osThumb);
            InputStream isThumbnail = new ByteArrayInputStream(osThumb.toByteArray());

            try (InputStream input = is) {
                Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            try (InputStream input = isThumbnail) {
                Files.copy(input, Paths.get(GlobalsBean.destThumbnail + GlobalsBean.separator + file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }

            //File chartFile = new File(file.getAbsolutePath());
            //chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/jpg");
            ImageBean ib = new ImageBean();
            ib.setFilename(file.getName());
            ib.setThumbFile(file.getName());
            ib.setImageFileLocation(GlobalsBean.destOriginal + GlobalsBean.separator + file.getName());
            imageList.add(ib);

        } catch (IOException | IllegalArgumentException | ImagingOpException ex) {
            Utilities.displayError(ex.getMessage());
        }
    }
}

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

@Test
public void testInstallCustomExtensionTwiceDontOverwrite() 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, "n");

    Assert.assertTrue("Expected output to contain \"already exists\"\n" + output,
            output.contains(" already exists"));
    Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output,
            output.contains(" installed successfully"));

    Assert.assertTrue(sampleCommandFile.lastModified() == 0);

    File extensionFile = extensionPath.toFile();

    Assert.assertFalse(extensionFile.lastModified() == 0);

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

    Assert.assertFalse(extensionFile.lastModified() == 0);
    Assert.assertTrue("Expected output to contain \"already exists\"\n" + output,
            output.contains(" already exists"));
    Assert.assertFalse("Expected output to not contain \"Overwriting\"\n" + output,
            output.contains("Overwriting"));
    Assert.assertFalse("Expected output to not contain \"installed successfully\"\n" + output,
            output.contains(" installed successfully"));
}