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:Main.java

public static void main(String[] args) throws Exception {
    Path newFile = FileSystems.getDefault().getPath("C:/home/docs/newFile.txt");
    Path copiedFile = FileSystems.getDefault().getPath("C:/home/docs/copiedFile.txt");

    Files.createFile(newFile);// ww w  .ja  v a  2 s. c o  m
    System.out.println("File created successfully!");
    Files.copy(newFile, copiedFile);
    System.out.println("File copied successfully!");
    Files.copy(newFile, copiedFile, StandardCopyOption.REPLACE_EXISTING);

}

From source file:de.jackwhite20.japs.server.Main.java

public static void main(String[] args) throws Exception {

    Config config = null;/*from  w w w  . j a  v  a  2  s.  com*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//w  w  w .ja v  a 2  s  .c  o m
 * @throws org.antlr.runtime.RecognitionException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, RecognitionException, ParseException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        System.out.println();
        printHelp(options);
        System.exit(0);
        return;
    }
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    final PathResolver pathResolver = new PathResolver();

    Configuration configuration;
    Path configurationFile = pathResolver.findConfiguration();
    if (Files.isRegularFile(configurationFile)) {
        configuration = Configuration.fromPropertiesFile(configurationFile);
    } else {
        configuration = new Configuration();
    }
    configuration = toConfiguration(configuration, commandLine);
    //configuration.toProperties().store(System.err, null);

    if (!Files.isRegularFile(configurationFile)) {
        configuration.writeProperties(configurationFile);
        System.err.println(
                "no configuration file present, write based on CLI options: " + configurationFile.toString());
        configuration.toProperties().store(System.err, null);
    }

    Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths();
    if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) {
        System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths)
                + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf");
        System.exit(1);
    }

    Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration);

    final String[] removeTagsValues = commandLine.getOptionValues("remove");
    if (null != removeTagsValues) {
        taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues));
    }

    Set<TagType> tagTypes = configuration.getTagTypes();
    if (null == tagTypes) {
        System.err.println("no tag types!");
        System.exit(1);
    }

    final boolean printTags = commandLine.hasOption("p");

    final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"),
            null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays());
    final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads());
    if (true || commandLine.hasOption("v")) {
        tagLoader.registerEventListener(new CliEventLoggerLoaded());
    }
    Tagger tagger = new Tagger(tagLoader);

    if (printTags) {
        Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions);
        Joiner.on("\n").appendTo(System.out, availableTags);
    } else {
        for (Path path : sharedConfigPaths) {
            VdfNode tagged = tagger.tag(path, taggerOptions);
            if (commandLine.hasOption("w")) {
                Path backup = path.getParent()
                        .resolve(path.getFileName().toString() + ".bak" + new Date().getTime());
                Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
                System.err.println("backup up " + path + " to " + backup);
                Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)),
                        path, StandardCopyOption.REPLACE_EXISTING);
                try {
                    Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS);
                } catch (Exception e) {
                    System.err.println(e);
                }
                System.err.println("wrote " + path);
            } else {
                System.out.println(tagged.toPrettyString());
                System.err.println("pipe to file and copy to: " + path.toString());
            }
        }
    }
}

From source file:org.owasp.benchmark.score.BenchmarkScore.java

public static void main(String[] args) {
    if (args == null || args.length < 2) {
        System.out.println(usageNotice);
        System.exit(-1);//from   w  w w  .  j a v  a  2s .c  o m
    }

    if (args.length > 2) {
        focus = args[2].replace(' ', '_');
    }

    if (args.length > 3) {
        if ("anonymous".equalsIgnoreCase(args[3])) {
            anonymousMode = true;
        } else if ("show_ave_only".equalsIgnoreCase(args[3])) {
            showAveOnlyMode = true;
        } else {
            System.out.println(usageNotice);
            System.exit(-1);
        }
    }

    // Prepare the scorecard results directory for the newly generated scorecards
    // Step 1: Create the dir if it doesn't exist, or delete everything in it if it does
    File scoreCardDir = new File(scoreCardDirName);
    try {
        if (!scoreCardDir.exists()) {
            Files.createDirectories(Paths.get(scoreCardDirName));
        } else {
            System.out.println(
                    "Deleting previously generated scorecard files in: " + scoreCardDir.getAbsolutePath());
            FileUtils.cleanDirectory(scoreCardDir);
        }

        // Step 2: Now copy the entire /content directory, that either didn't exist, or was just deleted with everything else
        File dest1 = new File(scoreCardDirName + File.separator + "content");
        FileUtils.copyDirectory(new File(pathToScorecardResources + "content"), dest1);

    } catch (IOException e) {
        System.out.println("Error dealing with scorecard directory: '" + scoreCardDir.getAbsolutePath()
                + "' for some reason!");
        e.printStackTrace();
    }

    // Step 3: Copy over the Homepage and Guide templates
    try {
        Files.copy(Paths.get(pathToScorecardResources + HOMEFILENAME),
                Paths.get(scoreCardDirName + "/" + HOMEFILENAME), StandardCopyOption.REPLACE_EXISTING);

        Files.copy(Paths.get(pathToScorecardResources + GUIDEFILENAME),
                Paths.get(scoreCardDirName + "/" + GUIDEFILENAME), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        System.out.println("Problem copying home and guide files");
        e.printStackTrace();
    }

    // Step 4: Read the expected results so we know what each tool 'should do'
    try {

        if ("mixed".equalsIgnoreCase(args[0])) {

            mixedMode = true; // Tells anyone that cares that we aren't processing a single version of Benchmark results

            File f = new File(args[1]);
            if (!f.exists()) {
                System.out.println("Error! - results directory: '" + f.getAbsolutePath() + "' doesn't exist.");
                System.exit(-1);
            }
            if (!f.isDirectory()) {
                System.out.println("Error! - results parameter is a file: '" + f.getAbsolutePath()
                        + "' but must be a directory when processing results in 'mixed' mode.");
                System.exit(-1);
            }

            // Go through each file in the root directory.
            // -- 1st find each directory. And then within each of those directories:
            //    -- 1st find the expected results file in that directory
            //    -- and then each of the actual results files in that directory
            for (File rootDirFile : f.listFiles()) {

                if (rootDirFile.isDirectory()) {

                    // Process this directory
                    TestResults expectedResults = null;
                    String expectedResultsFilename = null;
                    // Step 4a: Find and process the expected results file so we know what each tool in this directory 'should do'
                    for (File resultsDirFile : rootDirFile.listFiles()) {

                        if (resultsDirFile.getName().startsWith("expectedresults-")) {
                            if (expectedResults != null) {
                                System.out.println("Found 2nd expected results file "
                                        + resultsDirFile.getAbsolutePath()
                                        + " in same directory. Can only have 1 in each results directory");
                                System.exit(-1);
                            }

                            // read in the expected results for this directory of results
                            expectedResults = readExpectedResults(resultsDirFile);
                            if (expectedResults == null) {
                                System.out.println("Couldn't read expected results file: "
                                        + resultsDirFile.getAbsolutePath());
                                System.exit(-1);
                            } // end if

                            expectedResultsFilename = resultsDirFile.getName();
                            if (benchmarkVersion == null) {
                                benchmarkVersion = expectedResults.getBenchmarkVersion();
                            } else
                                benchmarkVersion += "," + expectedResults.getBenchmarkVersion();
                            System.out.println(
                                    "\nFound expected results file: " + resultsDirFile.getAbsolutePath());
                        } // end if
                    } // end for loop going through each file looking for expected results file

                    // Make sure we found an expected results file, before processing the results
                    if (expectedResults == null) {
                        System.out.println("Couldn't find expected results file in results directory: "
                                + rootDirFile.getAbsolutePath());
                        System.out.println(
                                "Expected results file has to be a .csv file that starts with: 'expectedresults-'");
                        System.exit(-1);
                    }

                    // Step 5a: Go through each result file and generate a scorecard for that tool.
                    if (!anonymousMode) {
                        for (File actual : rootDirFile.listFiles()) {
                            // Don't confuse the expected results file as an actual results file if its in the same directory
                            if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName()))
                                process(actual, expectedResults, toolResults);
                        }
                    } else {
                        // To handle anonymous mode, we are going to randomly grab files out of this directory
                        // and process them. By doing it this way, multiple runs should randomly order the commercial
                        // tools each time.
                        List<File> files = new ArrayList();
                        for (File file : rootDirFile.listFiles()) {
                            files.add(file);
                        }

                        SecureRandom generator = SecureRandom.getInstance("SHA1PRNG");
                        while (files.size() > 0) {
                            // Get a random, positive integer
                            int fileToGet = Math.abs(generator.nextInt(files.size()));
                            File actual = files.remove(fileToGet);
                            // Don't confuse the expected results file as an actual results file if its in the same directory
                            if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName()))
                                process(actual, expectedResults, toolResults);
                        }
                    }
                } // end if a directory
            } // end for loop through all files in the directory

            // process the results the normal way with a single results directory
        } else {

            // Step 4b: Read the expected results so we know what each tool 'should do'
            File expected = new File(args[0]);
            TestResults expectedResults = readExpectedResults(expected);
            if (expectedResults == null) {
                System.out.println("Couldn't read expected results file: " + expected);
                System.exit(-1);
            } else {
                System.out.println("Read expected results from file: " + expected.getAbsolutePath());
                int totalResults = expectedResults.totalResults();
                if (totalResults != 0) {
                    System.out.println(totalResults + " results found.");
                    benchmarkVersion = expectedResults.getBenchmarkVersion();
                } else {
                    System.out.println("Error! - zero expected results found in results file.");
                    System.exit(-1);
                }
            }

            // Step 5b: Go through each result file and generate a scorecard for that tool.
            File f = new File(args[1]);
            if (!f.exists()) {
                System.out.println("Error! - results file: '" + f.getAbsolutePath() + "' doesn't exist.");
                System.exit(-1);
            }
            if (f.isDirectory()) {
                if (!anonymousMode) {
                    for (File actual : f.listFiles()) {
                        // Don't confuse the expected results file as an actual results file if its in the same directory
                        if (!actual.isDirectory() && !expected.getName().equals(actual.getName()))
                            process(actual, expectedResults, toolResults);
                    }
                } else {
                    // To handle anonymous mode, we are going to randomly grab files out of this directory
                    // and process them. By doing it this way, multiple runs should randomly order the commercial
                    // tools each time.
                    List<File> files = new ArrayList();
                    for (File file : f.listFiles()) {
                        files.add(file);
                    }

                    SecureRandom generator = SecureRandom.getInstance("SHA1PRNG");
                    while (files.size() > 0) {
                        int randomNum = generator.nextInt();
                        // FIXME: Get Absolute Value better
                        if (randomNum < 0)
                            randomNum *= -1;
                        int fileToGet = randomNum % files.size();
                        File actual = files.remove(fileToGet);
                        // Don't confuse the expected results file as an actual results file if its in the same directory
                        if (!actual.isDirectory() && !expected.getName().equals(actual.getName()))
                            process(actual, expectedResults, toolResults);
                    }
                }

            } else {
                // This will process a single results file, if that is what the 2nd parameter points to.
                // This has never been used.
                process(f, expectedResults, toolResults);
            }
        } // end else

        System.out.println("Tool scorecards computed.");
    } catch (Exception e) {
        System.out.println("Error during processing: " + e.getMessage());
        e.printStackTrace();
    }

    // Step 6: Now generate scorecards for each type of vulnerability across all the tools

    // First, we have to figure out the list of vulnerabilities
    // A set is used here to eliminate duplicate categories across all the results
    Set<String> catSet = new TreeSet<String>();
    for (Report toolReport : toolResults) {
        catSet.addAll(toolReport.getOverallResults().getCategories());
    }

    // Then we generate each vulnerability scorecard
    BenchmarkScore.generateVulnerabilityScorecards(toolResults, catSet);
    System.out.println("Vulnerability scorecards computed.");

    // Step 7: Update all the menus for all the generated pages to reflect the tools and vulnerability categories
    updateMenus(toolResults, catSet);

    // Step 8: Generate the overall comparison chart for all the tools in this test
    ScatterHome.generateComparisonChart(toolResults, focus);

    // Step 9: Generate the results table across all the tools in this test
    String table = generateOverallStatsTable(toolResults);

    File f = Paths.get(scoreCardDirName + "/" + HOMEFILENAME).toFile();
    try {
        String html = new String(Files.readAllBytes(f.toPath()));
        html = html.replace("${table}", table);
        Files.write(f.toPath(), html.getBytes());
    } catch (IOException e) {
        System.out.println("Error updating results table in: " + f.getName());
        e.printStackTrace();
    }

    System.out.println("Benchmark scorecards complete.");

    System.exit(0);
}

From source file:Main.java

private static Path unzip(Path tmpDir, Path zipPath, String name) throws IOException {
    Path outPath = tmpDir.resolve(zipPath.getFileName());
    try (ZipFile zipFile = new ZipFile(zipPath.toFile())) {
        Files.copy(zipFile.getInputStream(zipFile.getEntry(name)), outPath,
                StandardCopyOption.REPLACE_EXISTING);
        return outPath;
    }/*w  w w .ja  v a  2s. co m*/
}

