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:de.ks.file.FileStore.java

public void saveInFileStore(FileReference ref, File file) {
    if (!file.exists()) {
        throw new IllegalArgumentException("File " + file + " has to exist");
    }//from ww  w . j  a v  a 2  s.  c o m
    if (ref.getMd5Sum() == null) {
        throw new IllegalArgumentException("MD5 sum has to be calculated");
    }

    Path dir = Paths.get(getFileStoreDir(), ref.getMd5Sum());
    try {
        Files.createDirectories(dir);
    } catch (IOException e) {
        log.error("Could not store create parent directory {}", dir, e);
        return;
    }

    Path targetPath = Paths.get(getFileStoreDir(), ref.getMd5Sum(), ref.getName());
    if (options.shouldCopy()) {
        try {
            Files.copy(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("could not copy {} to {}", file.toPath(), targetPath);
            throw new RuntimeException(e);
        }
    } else {
        try {
            Files.move(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("could not move {} to {}", file.toPath(), targetPath);
            throw new RuntimeException(e);
        }
    }
}

From source file:org.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * {@inheritDoc}//from  w  ww .  j  av  a  2  s .  co m
 */
@Override
public void run() {

    final Path tempArchiveFile = arguments.tempArchiveFile;
    final Path finalArchiveFile = arguments.finalArchiveFile;

    try (final ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(
            Files.newOutputStream(tempArchiveFile))) {

        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
        zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);

        final RepositoryElement repository = buildOrgUnitRepository(arguments.backup, arguments.userId);
        repository.setName("");

        zipRepository(repository, zipOutputStream, "");

        // TODO Delete existing previous organization file(s).

        // Renames temporary '.tmp' file to complete '.zip' file.
        Files.move(tempArchiveFile, finalArchiveFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (final Throwable t) {

        if (LOG.isErrorEnabled()) {
            LOG.error("An error occurred during backup archive generation process.", t);
        }

        try {

            Files.deleteIfExists(tempArchiveFile);
            Files.deleteIfExists(finalArchiveFile);

        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while deleting archive error file.", e);
            }
        }
    }
}

From source file:onl.area51.gfs.mapviewer.action.ImportGribAction.java

private void selectDestName(FTPClient client, FTPFile remoteFile) throws Exception {
    SwingUtilities.invokeLater(() -> {
        // Default to the remote file name
        fileChooser.setSelectedFile(new File(remoteFile.getName()));

        if (fileChooser.showSaveDialog(Main.getFrame()) == JFileChooser.APPROVE_OPTION) {
            File localFile = fileChooser.getSelectedFile();

            ProgressDialog.copy(remoteFile.getName(), remoteFile.getSize(),
                    () -> client.retrieveFileStream(remoteFile.getName()), () -> {
                        Main.setStatus("Disconnecting, transfer complete.");
                        SwingUtils.executeTask(client::close);
                        OpenGribAction.getInstance().open(localFile);
                    }, () -> {/*from w w w.j  a v  a  2s.c  om*/
                        Main.setStatus("Disconnecting, transfer failed");
                        SwingUtils.executeTask(client::close);
                    }, localFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } else {
            Main.setStatus("Disconnecting, no transfer performed.");
            SwingUtils.executeTask(client::close);
        }

    });
}

From source file:BluemixUtils.java

private static void copyPhotosInTempDir(List<ClassifierUnit> all, int minSize) throws IOException {
    for (ClassifierUnit unit : all) {
        File dir = new File(TMP_DIR + File.separator + unit.getName());
        dir.mkdir();//  ww w  .j  a  va  2  s. c o  m
        System.out.println("Copying files to " + dir.getAbsolutePath());
        File photosDir = new File(unit.getFolderWithImages());
        File[] photoes = photosDir.listFiles(filter);
        for (int i = 0; i < minSize; i++) {
            File source = photoes[i];
            System.out.println("Copying file " + photoes[i].getName());
            Files.copy(source.toPath(),
                    (new File(dir.getAbsolutePath() + File.separator + (i + 1)
                            + source.getName().substring(source.getName().indexOf(".")))).toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        }

    }
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private Entry<Date, File> downloadIfNewer(DataType dataType, Resource resource, CheckedFunction<Path, Path> fun)
        throws IOException {
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 0, 1));
    final String alias = dataType.name().toLowerCase();
    final File tmpDownloadedFile = new File(tmpDir, alias);
    final Date remoteLastModified = new Date(resource.lastModified());
    final long localLastModified = tmpDownloadedFile.exists() ? tmpDownloadedFile.lastModified() : -2;
    logger.info(/*from   w w  w.ja  v  a  2  s.co m*/
            "Local file for alias {}" + "\nPath: {}" + "\nExists: {}" + "\nLocal last-modified: {} "
                    + "\nRemote last modified: {}",
            alias, tmpDownloadedFile.getAbsolutePath(), tmpDownloadedFile.exists(),
            formatDate(localLastModified), formatDate(remoteLastModified.getTime()));

    if (!tmpDownloadedFile.exists() || remoteLastModified.getTime() > localLastModified) {
        logger.info("Downloading {}", resource.getURL());
        Files.copy(resource.getInputStream(), tmpDownloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        logger.info("Download complete");
    }

    final Path preppedFile = fun.apply(tmpDownloadedFile.toPath());
    Files.setLastModifiedTime(tmpDownloadedFile.toPath(), FileTime.fromMillis(remoteLastModified.getTime()));
    Files.setLastModifiedTime(preppedFile, FileTime.fromMillis(remoteLastModified.getTime()));
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 1, 1));
    return new AbstractMap.SimpleEntry<>(new Date(remoteLastModified.getTime()), preppedFile.toFile());
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUserNoController() {
    if (!isValidData()) {
        return;/*from w w  w  . j  a  v  a  2s .com*/
    }
    tfUsername.setEditable(false);
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    User objUser;
    if (mAvatar != null) {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if ((new ModelUser()).editItem(objUser)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    mUser = objUser;
    this.dispose();
}

From source file:org.roda.common.certification.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat)//from  ww w  .j a va2 s . co m
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, InvalidFormatException, XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setKey(pk);
    signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE);
    signatureConfig.setOpcPackage(pkg);

    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    si.confirmSignature();

    // boolean b = si.verifySignature();
    pkg.close();
    IOUtils.closeQuietly(is);

    return output;
}

From source file:org.roda.core.plugins.plugins.characterization.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat) throws IOException, GeneralSecurityException, InvalidFormatException,
        XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream is = new FileInputStream(keystore)) {
        ks.load(is, password.toCharArray());

        PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
        X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

        SignatureConfig signatureConfig = new SignatureConfig();
        signatureConfig.setKey(pk);/*w w w  .  ja  v  a 2s .  c  om*/
        signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));

        try (OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE)) {
            signatureConfig.setOpcPackage(pkg);

            SignatureInfo si = new SignatureInfo();
            si.setSignatureConfig(signatureConfig);
            si.confirmSignature();

            // boolean b = si.verifySignature();
        }
    }
    return output;
}

