Example usage for java.nio.file Files deleteIfExists

List of usage examples for java.nio.file Files deleteIfExists

Introduction

In this page you can find the example usage for java.nio.file Files deleteIfExists.

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:test.DatabaseInit.java

/**
 * Removes the old server database, creates a new one and initializes it
 * with test values./*from w ww.  j a  v a2s  . c o  m*/
 * 
 * @param args
 *            the path to the server configuration file.
 */
public static void main(String[] args) {
    if (args.length != 1) {
        throw new IllegalArgumentException("Path to configuration file must be present!");
    }

    try {
        ServerConfiguration serverConfig = ServerConfiguration.parse(Paths.get(args[0]));
        Files.deleteIfExists(Paths.get(serverConfig.getDatabasePath()));
        DatabaseCreation.main(args);
        DatabaseQueries.insertUser("joe1", "joe1-secret");
        DatabaseQueries.insertUser("sharer1", "sharer1-secret");
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:de.qaware.chronix.spark.api.java.ExternalizeTestData.java

/**
 * @param args optional first argument: file to serialize to. A default file name is provided.
 * @throws SolrServerException//from   w  ww . j a  v  a2 s .  co m
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws SolrServerException, IOException {

    ChronixSparkLoader chronixSparkLoader = new ChronixSparkLoader();
    ChronixYAMLConfiguration config = chronixSparkLoader.getConfig();

    String file = (args.length >= 1) ? args[0] : config.getTestdataFile();

    Path filePath = Paths.get(file);
    Files.deleteIfExists(filePath);
    Output output = new Output(new DeflaterOutputStream(new FileOutputStream(filePath.toString())));
    System.out.println("Opening test data file: " + filePath.toString());

    ChronixSparkContext cSparkContext = null;

    //Create target file
    try {
        //Create Chronix Spark context
        cSparkContext = chronixSparkLoader.createChronixSparkContext();

        //Read data into ChronixRDD
        SolrQuery query = new SolrQuery(config.getSolrReferenceQuery());
        ChronixRDD rdd = cSparkContext.queryChronixChunks(query, config.getZookeeperHost(),
                config.getChronixCollection(), config.getStorage());

        System.out.println("Writing " + rdd.count() + " time series into test data file.");

        //Loop through result and serialize it to disk
        Kryo kryo = new Kryo();
        List<MetricTimeSeries> mtsList = IteratorUtils.toList(rdd.iterator());
        System.out.println("Writing objects...");
        kryo.writeObject(output, mtsList);
        output.flush();
        System.out.println("Objects written.");
    } finally {
        output.close();
        if (cSparkContext != null) {
            cSparkContext.getSparkContext().close();
        }
        System.out.println("Test data file written successfully!");
    }
}

From source file:ru.xxlabaza.csv.merger.Main.java

public static void main(String[] args) throws IOException {
    System.out.format("Total memory: %dMb\n", Runtime.getRuntime().maxMemory() / 1024 / 1024);
    System.out.format("Lines per pass: %d\n", LINES_PER_PASS);

    val commandLine = parseArguments(args);

    val temporaryFolder = new File(TEMPORARY_FOLDER_NAME);
    if (!temporaryFolder.exists()) {
        temporaryFolder.mkdirs();/*from   ww w .  j  av  a  2s  . c o  m*/
    }

    val inputFiles = Stream.of(commandLine.getOptionValues("input")).map(Main::resolveFilePath).map(File::new)
            .collect(toList());

    if (!inputFiles.stream().allMatch(File::exists)) {
        throw new IllegalArgumentException("Invalid input file");
    }

    val firstFile = new FilePartContentDescriptor(inputFiles.get(0), LINES_PER_PASS);
    val secondFile = new FilePartContentDescriptor(inputFiles.get(1), LINES_PER_PASS);

    val resultFile = Paths.get(resolveFilePath(commandLine.getOptionValue("output")));
    Files.deleteIfExists(resultFile);
    Files.createFile(resultFile);

    process(firstFile, secondFile, temporaryFolder, resultFile);
}