From source file:com.twitter.heron.apiserver.utils.FileHelper.java

public static boolean copy(InputStream in, Path to) {
    try {/*from  ww w.ja va2  s.c  om*/
        Files.copy(in, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        LOG.error("Failed to copy file to {}", to, ioe);
        return false;
    }
    return true;
}

From source file:gov.nist.appvet.shared.FileUtil.java

public static synchronized boolean copyFile(File sourceFile, File destFile) {
    if (sourceFile == null || !sourceFile.exists() || destFile == null) {
        return false;
    }/*ww w  . j av  a2s.c  o  m*/
    try {
        Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:gov.nist.appvet.tool.sigverifier.util.FileUtil.java

public static boolean copyFile(File sourceFile, File destFile) {
    if (sourceFile == null || !sourceFile.exists() || destFile == null) {
        return false;
    }//from w w w .j  a  v a  2s.  c o  m
    try {
        Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e) {
        log.error(e.toString());
        return false;
    }
    return true;
}

From source file:com.stratio.mojo.scala.crossbuild.FileRewriter.java

private static void backupFile(final File origFile) throws IOException {
    final File bkpFile = getBackupFileName(origFile);
    Files.copy(origFile.toPath(), bkpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.thesmartguild.firmloader.lib.tftp.TFTPServerFactory.java

public static TFTPServer instantiate(File file) {
    try {//from w ww  .j  av a 2s  .c  o  m
        TFTPServer TFTPServer_;
        Path tmpFilePath = TFTPServerFactory.createTempDirectory();
        Path filePath = Files.copy(file.toPath(), Paths.get(tmpFilePath.toString(), file.getName()),
                StandardCopyOption.REPLACE_EXISTING);
        filePath.toFile().deleteOnExit();
        TFTPServer_ = new TFTPServer(tmpFilePath.toFile(), tmpFilePath.toFile(), ServerMode.GET_ONLY);
        TFTPServer_.setLog(System.out);
        TFTPServer_.setLogError(System.out);
        return TFTPServer_;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}