From source file:uk.ac.sanger.cgp.wwdocker.interfaces.Workflow.java

default void iniUpdate(List<File> inisFrom, BaseConfiguration config, HostStatus hs) {
    String iniBaseTo = config.getString("wfl_inis");
    if (!iniBaseTo.endsWith("/")) {
        iniBaseTo = iniBaseTo.concat("/");
    }/* w  w  w . j av a 2 s  . c o m*/
    iniBaseTo = iniBaseTo.concat(hs.name()).concat("/");
    File dirCreate = new File(iniBaseTo);
    if (!dirCreate.exists()) {
        if (!dirCreate.mkdirs()) {
            throw new RuntimeException("Failed to create full path: " + dirCreate.getAbsolutePath());
        }
    }
    for (File iniFrom : inisFrom) {
        File iniTo = new File(iniBaseTo.concat(iniFrom.getName()));
        try {
            Files.move(iniFrom.toPath(), iniTo.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.wso2.appserver.integration.tests.session.persistence.WSAS2060SessionPersistenceTestCase.java

@AfterClass(alwaysRun = true)
public void restoreServer() throws Exception {
    sessionCookie = loginLogoutClient.login();
    webAppAdminClient = new WebAppAdminClient(backendURL, sessionCookie);
    if (userMode.equals(TestUserMode.TENANT_USER)) {
        webAppAdminClient.deleteWebAppFile(HELLOWORLD_WEBAPP_NAME + ".war",
                asServer.getInstance().getHosts().get("default"));
    }//from   w  w w. j  a  v a2  s . com
    //Revert and restart only once
    --isRestarted;
    if (isRestarted == 0) {
        if (Files.exists(Paths.get(CONTEXT_XML_PATH + ".backup"))) {
            Files.move(Paths.get(CONTEXT_XML_PATH + ".backup"), Paths.get(CONTEXT_XML_PATH),
                    new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
        }
        if (Files.exists(Paths.get(CARBON_XML_PATH + ".backup"))) {
            Files.move(Paths.get(CARBON_XML_PATH + ".backup"), Paths.get(CARBON_XML_PATH),
                    new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
        }
        serverConfigurationManager.restartGracefully();
    }
}