From source file:org.deeplearning4j.examples.tictactoe.TicTacToeData.java

/**
 * Main function that calls all major functions one-by-one to generate training data to be used in training program.
 *//* w ww .  j a va2s .  c o m*/
public static void main(String[] args) throws Exception {
    long start = System.nanoTime();
    try {
        TicTacToeData data = new TicTacToeData();
        log.info("Data Processing Started");
        final String allMoves = data.generatePossibleGames();
        log.info("All possible game state sequence generated, Finished");

        final Path dataFile = Paths.get(System.getProperty("user.home") + "/AllMoveWithReward.txt");
        Files.deleteIfExists(dataFile);
        final Path dataFilePath = Files.createFile(dataFile);
        try (BufferedWriter writer = Files.newBufferedWriter(dataFilePath)) {
            writer.write(allMoves);
        }
    } catch (Exception e) {
        log.error(e);
    }
    log.info("Total time = " + (System.nanoTime() - start) / 1_000_000);
}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * The main method./*from   w ww  .  j ava  2 s.  c  om*/
 * 
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    // simple parse command line
    if (args != null && args.length > 0) {
        LOGGER.debug("TMM started with: " + Arrays.toString(args));
        TinyMediaManagerCMD.parseParams(args);
        System.setProperty("java.awt.headless", "true");
    } else {
        // no cmd params found, but if we are headless - display syntax
        String head = System.getProperty("java.awt.headless");
        if (head != null && head.equals("true")) {
            LOGGER.info("TMM started 'headless', and without params -> displaying syntax ");
            TinyMediaManagerCMD.printSyntax();
            System.exit(0);
        }
    }

    // check if we have write permissions to this folder
    try {
        RandomAccessFile f = new RandomAccessFile("access.test", "rw");
        f.close();
        Files.deleteIfExists(Paths.get("access.test"));
    } catch (Exception e2) {
        String msg = "Cannot write to TMM directory, have no rights - exiting.";
        if (!GraphicsEnvironment.isHeadless()) {
            JOptionPane.showMessageDialog(null, msg);
        } else {
            System.out.println(msg);
        }
        System.exit(1);
    }

    // HACK for Java 7 and JavaFX not being in boot classpath
    // In Java 8 and on, this is installed inside jre/lib/ext
    // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references
    // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o)
    String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper
    File jfx = new File(dir, "lib/ext/jfxrt.jar");
    if (!jfx.exists()) {
        // java 7
        jfx = new File(dir, "lib/jfxrt.jar");
        if (jfx.exists()) {
            try {
                TmmOsUtils.addPath(jfx.getAbsolutePath());
            } catch (Exception e) {
                LOGGER.debug("failed to load JavaFX - using old styles...");
            }
        }
    }

    if (Globals.isDebug()) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        LOGGER.info("=== DEBUG CLASS LOADING =============================");
        for (URL url : urls) {
            LOGGER.info(url.getFile());
        }
    }

    LOGGER.info("=====================================================");
    LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ===");
    LOGGER.info("=====================================================");
    LOGGER.info("tmm.version      : " + ReleaseInfo.getRealVersion());

    if (Globals.isDonator()) {
        LOGGER.info("tmm.supporter    : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)");
    }

    LOGGER.info("os.name          : " + System.getProperty("os.name"));
    LOGGER.info("os.version       : " + System.getProperty("os.version"));
    LOGGER.info("os.arch          : " + System.getProperty("os.arch"));
    LOGGER.trace("network.id       : " + License.getMac());
    LOGGER.info("java.version     : " + System.getProperty("java.version"));

    if (Globals.isRunningJavaWebStart()) {
        LOGGER.info("java.webstart    : true");
    }
    if (Globals.isRunningWebSwing()) {
        LOGGER.info("java.webswing    : true");
    }

    // START character encoding debug
    debugCharacterEncoding("default encoding : ");
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
    Field charset;
    try {
        // we cannot (re)set the properties while running inside JVM
        // so we trick it to reread it by setting them to null ;)
        charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null, null);
    } catch (Exception e) {
        LOGGER.warn("Error resetting to UTF-8", e);
    }
    debugCharacterEncoding("set encoding to  : ");
    // END character encoding debug

    // set GUI default language
    Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage()));
    LOGGER.info("System language  : " + System.getProperty("user.language") + "_"
            + System.getProperty("user.country"));
    LOGGER.info(
            "GUI language     : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry());
    LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage());
    LOGGER.info("TV Scraper lang  : " + TvShowModuleManager.SETTINGS.getScraperLanguage());

    // start EDT
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades
            try {
                Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop());
                if (!GraphicsEnvironment.isHeadless()) {
                    Thread.currentThread().setName("main");
                } else {
                    Thread.currentThread().setName("headless");
                    LOGGER.debug("starting without GUI...");
                }
                Toolkit tk = Toolkit.getDefaultToolkit();
                tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);
                if (!GraphicsEnvironment.isHeadless()) {
                    setLookAndFeel();
                }
                doStartupTasks();

                // suppress logging messages from betterbeansbinding
                org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName())
                        .setLevel(Level.SEVERE);

                // init ui logger
                TmmUILogCollector.init();

                LOGGER.info("=====================================================");
                // init splash
                SplashScreen splash = null;
                if (!GraphicsEnvironment.isHeadless()) {
                    splash = SplashScreen.getSplashScreen();
                }
                Graphics2D g2 = null;
                if (splash != null) {
                    g2 = splash.createGraphics();
                    if (g2 != null) {
                        Font font = new Font("Dialog", Font.PLAIN, 14);
                        g2.setFont(font);
                    } else {
                        LOGGER.debug("got no graphics from splash");
                    }
                } else {
                    LOGGER.debug("no splash found");
                }

                if (g2 != null) {
                    updateProgress(g2, "starting tinyMediaManager", 0);
                    splash.update();
                }
                LOGGER.info("starting tinyMediaManager");

                // upgrade check
                String oldVersion = Globals.settings.getVersion();
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading to new version", 10);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version
                    Globals.settings.setCurrentVersion();
                    Globals.settings.saveSettings();
                }

                // proxy settings
                if (Globals.settings.useProxy()) {
                    LOGGER.info("setting proxy");
                    Globals.settings.setProxy();
                }

                // MediaInfo /////////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading MediaInfo libs", 20);
                    splash.update();
                }
                MediaInfoUtils.loadMediaInfo();

                // load modules //////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading movie module", 30);
                    splash.update();
                }
                TmmModuleManager.getInstance().startUp();
                TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading TV show module", 40);
                    splash.update();
                }

                TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading plugins", 50);
                    splash.update();
                }

                // just instantiate static - will block (takes a few secs)
                PluginManager.getInstance();
                if (ReleaseInfo.isSvnBuild()) {
                    PluginManager.loadClasspathPlugins();
                }

                // do upgrade tasks after database loading
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading database to new version", 70);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion);
                }

                // launch application ////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading ui", 80);
                    splash.update();
                }
                if (!GraphicsEnvironment.isHeadless()) {
                    MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion());

                    // finished ////////////////////////////////////////////////////
                    if (g2 != null) {
                        updateProgress(g2, "finished starting :)", 100);
                        splash.update();
                    }

                    // write a random number to file, to identify this instance (for
                    // updater, tracking, whatsoever)
                    Utils.trackEvent("startup");

                    TmmWindowSaver.getInstance().loadSettings(window);
                    window.setVisible(true);

                    // wizard for new user
                    if (Globals.settings.newConfig) {
                        Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults!
                        TinyMediaManagerWizard wizard = new TinyMediaManagerWizard();
                        wizard.setVisible(true);
                    }

                    // show changelog
                    if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) {
                        // special case nightly/svn: if same snapshot version, do not display changelog
                        Utils.trackEvent("updated");
                        showChangelog();
                    }
                } else {
                    TinyMediaManagerCMD.startCommandLineTasks();
                    // wait for other tmm threads (artwork download et all)
                    while (TmmTaskManager.getInstance().poolRunning()) {
                        Thread.sleep(2000);
                    }

                    LOGGER.info("bye bye");
                    // MainWindows.shutdown()
                    try {
                        // send shutdown signal
                        TmmTaskManager.getInstance().shutdown();
                        // save unsaved settings
                        Globals.settings.saveSettings();
                        // hard kill
                        TmmTaskManager.getInstance().shutdownNow();
                        // close database connection
                        TmmModuleManager.getInstance().shutDown();
                    } catch (Exception ex) {
                        LOGGER.warn(ex.getMessage());
                    }
                    System.exit(0);
                }
            } catch (IllegalStateException e) {
                LOGGER.error("IllegalStateException", e);
                if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) {
                    // MessageDialog.showExceptionWindow(e);
                    ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$
                    MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(),
                            bundle.getString("tmm.problemdetected")); //$NON-NLS-1$
                    dialog.setImage(IconManager.ERROR);
                    dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$
                    dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$
                    dialog.setResizable(true);
                    dialog.pack();
                    dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                    dialog.setVisible(true);
                }
                System.exit(1);
            } catch (Exception e) {
                LOGGER.error("Exception while start of tmm", e);
                if (!GraphicsEnvironment.isHeadless()) {
                    MessageDialog.showExceptionWindow(e);
                }
                System.exit(1);
            }
        }

        /**
         * Update progress on splash screen.
         * 
         * @param text
         *          the text
         */
        private void updateProgress(Graphics2D g2, String text, int progress) {
            Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(20, 200, 480, 305);
            g2.setPaintMode();

            g2.setColor(new Color(51, 153, 255));
            g2.fillRect(22, 272, 452 * progress / 100, 21);

            g2.setColor(Color.black);
            g2.drawString(text + "...", 23, 310);
            int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right
            g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
            LOGGER.debug("Startup (" + progress + "%) " + text);
        }

        /**
         * Sets the look and feel.
         * 
         * @throws Exception
         *           the exception
         */
        private void setLookAndFeel() throws Exception {
            // get font settings
            String fontFamily = Globals.settings.getFontFamily();
            try {
                // sanity check
                fontFamily = Font.decode(fontFamily).getFamily();
            } catch (Exception e) {
                fontFamily = "Dialog";
            }

            int fontSize = Globals.settings.getFontSize();
            if (fontSize < 12) {
                fontSize = 12;
            }

            String fontString = fontFamily + " " + fontSize;

            // Get the native look and feel class name
            // String laf = UIManager.getSystemLookAndFeelClassName();
            Properties props = new Properties();
            props.setProperty("controlTextFont", fontString);
            props.setProperty("systemTextFont", fontString);
            props.setProperty("userTextFont", fontString);
            props.setProperty("menuTextFont", fontString);
            // props.setProperty("windowTitleFont", "Dialog bold 20");

            fontSize = Math.round((float) (fontSize * 0.833));
            fontString = fontFamily + " " + fontSize;

            props.setProperty("subTextFont", fontString);
            props.setProperty("backgroundColor", "237 237 237");
            props.setProperty("menuBackgroundColor", "237 237 237");
            props.setProperty("controlBackgroundColor", "237 237 237");
            props.setProperty("menuColorLight", "237 237 237");
            props.setProperty("menuColorDark", "237 237 237");
            props.setProperty("toolbarColorLight", "237 237 237");
            props.setProperty("toolbarColorDark", "237 237 237");
            props.setProperty("tooltipBackgroundColor", "255 255 255");
            props.put("windowDecoration", "system");
            props.put("logoString", "");

            // Get the look and feel class name
            com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props);
            String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";

            // Install the look and feel
            UIManager.setLookAndFeel(laf);
        }

        /**
         * Does some tasks at startup
         */
        private void doStartupTasks() {
            // rename downloaded files
            UpgradeTasks.renameDownloadedFiles();

            // extract templates, if GD has not already done
            Utils.extractTemplates();

            // check if a .desktop file exists
            if (Platform.isLinux()) {
                File desktop = new File(TmmOsUtils.DESKTOP_FILE);
                if (!desktop.exists()) {
                    TmmOsUtils.createDesktopFileForLinux(desktop);
                }
            }
        }

        private void showChangelog() {
            // read the changelog
            try {
                final String changelog = Utils.readFileToString(Paths.get("changelog.txt"));
                if (StringUtils.isNotBlank(changelog)) {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            WhatsNewDialog dialog = new WhatsNewDialog(changelog);
                            dialog.pack();
                            dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                            dialog.setVisible(true);
                        }
                    });
                }
            } catch (IOException e) {
                // no file found
                LOGGER.warn(e.getMessage());
            }
        }
    });
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args//from www  . j av a 2 s  . c o m
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.languagetool.dev.wordsimilarity.SimilarWordFinder.java

