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.fabric8.profiles.Profiles.java

/**
 * @param target       is the directory where resulting materialized profile configuration will be written to.
 * @param profileNames a list of profile names that will be combined to create the materialized profile.
 *//*from w ww .j a v  a 2 s . com*/
public void materialize(Path target, String... profileNames) throws IOException {
    ArrayList<String> profileSearchOrder = new ArrayList<>();
    for (String profileName : profileNames) {
        collectProfileNames(profileSearchOrder, profileName);
    }

    HashSet<String> files = new HashSet<>();
    for (String profileName : profileSearchOrder) {
        files.addAll(listFiles(profileName));
    }

    System.out.println("profile search order" + profileSearchOrder);
    System.out.println("files: " + files);
    for (String file : files) {
        try (InputStream is = materializeFile(file, profileSearchOrder)) {
            Files.copy(is, target.resolve(file), StandardCopyOption.REPLACE_EXISTING);
        }
    }

}

From source file:org.nuxeo.template.deckjs.DeckJSPDFConverter.java

@Override
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters)
        throws ConversionException {
    CommandLineExecutorService cles = Framework.getService(CommandLineExecutorService.class);
    CommandAvailability commandAvailability = cles
            .getCommandAvailability(DeckJSConverterConstants.PHANTOM_JS_COMMAND_NAME);
    if (!commandAvailability.isAvailable()) {
        return null;
    }/*from w  w w . j a v a  2s.  c om*/
    Blob blob = blobHolder.getBlob();
    File jsFile = null;
    try (CloseableFile inputFile = blob.getCloseableFile(".html")) {
        jsFile = Framework.createTempFile("phantomJsScript", ".js");
        try (InputStream is = TemplateBundleActivator
                .getResourceAsStream(DeckJSConverterConstants.DECK_JS2PDF_JS_SCRIPT_PATH)) {
            Files.copy(is, jsFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        Blob pdfOutput = Blobs.createBlobWithExtension(".pdf");
        pdfOutput.setMimeType("application/pdf");
        CmdParameters params = cles.getDefaultCmdParameters();
        params.addNamedParameter("jsFilePath", jsFile);
        params.addNamedParameter("inFilePath", inputFile.getFile());
        params.addNamedParameter("outFilePath", pdfOutput.getFile());
        ExecResult res = cles.execCommand("phantomjs", params);
        if (!res.isSuccessful()) {
            throw res.getError();
        }
        return new SimpleCachableBlobHolder(pdfOutput);
    } catch (CommandNotAvailable | IOException | CommandException e) {
        throw new ConversionException("PDF conversion failed", e);
    } finally {
        org.apache.commons.io.FileUtils.deleteQuietly(jsFile);
    }
}

From source file:org.wisdom.maven.utils.BundlePackager.java

/**
 * Creates the bundle.//  ww w  .ja  v a 2  s .c o m
 *
 * @param basedir the project's base directory
 * @param output  the output file
 * @throws IOException occurs when the bundle cannot be built correctly.
 */
public static void bundle(File basedir, File output) throws IOException {
    Properties properties = new Properties();
    // Loads the properties inherited from Maven.
    readMavenProperties(basedir, properties);
    // Loads the properties from the BND file.
    boolean provided = readInstructionsFromBndFiles(properties, basedir);
    if (!provided) {
        // No bnd files, set default valued
        populatePropertiesWithDefaults(basedir, properties);
    }

    // Integrate custom headers added by other plugins.
    mergeExtraHeaders(basedir, properties);

    // Instruction loaded, start the build sequence.
    final Jar[] jars = computeClassPath(basedir);
    final Set<String> elements = computeClassPathElement(basedir);

    File bnd = null;
    File ipojo = null;
    try {
        Builder builder = getOSGiBuilder(basedir, properties, jars);
        builder.build();

        reportErrors("BND ~> ", builder.getWarnings(), builder.getErrors());
        bnd = File.createTempFile("bnd-", ".jar");
        ipojo = File.createTempFile("ipojo-", ".jar");
        builder.getJar().write(bnd);
    } catch (Exception e) {
        throw new IOException("Cannot build the OSGi bundle", e);
    }

    Classpath classpath = new Classpath(elements);
    Pojoization pojoization = new Pojoization();
    pojoization.pojoization(bnd, ipojo, new File(basedir, "src/main/resources"), classpath.createClassLoader());
    reportErrors("iPOJO ~> ", pojoization.getWarnings(), pojoization.getErrors());

    Files.move(Paths.get(ipojo.getPath()), Paths.get(output.getPath()), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.anritsu.mcreleaseportal.utils.FileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  .ja v  a  2  s.c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    session.setAttribute("mcPackage", null);
    PrintWriter pw = response.getWriter();
    response.setContentType("text/plain");
    ServletFileUpload upload = new ServletFileUpload();
    try {
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();

            // Save input stream file for later use
            File dir = new File(Configuration.getInstance().getSavePath());
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdir();
                LOGGER.log(Level.INFO, "Changes.xml archive directory was created at " + dir.getAbsolutePath());
            }
            String fileName = request.getSession().getId() + "_" + System.currentTimeMillis();
            File file = new File(dir, fileName);
            file.createNewFile();
            Path path = file.toPath();
            Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
            LOGGER.log(Level.INFO, "changes.xml saved on disk as: " + file.getAbsolutePath());

            // Save filename to session for next calls
            session.setAttribute("xmlFileLocation", file.getAbsolutePath());
            LOGGER.log(Level.INFO, "changes.xml saved on session as: fileName:" + file.getAbsolutePath());

            // Cleanup
            stream.close();

        }

    } catch (FileUploadException | IOException | RuntimeException e) {
        pw.println(
                "An error occurred when trying to process uploaded file! \n Please check the file consistency and try to re-submit. \n If the error persist pleace contact system administrator!");
    }
}

From source file:dialog.DialogFunctionUser.java

private void actionAddUserNoController() {
    if (!isValidData()) {
        return;//from w  ww  . j av  a 2s  .  com
    }
    if (isExistUsername(tfUsername.getText())) {
        JOptionPane.showMessageDialog(null, "Username  tn ti", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = new String(tfPassword.getPassword());
    password = LibraryString.md5(password);
    int role = cbRole.getSelectedIndex();
    User objUser;
    if (mAvatar != null) {
        objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                + FilenameUtils.getExtension(mAvatar.getName());
        Path source = Paths.get(mAvatar.toURI());
        Path destination = Paths.get("files/" + fileName);
        try {
            Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ex) {
            Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), "");
    }
    if ((new ModelUser()).addItem(objUser)) {
        ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
        JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success",
                JOptionPane.INFORMATION_MESSAGE, icon);
    } else {
        JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail",
                JOptionPane.ERROR_MESSAGE);
    }
    this.dispose();
}

