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:org.forgerock.openidm.maintenance.upgrade.FileStateCheckerTest.java

@Test
public void testUpdateStateRemoval() throws IOException, URISyntaxException, NoSuchAlgorithmException {
    Files.copy(Paths.get(getClass().getResource("/checksums2.csv").toURI()), tempFile,
            StandardCopyOption.REPLACE_EXISTING);
    ChecksumFile tempChecksumFile = new ChecksumFile(tempFile);
    FileStateChecker checker = new FileStateChecker(tempChecksumFile);
    Path filepath = Paths.get("file3");
    checker.updateState(filepath);//from   w  w  w  .  j  a  v  a2 s .c  o m
    checker = new FileStateChecker(tempChecksumFile);
    assertThat(checker.getCurrentFileState(filepath).equals(FileState.DELETED));
}

From source file:eu.eexcess.partnerwizard.webservice.WizardRESTService.java

@POST
@Path("updateConfigAndDeploy")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public boolean updateConfigAndDeploy(PartnerConfiguration config) {
    LOGGER.info("REST wizard/updateConfigAndDeploy called");
    if (config == null) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }//ww  w .j  av a  2  s. c o  m
    LOGGER.info("REST wizard/updateConfigAndDeploy config:\n" + config.toString());
    if (config.getTransformerClass() != null && !config.getTransformerClass().isEmpty()) {
        String artifactId = config.getTransformerClass();
        artifactId = artifactId.substring(artifactId.lastIndexOf(".") + 1);
        artifactId = artifactId.replace("Transformer", "");
        String copyTargetPath = Bean.PATH_BUILD_SANDBOX + artifactId + "\\src\\main\\resources\\";
        String dateString = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());

        LOGGER.info("artifactId:" + artifactId);
        LOGGER.info("copyTargetPath:" + copyTargetPath);

        // backup old config
        Charset charset = StandardCharsets.UTF_8;
        try {
            Files.copy(
                    Paths.get(copyTargetPath + "partner-config.json"), Paths.get(Bean.PATH_BUILD_SANDBOX
                            + artifactId + "-" + dateString + ".old.partner-config.json"),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // neues config reinkopieren
        try {
            String newFile = mapper.writeValueAsString(config);
            Files.write(Paths.get(copyTargetPath + "partner-config.json"), newFile.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // new config saving
        try {
            String newFile = mapper.writeValueAsString(config);
            Files.write(
                    Paths.get(Bean.PATH_BUILD_SANDBOX + artifactId + "-" + dateString + ".partner-config.json"),
                    newFile.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // build new version

        ArrayList<String> commands = new ArrayList<String>();
        commands.add("cd " + Bean.PATH_BUILD_SANDBOX);
        commands.add("cd " + artifactId);
        commands.add("mvn install -DskipTests");
        commands.add("cd target");
        String warName = "eexcess-partner-" + artifactId + "-*";
        commands.add("del %TOMCAT%webapps\\" + warName + "*.war");
        commands.add("rd /S /Q %TOMCAT%webapps\\" + warName);
        commands.add("xcopy " + warName + ".war %TOMCAT%webapps\\ /Y");
        this.cmdExecute(commands);

    }
    return true;
}

From source file:org.wso2.carbon.esb.rest.test.api.ESBJAVA4519TestCase.java

@Test(groups = { "wso2.esb" }, description = "Test whether file get restored after deployment failure")
public void testRestoringToPreviousConfigurationOnHotDeploymentFailure() throws Exception {

    boolean messageInLog = false;
    String esbApiPath = System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "repository"
            + File.separator + "deployment" + File.separator + "server" + File.separator + "synapse-configs"
            + File.separator + "default" + File.separator + "api" + File.separator + "CorruptedApi.xml";
    File esbApiFile = new File(esbApiPath);

    String corruptedApiPath = TestConfigurationProvider.getResourceLocation("ESB") + File.separator
            + "synapseconfig" + File.separator + "rest" + File.separator + "CorruptedApi.xml";
    File corruptedApiFile = new File(corruptedApiPath);

    String validApiPath = TestConfigurationProvider.getResourceLocation("ESB") + File.separator
            + "synapseconfig" + File.separator + "rest" + File.separator + "CorrectApi.xml";
    File validApiFile = new File(validApiPath);

    long startTime = System.currentTimeMillis();

    while ((startTime + 60000) > System.currentTimeMillis()) {
        log.info("Waiting for esb to persist the api config file...");
        if (esbApiFile.exists() && FileUtils.contentEquals(validApiFile, esbApiFile)) {
            log.info("Api Config is written to file system by esb. Waiting for hot deployment to pick up the "
                    + "resorted file as it will be taken as a restored file from esb.");
            Thread.sleep(30000);//from   w  w w . j  a  v  a 2 s .  c  o  m
            break;
        } else {
            Thread.sleep(20000);
        }
    }

    LogEvent[] logs;
    log.info("Copying the corrupted api config file...");
    Files.copy(corruptedApiFile.toPath(), esbApiFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    log.info("Copied the corrupted api config file to config folder.");
    for (int i = 0; i < 5; i++) {
        log.info("Checking for error logs in the esb..");
        logs = logViewerClient.getAllRemoteSystemLogs();
        for (LogEvent logEvent : logs) {
            String message = logEvent.getMessage();
            if (message.contains("Deployment of synapse artifact failed")) {
                log.info("Hot Deployment error log is printed in the ESB logs.");
                messageInLog = true;
                break;
            }
        }
        if (!messageInLog) {
            Thread.sleep(20000);
        } else {
            break;
        }
    }

    Assert.assertTrue(messageInLog, "Exception has occurred");
    messageInLog = false;
    logs = logViewerClient.getAllRemoteSystemLogs();
    for (LogEvent logEvent : logs) {
        String message = logEvent.getMessage();
        if (message.contains("Restoring the existing artifact into the file")) {
            messageInLog = true;
            break;
        }
    }
    Assert.assertTrue(messageInLog, "Original xml is not restored.");
}

From source file:com.github.podd.resources.test.DataReferenceAttachResourceImplTest.java

/**
 * Given the path to a resource containing an incomplete File Reference object, this method
 * constructs a complete File Reference and returns it as an RDF/XML string.
 *
 * @param fragmentSource//from   www.ja  v  a  2  s. com
 *            Location of resource containing incomplete File Reference
 * @return String containing RDF statements
 */
private String buildFileReferenceString(final String fragmentSource, final RDFFormat format,
        final Path testDirectory) throws Exception {
    // read the fragment's RDF statements into a Model
    final InputStream inputStream = this.getClass().getResourceAsStream(fragmentSource);
    final Model model = Rio.parse(inputStream, "", format);

    // path to be set as part of the file reference
    final Path completePath = testDirectory.resolve(TestConstants.TEST_REMOTE_FILE_NAME);
    Files.copy(
            this.getClass().getResourceAsStream(
                    TestConstants.TEST_REMOTE_FILE_PATH + "/" + TestConstants.TEST_REMOTE_FILE_NAME),
            completePath, StandardCopyOption.REPLACE_EXISTING);

    final Resource aliasUri = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).subjects().iterator().next();
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILE_PATH,
            ValueFactoryImpl.getInstance().createLiteral(testDirectory.toAbsolutePath().toString()));
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILENAME,
            ValueFactoryImpl.getInstance().createLiteral(TestConstants.TEST_REMOTE_FILE_NAME));

    // get a String representation of the statements in the Model
    final StringWriter out = new StringWriter();
    Rio.write(model, out, format);

    return out.toString();
}

From source file:org.dbflute.intro.app.logic.engine.EngineInstallLogic.java

private Path doDownloadToZip(String downloadUrl, File engineDir) {
    final Path zipFile = Paths.get(engineDir.getAbsolutePath() + ".zip");
    try (InputStream ins = new URL(downloadUrl).openStream()) {
        Files.copy(ins, zipFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to copy the downloaded data to zip file: " + zipFile, e);
    }/*from ww  w . j  av a  2 s.co  m*/
    return zipFile;
}

From source file:org.nuxeo.ecm.platform.ui.web.util.files.FileUtils.java

/**
 * Creates a Blob from a {@link Part}./*  w  w  w . j  av  a 2  s  . c  o m*/
 * <p>
 * Attempts to capture the underlying temporary file, if one exists. This needs to use reflection to avoid having
 * dependencies on the application server.
 *
 * @param part the servlet part
 * @return the blob
 * @since 7.2
 */
public static Blob createBlob(Part part) throws IOException {
    Blob blob = null;
    try {
        // part : org.apache.catalina.core.ApplicationPart
        // part.fileItem : org.apache.tomcat.util.http.fileupload.disk.DiskFileItem
        // part.fileItem.isInMemory() : false if on disk
        // part.fileItem.getStoreLocation() : java.io.File
        Field fileItemField = part.getClass().getDeclaredField("fileItem");
        fileItemField.setAccessible(true);
        Object fileItem = fileItemField.get(part);
        if (fileItem != null) {
            Method isInMemoryMethod = fileItem.getClass().getDeclaredMethod("isInMemory");
            boolean inMemory = ((Boolean) isInMemoryMethod.invoke(fileItem)).booleanValue();
            if (!inMemory) {
                Method getStoreLocationMethod = fileItem.getClass().getDeclaredMethod("getStoreLocation");
                File file = (File) getStoreLocationMethod.invoke(fileItem);
                if (file != null) {
                    // move the file to a temporary blob we own
                    blob = Blobs.createBlobWithExtension(null);
                    Files.move(file.toPath(), blob.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
    } catch (ReflectiveOperationException | SecurityException | IllegalArgumentException e) {
        // unknown Part implementation
    }
    if (blob == null) {
        // if we couldn't get to the file, use the InputStream
        blob = Blobs.createBlob(part.getInputStream());
    }
    blob.setMimeType(part.getContentType());
    blob.setFilename(retrieveFilename(part));
    return blob;
}

From source file:org.sonar.plugins.csharp.CSharpSensorTest.java

@Before
public void prepare() throws Exception {
    workDir = temp.newFolder().toPath();
    Path srcDir = Paths.get("src/test/resources/CSharpSensorTest");
    Files.walk(srcDir).forEach(path -> {
        if (Files.isDirectory(path)) {
            return;
        }// ww  w.java 2 s.c o  m
        Path relativized = srcDir.relativize(path);
        try {
            Path destFile = workDir.resolve(relativized);
            if (!Files.exists(destFile.getParent())) {
                Files.createDirectories(destFile.getParent());
            }
            Files.copy(path, destFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    });
    File csFile = new File("src/test/resources/Program.cs").getAbsoluteFile();

    EncodingInfo msg = EncodingInfo.newBuilder().setEncoding("UTF-8").setFilePath(csFile.getAbsolutePath())
            .build();
    try (OutputStream output = Files.newOutputStream(workDir.resolve("output-cs\\encoding.pb"))) {
        msg.writeDelimitedTo(output);
    } catch (IOException e) {
        throw new IllegalStateException("could not save message to file", e);
    }

    Path roslynReport = workDir.resolve("roslyn-report.json");
    Files.write(roslynReport,
            StringUtils
                    .replace(new String(Files.readAllBytes(roslynReport), StandardCharsets.UTF_8), "Program.cs",
                            StringEscapeUtils.escapeJavaScript(csFile.getAbsolutePath()))
                    .getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.WRITE);

    tester = SensorContextTester.create(new File("src/test/resources"));
    tester.fileSystem().setWorkDir(workDir.toFile());

    inputFile = new DefaultInputFile(tester.module().key(), "Program.cs").setLanguage(CSharpPlugin.LANGUAGE_KEY)
            .initMetadata(new FileMetadata().readMetadata(new FileReader(csFile)));
    tester.fileSystem().add(inputFile);

    fileLinesContext = mock(FileLinesContext.class);
    fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(inputFile)).thenReturn(fileLinesContext);

    extractor = mock(SonarAnalyzerScannerExtractor.class);
    when(extractor.executableFile(CSharpPlugin.LANGUAGE_KEY))
            .thenReturn(new File(workDir.toFile(), SystemUtils.IS_OS_WINDOWS ? "fake.bat" : "fake.sh"));

    noSonarFilter = mock(NoSonarFilter.class);
    settings = new Settings();

    CSharpConfiguration csConfigConfiguration = new CSharpConfiguration(settings);
    sensor = new CSharpSensor(settings, extractor, fileLinesContextFactory, noSonarFilter,
            csConfigConfiguration,
            new EncodingPerFile(
                    ProjectDefinition.create().setProperty(CoreProperties.ENCODING_PROPERTY, "UTF-8"),
                    new SonarQubeVersion(tester.getSonarQubeVersion())));
}

From source file:de.fabianonline.telegram_backup.mediafilemanager.StickerFileManager.java

public void download() throws RpcErrorException, IOException {
    String old_file = Config.FILE_BASE + File.separatorChar + Config.FILE_STICKER_BASE + File.separatorChar
            + getTargetFilename();//ww w .j  a  v a2 s. c o m

    logger.trace("Old filename exists: {}", new File(old_file).exists());

    if (new File(old_file).exists()) {
        Files.copy(Paths.get(old_file), Paths.get(getTargetPathAndFilename()),
                StandardCopyOption.REPLACE_EXISTING);
        return;
    }
    super.download();
}

From source file:com.google.devtools.build.lib.bazel.repository.CompressedTarFunction.java

@Override
public Path decompress(DecompressorDescriptor descriptor) throws RepositoryFunctionException {
    Optional<String> prefix = descriptor.prefix();
    boolean foundPrefix = false;

    try (InputStream decompressorStream = getDecompressorStream(descriptor)) {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(decompressorStream);
        TarArchiveEntry entry;//from  w  w  w .ja v a  2 s .c o  m
        while ((entry = tarStream.getNextTarEntry()) != null) {
            StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix);
            foundPrefix = foundPrefix || entryPath.foundPrefix();
            if (entryPath.skip()) {
                continue;
            }

            Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment());
            FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory());
            if (entry.isDirectory()) {
                FileSystemUtils.createDirectoryAndParents(filename);
            } else {
                if (entry.isSymbolicLink() || entry.isLink()) {
                    PathFragment linkName = new PathFragment(entry.getLinkName());
                    boolean wasAbsolute = linkName.isAbsolute();
                    // Strip the prefix from the link path if set.
                    linkName = StripPrefixedPath.maybeDeprefix(linkName.getPathString(), prefix)
                            .getPathFragment();
                    if (wasAbsolute) {
                        // Recover the path to an absolute path as maybeDeprefix() relativize the path
                        // even if the prefix is not set
                        linkName = descriptor.repositoryPath().getRelative(linkName).asFragment();
                    }
                    if (entry.isSymbolicLink()) {
                        FileSystemUtils.ensureSymbolicLink(filename, linkName);
                    } else {
                        FileSystemUtils.createHardLink(filename,
                                descriptor.repositoryPath().getRelative(linkName));
                    }
                } else {
                    Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                    filename.chmod(entry.getMode());

                    // This can only be done on real files, not links, or it will skip the reader to
                    // the next "real" file to try to find the mod time info.
                    Date lastModified = entry.getLastModifiedDate();
                    filename.setLastModifiedTime(lastModified.getTime());
                }
            }
        }
    } catch (IOException e) {
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    if (prefix.isPresent() && !foundPrefix) {
        throw new RepositoryFunctionException(
                new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"),
                Transience.PERSISTENT);
    }

    return descriptor.repositoryPath();
}

From source file:de.elomagic.mag.MAG.java

private void run(String[] args) {
    Path configurationFile = Paths.get(System.getProperty("user.dir"), "conf", "configuration.properties");

    DefaultParser parser = new DefaultParser();
    try {/*  w w w .  ja v  a 2 s.  co  m*/
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption(optionHelp.getOpt())) {
            printHelp();
        } else if (commandLine.hasOption(optionEncrypt.getOpt())) {
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);
            }
            encryptConfiguration(configurationFile);
        } else {
            boolean initCreateOfConfig = false;
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);

                LOGGER.info("Using configuration file \"" + file + "\".");
            } else if (Files.notExists(configurationFile)) {
                System.out.println("Creating default configuration file \"" + configurationFile + "\".");
                try (InputStream in = getClass().getResourceAsStream(Configuration.DEFAULT_PROPERTIES_FILE)) {
                    Files.createDirectories(configurationFile.getParent());
                    Files.copy(in, configurationFile, StandardCopyOption.REPLACE_EXISTING);
                }
                System.out
                        .println("Configure file \"" + configurationFile + "\" as your needs and start again.");
                initCreateOfConfig = true;
            }

            if (!initCreateOfConfig) {
                Configuration.loadConfiguration(configurationFile);
                System.out.println("Use ctrl + c to terminate MAG....");
                createCamelMain().run();
                System.out.println("MAG was terminated....");
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (ParseException e) {
        LOGGER.error("Parameter syntax error.", e);
        printHelp();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

}