public static void main(String[] args) throws IOException {
    SimilarWordFinder simWordFinder = new SimilarWordFinder();
    System.out.println("Using key distance: " + keyDistance.getClass());
    if (args.length == 1) {
        File indexDir = new File(args[0]);
        simWordFinder.findSimilarWords(indexDir);
    } else if (args.length == 2) {
        File indexDir = new File(args[1]);
        String[] words = args[0].split(",");
        simWordFinder.findSimilarWords(indexDir, Arrays.asList(words));
    } else if (args.length == 3) {
        List<String> words = FileUtils.readLines(new File(args[1]), "utf-8");
        File indexDir = new File(args[2]);
        Files.deleteIfExists(indexDir.toPath());
        simWordFinder.createIndex(words, indexDir);
    } else {/*ww  w  . j  a  v  a 2 s.c o m*/
        System.out.println(
                "Usage 1: " + SimilarWordFinder.class.getSimpleName() + " --index <wordFile> <indexFile>");
        System.out.println("Usage 2: " + SimilarWordFinder.class.getSimpleName()
                + " <words> <indexDir> (as created with usage 1)");
        System.out.println("             <indexDir> as created with usage 1");
        System.out.println(
                "             <words> a comma-separated list of words to search similar words for (no spaces)");
        System.out.println("Usage 3: " + SimilarWordFinder.class.getSimpleName() + " <indexDir>");
        System.exit(1);
    }
}

From source file:dev.meng.wikipedia.profiler.Cleaner.java

public static void cleanDB(List<String> values) {
    for (String value : values) {
        try {/* www  .java  2s . c o m*/
            String[] splits = value.split(":");
            Path filepath = Paths.get(splits[splits.length - 1]);
            Files.deleteIfExists(filepath);
        } catch (IOException ex) {
            LogHandler.console(Cleaner.class, ex);
        }
    }
}

From source file:org.kitodo.editor.XMLEditorTest.java

@AfterClass
public static void tearDown() throws IOException {
    Files.deleteIfExists(Paths.get(absolutePath));
}

From source file:dev.meng.wikipedia.profiler.Cleaner.java

public static void cleanLog(List<String> values) {
    for (String value : values) {
        for (LogLevel level : LogLevel.values()) {
            try {
                Path filepath = Paths.get(value + "-" + level.name().toLowerCase() + ".log");
                Files.deleteIfExists(filepath);
            } catch (IOException ex) {
                LogHandler.console(Cleaner.class, ex);
            }// w  ww  .  j av a2s .  c  o m
        }
    }
}