From source file:cz.etnetera.reesmo.writer.storage.FileSystemStorage.java

@Override
protected Result createResult(String projectKey, Result result, List<Object> attachments)
        throws StorageException {
    File baseDir = this.baseDir;
    File resultDir = createModelDir(baseDir, result);

    createModelFile(resultDir, result);/*  ww w  .ja  v a 2  s.com*/
    if (projectKey != null)
        createModelProjectKeyFile(resultDir, result, projectKey);

    if (attachments != null && !attachments.isEmpty()) {
        File resultAttachmentDir = createResultAttachmentDir(resultDir);
        for (Object attachment : attachments) {
            if (attachment instanceof File) {
                try {
                    Files.copy(((File) attachment).toPath(), resultAttachmentDir.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new StorageException("Unable to copy result attachment file: " + attachment, e);
                }
            } else if (attachment instanceof ExtendedFile) {
                ExtendedFile file = (ExtendedFile) attachment;
                File targetFile = new File(resultAttachmentDir, file.getPath());
                targetFile.mkdirs();
                try {
                    Files.copy(file.getFile().toPath(), targetFile.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new StorageException("Unable to copy result attachment file: " + attachment, e);
                }
            } else {
                throw new StorageException("Unsupported attachment type: " + attachment.getClass());
            }
        }
    }

    createModelReadyFile(resultDir, result);
    result.setId(createModelId(resultDir));

    return result;
}

From source file:io.github.tsabirgaliev.ZipperInputStreamTest.java

public void testFileSystemOutput() throws IOException {
    ZipperInputStream lzis = new ZipperInputStream(enumerate(file1, file2));

    Files.copy(lzis, Paths.get("target", "output.zip"), StandardCopyOption.REPLACE_EXISTING);
}

From source file:ch.silviowangler.dox.web.admin.RepositoryControllerTest.java

@Test
public void testGetDocument2() throws Exception {

    final File file = folder.newFile("hello.txt");

    InputStream in = new ByteArrayInputStream("hello".getBytes());
    Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);

    when(response.getOutputStream()).thenReturn(outputStream);
    doThrow(new IOException()).when(outputStream).write(any(byte[].class), any(int.class), any(int.class));

    when(doxExporter.export()).thenReturn(file);
    when(mimeTypes.getProperty("zip")).thenReturn("my content type");

    controller.getDocument(this.response);
    verify(response).setStatus(SC_INTERNAL_SERVER_ERROR);
}

From source file:org.ng200.openolympus.controller.task.TaskFilesystemManipulatingController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
private void extractZipFile(final InputStream zipFile, final Path destination) throws Exception {
    try (ArchiveInputStream input = new ArchiveStreamFactory()
            .createArchiveInputStream(new BufferedInputStream(zipFile))) {
        ArchiveEntry entry;// w  w w  .ja  v a 2s . co m
        while ((entry = input.getNextEntry()) != null) {
            final Path dest = destination.resolve(entry.getName());
            if (entry.isDirectory()) {
                FileAccess.createDirectories(dest);
            } else {
                FileAccess.createDirectories(dest.getParent());
                FileAccess.createFile(dest);
                Files.copy(input, dest, StandardCopyOption.REPLACE_EXISTING);
            }
        }
    }
}

From source file:org.apdplat.superword.extract.SynonymAntonymExtractor.java

public static Set<SynonymAntonym> parseZip(String zipFile) {
    Set<SynonymAntonym> data = new HashSet<>();
    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.jav  a2s  .  com
                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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

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