Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

In this page you can find the example usage for java.io File exists.

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:act.installer.pubchem.PubchemTTLMerger.java

public static void main(String[] args) throws Exception {
    org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/* w  ww.j a v a 2 s .  co  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    PubchemTTLMerger merger = new PubchemTTLMerger();

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));

    if (cl.hasOption(OPTION_ONLY_MERGE)) {
        if (!(rocksDBFile.exists() && rocksDBFile.isDirectory())) {
            System.err.format("Must specify an existing RocksDB index when using '%s'.\n", OPTION_ONLY_MERGE);
            HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
            System.exit(1);
        }
        merger.finish(merger.merge(rocksDBFile));
        return;
    }

    File rdfDir = new File(cl.getOptionValue(OPTION_RDF_DIRECTORY));
    if (!rdfDir.isDirectory()) {
        System.err.format("Must specify a directory of RDF files to be parsed.\n");
        HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File[] filesInDirectoryArray = rdfDir.listFiles(new FilenameFilter() {
        private static final String TTL_GZ_SUFFIX = ".ttl.gz";

        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(TTL_GZ_SUFFIX);
        }
    });

    if (filesInDirectoryArray == null || filesInDirectoryArray.length == 0) {
        System.err.format("Found zero compressed TTL files in directory at '%s'.\n", rdfDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    // Sort files for stability/sanity.
    List<File> filesInDirectory = Arrays.asList(filesInDirectoryArray);
    Collections.sort(filesInDirectory);

    if (cl.hasOption(OPTION_ONLY_SYNONYMS)) {
        filesInDirectory = filterByFileContents(filesInDirectory, PC_RDF_DATA_FILE_CONFIG.HASH_TO_SYNONYM);
    }

    if (cl.hasOption(OPTION_ONLY_MESH)) {
        filesInDirectory = filterByFileContents(filesInDirectory, PC_RDF_DATA_FILE_CONFIG.HASH_TO_MESH);
    }

    if (cl.hasOption(OPTION_ONLY_PUBCHEM_IDS)) {
        filesInDirectory = filterByFileContents(filesInDirectory, PC_RDF_DATA_FILE_CONFIG.HASH_TO_CID);
    }

    if (filesInDirectory.size() == 0) {
        System.err.format(
                "Arrived at index initialization with no files to process.  "
                        + "Maybe too many filters were specified?  synonyms: %s, MeSH: %s, Pubchem ids: %s\n",
                cl.hasOption(OPTION_ONLY_SYNONYMS), cl.hasOption(OPTION_ONLY_MESH),
                cl.hasOption(OPTION_ONLY_PUBCHEM_IDS));
        HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    RocksDB.loadLibrary();
    Pair<RocksDB, Map<COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null;
    try {
        if (rocksDBFile.exists()) {
            if (!cl.hasOption(OPTION_OPEN_EXISTING_OKAY)) {
                System.err.format(
                        "Index directory at '%s' already exists, delete before retrying or add '%s' option to reuse.\n",
                        rocksDBFile.getAbsolutePath(), OPTION_OPEN_EXISTING_OKAY);
                HELP_FORMATTER.printHelp(PubchemTTLMerger.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                        true);
                System.exit(1);
            } else {
                LOGGER.info("Reusing existing index at %s", rocksDBFile.getAbsolutePath());
                dbAndHandles = openExistingRocksDB(rocksDBFile);
            }
        } else {
            LOGGER.info("Creating new index at %s", rocksDBFile.getAbsolutePath());
            dbAndHandles = createNewRocksDB(rocksDBFile);
        }
        merger.buildIndex(dbAndHandles, filesInDirectory);

        merger.merge(dbAndHandles);
    } finally {
        if (dbAndHandles != null) {
            merger.finish(dbAndHandles);
        }
    }
}

From source file:malware_classification.Malware_Classification.java

/**
 * @param args the command line arguments. Order is malicious_filename,
 * benign filename, (optional) bin_size//www  .  j  av  a  2 s  . c  o  m
 */
public static void main(String[] args) {
    String malicious_file_path = args[0];
    String benign_file_path = args[1];
    int curr_bin_size;
    if (args.length > 2) {
        curr_bin_size = Integer.parseInt(args[2]);
    } else {
        curr_bin_size = -1;
    }
    String pid_str = ManagementFactory.getRuntimeMXBean().getName();
    logger.setLevel(Level.CONFIG);
    logger.log(Level.INFO, pid_str);
    boolean found_file = false;
    String output_base = "std_output";
    File output_file = null;
    for (int i = 0; !found_file; i++) {
        output_file = new File(output_base + i + ".txt");
        found_file = !output_file.exists();
    }

    FileHandler fh = null;
    try {
        fh = new FileHandler(output_file.getAbsolutePath());
    } catch (IOException ex) {
        Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex);
    }
    logger.addHandler(fh);
    logger.info("Writing output in " + output_file.getAbsolutePath());

    Malware_Classification classifier = new Malware_Classification(malicious_file_path, benign_file_path,
            curr_bin_size);
    //        classifier.run_tests();
}

From source file:edu.stanford.muse.launcher.Splash.java

public static void main(String args[]) throws Exception {
    Splash splash = null;/*from   www .j  ava 2 s . c o m*/
    splash = new Splash();

    tellUser(splash, "Setting up logging...");
    setupLogging();
    tellUser(splash, "Setting up shutdown port...");
    basicSetup(args);
    BASE_URL = "http://localhost:" + PORT + "/" + WEBAPP_NAME;
    MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.

    tellUser(splash, "Log file: " + debugFile + "***\n");

    out.println("Starting up ePADD on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    tellUser(splash, "Memory: " + getMemoryStats());

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! ePADD already running at: " + BASE_URL + ", will shut it down!");
        tellUser(splash, "ePADD already running at: " + BASE_URL + ", will shut it down!");
        killRunningServer(BASE_URL);

        boolean killed = false;
        int N_KILL_TRIES = 20, N_KILL_PERIOD_MILLIS = 3000;
        // check every 3 secs 20 times (total 1 minute) for the previous muse to die
        // if it doesn't die after a minute, fail
        for (int i = 0; i < N_KILL_TRIES; i++) {
            try {
                Thread.sleep(N_KILL_PERIOD_MILLIS);
            } catch (InterruptedException ie) {
            }
            out.println("Checking " + MUSE_CHECK_URL);
            tellUser(splash, "Checking " + MUSE_CHECK_URL);
            try {
                urlAlive = isURLAlive(MUSE_CHECK_URL);
            } catch (Exception e) {
                out.println("Exception: " + e);
                e.printStackTrace(out);
            }
            if (!urlAlive)
                break;
        }

        if (!urlAlive) {
            out.println("Good. Shutdown succeeded, will restart");
            tellUser(splash, "Good. Shutdown succeeded, we'll restart ePADD.");
        } else {
            String message = "Previously running ePADD still alive despite attempt to shut it down, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL;
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n";
            aggressiveWarn(message, 2000);
            tellUser(splash, "Sorry, unable to kill previous ePADD. Quitting!");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ie) {
            }
            if (splash != null)
                splash.close();
            return;
        }
    }

    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        setupResources();
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        tellUser(splash, "Starting ePADD at " + BASE_URL);

        server.start();

        PrintStream debugOut1 = err;
        try {
            File f = new File(debugFile);
            if (f.exists())
                f.delete(); // particular problem on windows :-(
            debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
        } catch (IOException ioe) {
            err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
        }

        final PrintStream debugOut = debugOut1;

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    shutdownSessions();
                    server.stop();
                    server.destroy();
                    debugOut.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }));
        //        InfoFrame frame = new InfoFrame();
        //        frame.doShow();

        boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
        //        frame.updateText ("Opening a browser window");

        if (success) {
            try {
                int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

                new ShutdownThread(server, shutdownPort).start();
                out.println("Listening for ePADD shutdown message on port " + shutdownPort);
                tellUser(splash, "Listening for ePADD shutdown message on port " + shutdownPort);

            } catch (Exception e) {
                out.println(
                        "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
            }

            try {
                setupSystemTrayIcon();
            } catch (Exception e) {
                err.println("Unable to setup system tray icon: " + e);
                e.printStackTrace(err);
            }

            // open browser window
            if (browserOpen) {
                preferredBrowser = null;
                // launch a browser here
                try {

                    String link;
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                    if (startPage != null) {
                        // startPage has to be absolute
                        link = "http://localhost:" + PORT + "/muse/" + startPage;
                    }

                    if (baseDir != null)
                        link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                    launchBrowser(link, splash);

                } catch (Exception e) {
                    out.println(
                            "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):");
                    e.printStackTrace(out);
                }
            }

        } else {
            out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
            tellUser(splash, "SORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING");
        }

        savedSystemOut = out;
        savedSystemErr = err;
        System.setOut(debugOut);
        System.setErr(debugOut);
        if (splash != null)
            splash.close();
    }
    // splashDemo.closeWindow();
}

From source file:at.ac.tuwien.inso.subcat.ui.ViewFactory.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("h", "help", false, "Show this options");
    options.addOption("d", "db", true, "The database to process (required)");
    options.addOption("p", "project", true, "The project ID to process");
    options.addOption("P", "list-projects", false, "List all registered projects");
    options.addOption("C", "config", true, "A configuration file including reports");
    options.addOption("c", "commit-dictionary", true, "The commit dictionary ID to use");
    options.addOption("b", "bug-dictionary", true, "The bug dictionary ID to use");
    options.addOption("D", "list-dictionaries", false, "List all dictionaries");
    options.addOption("e", "db-extension", true, "Sqlite extension");
    options.addOption("v", "verbose", false, "Show details");

    Reporter reporter = new Reporter(false);
    String[] extensions = new String[0];
    ModelPool pool = null;/*from  w w w.j  a va2s.  co m*/
    Model model = null;

    CommandLineParser parser = new PosixParser();
    boolean printDetails = false;

    try {
        CommandLine cmd = parser.parse(options, args);
        printDetails = cmd.hasOption("verbose");

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("postprocessor", options);
            return;
        }

        if (cmd.hasOption("db-extension")) {
            extensions = cmd.getOptionValues("db-extension");
        }

        if (cmd.hasOption("db") == false) {
            reporter.error("explorer", "Option --db is required");
            reporter.printSummary();
            return;
        }

        if (cmd.hasOption("config") == false) {
            reporter.error("explorer", "Option --config is required");
            reporter.printSummary();
            return;
        }

        Configuration config = new Configuration();
        Parser configParser = new Parser();
        try {
            configParser.parse(config, new File(cmd.getOptionValue("config")));
        } catch (IOException e) {
            reporter.error("explorer", "Could not read configuration file: " + e.getMessage());
            reporter.printSummary();
            return;
        } catch (ParserException e) {
            reporter.error("explorer", "Could not parse configuration file: " + e.getMessage());
            reporter.printSummary();
            return;
        }

        File dbf = new File(cmd.getOptionValue("db"));
        if (dbf.exists() == false || dbf.isFile() == false) {
            reporter.error("explorer", "Invalid database file path");
            reporter.printSummary();
            return;
        }

        pool = new ModelPool(cmd.getOptionValue("db"), 2, extensions);
        pool.setPrintTemplates(printDetails);
        model = pool.getModel();

        if (cmd.hasOption("list-projects")) {
            for (Project proj : model.getProjects()) {
                System.out.println("  " + proj.getId() + ": " + proj.getDate());
            }

            return;
        }

        Integer projId = null;
        if (cmd.hasOption("project") == false) {
            reporter.error("explorer", "Option --project is required");
            reporter.printSummary();
            return;
        } else {
            try {
                projId = Integer.parseInt(cmd.getOptionValue("project"));
            } catch (NumberFormatException e) {
                reporter.error("explorer", "Invalid project ID");
                reporter.printSummary();
                return;
            }
        }

        Project project = model.getProject(projId);
        if (project == null) {
            reporter.error("explorer", "Invalid project ID");
            reporter.printSummary();
            return;
        }

        if (cmd.hasOption("list-dictionaries")) {
            List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
            for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                System.out.println("  (" + dict.getId() + ") " + dict.getContext() + " " + dict.getName());
            }
            return;
        }

        int bugDictId = -1;
        if (cmd.hasOption("bug-dictionary")) {
            try {
                bugDictId = Integer.parseInt(cmd.getOptionValue("bug-dictionary"));
                List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
                boolean valid = false;

                for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                    if (dict.getId() == bugDictId) {
                        valid = true;
                        break;
                    }
                }

                if (valid == false) {
                    reporter.error("explorer", "Invalid bug dictionary ID");
                    reporter.printSummary();
                    return;
                }
            } catch (NumberFormatException e) {
                reporter.error("explorer", "Invalid bug dictionary ID");
                reporter.printSummary();
                return;
            }
        } else {
            List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
            for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                if (dict.getContext().equals("bug")) {
                    bugDictId = dict.getId();
                    break;
                }
            }
        }

        int commitDictId = -1;
        if (cmd.hasOption("commit-dictionary")) {
            try {
                commitDictId = Integer.parseInt(cmd.getOptionValue("commit-dictionary"));
                List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
                boolean valid = false;

                for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                    if (dict.getId() == commitDictId) {
                        valid = true;
                        break;
                    }
                }

                if (valid == false) {
                    reporter.error("explorer", "Invalid commit dictionary ID");
                    reporter.printSummary();
                    return;
                }
            } catch (NumberFormatException e) {
                reporter.error("explorer", "Invalid commit dictionary ID");
                reporter.printSummary();
                return;
            }
        } else {
            List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
            for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                if (dict.getContext().equals("src")) {
                    commitDictId = dict.getId();
                    break;
                }
            }
        }

        // UI:
        Display display = new Display();
        final Shell shell = new Shell(display);
        final StackLayout stack = new StackLayout();
        shell.setLayout(stack);

        Composite _projectControl = null;
        Composite _teamControl = null;
        Composite _userControl = null;

        if (config.getProjectViewConfig() != null) {
            ViewFactory factory = new ViewFactory(model, config);
            _projectControl = factory.createProjectViewComposite(shell, SWT.NONE, project, commitDictId,
                    bugDictId, config.getProjectViewConfig());
        }

        if (config.getTeamViewConfig() != null) {
            ViewFactory factory = new ViewFactory(model, config);
            _teamControl = factory.createTeamViewComposite(shell, SWT.NONE, project, commitDictId, bugDictId,
                    config.getTeamViewConfig());
        }

        if (config.getUserViewConfig() != null) {
            ViewFactory factory = new ViewFactory(model, config);
            _userControl = factory.createUserViewComposite(shell, SWT.NONE, project, commitDictId, bugDictId,
                    config.getUserViewConfig());
        }

        final Composite projectControl = _projectControl;
        final Composite teamControl = _teamControl;
        final Composite userControl = _userControl;

        // Menu:
        Menu menu = new Menu(shell, SWT.BAR);
        shell.setMenuBar(menu);

        MenuItem mntmNewSubmenu = new MenuItem(menu, SWT.CASCADE);
        mntmNewSubmenu.setText("Views");

        Menu viewMenu = new Menu(shell, SWT.DROP_DOWN);
        mntmNewSubmenu.setMenu(viewMenu);

        Composite defaultView = null;

        if (projectControl != null) {
            MenuItem projectRadio = new MenuItem(viewMenu, SWT.RADIO);
            projectRadio.setText("Project View");
            projectRadio.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetDefaultSelected(SelectionEvent arg0) {
                    stack.topControl = projectControl;
                    shell.layout();
                }

                @Override
                public void widgetSelected(SelectionEvent arg0) {
                    stack.topControl = projectControl;
                    shell.layout();
                }
            });

            defaultView = projectControl;
            projectRadio.setSelection(true);
        }

        if (teamControl != null) {
            MenuItem teamRadio = new MenuItem(viewMenu, SWT.RADIO);
            teamRadio.setText("Team View");
            teamRadio.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetDefaultSelected(SelectionEvent arg0) {
                    stack.topControl = teamControl;
                    shell.layout();
                }

                @Override
                public void widgetSelected(SelectionEvent arg0) {
                    stack.topControl = teamControl;
                    shell.layout();
                }
            });

            if (defaultView == null) {
                defaultView = teamControl;
                teamRadio.setSelection(true);
            }
        }

        if (userControl != null) {
            MenuItem userRadio = new MenuItem(viewMenu, SWT.RADIO);
            userRadio.setText("User View");
            userRadio.addSelectionListener(new SelectionListener() {
                @Override
                public void widgetDefaultSelected(SelectionEvent arg0) {
                    stack.topControl = userControl;
                    shell.layout();
                }

                @Override
                public void widgetSelected(SelectionEvent arg0) {
                    stack.topControl = userControl;
                    shell.layout();
                }
            });

            if (defaultView == null) {
                defaultView = userControl;
                userRadio.setSelection(true);
            }
        }

        stack.topControl = defaultView;

        // Display:
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();

        /*/ UI:
        Display display = new Display ();
                
        Shell teamShell = new Shell (display, SWT.CLOSE);
        teamShell.setLayout (new FillLayout ());
                
        Shell projectShell = new Shell (display, SWT.CLOSE);
        projectShell.setLayout (new FillLayout ());
                
        projectShell.setText ("Project View");
        teamShell.setText ("Team View");
                
        if (config.getTeamViewConfig () != null) {
           ViewFactory factory = new ViewFactory (model, config);
           factory.createTeamViewComposite (teamShell, SWT.NONE, project, commitDictId, bugDictId, config.getTeamViewConfig ());
                
           teamShell.pack();
           teamShell.open ();
        } else {
           teamShell.dispose ();
        }
                
        if (config.getProjectViewConfig () != null) {
           ViewFactory factory = new ViewFactory (model, config);
           factory.createProjectViewComposite (projectShell, SWT.NONE, project, commitDictId, bugDictId, config.getProjectViewConfig ());
                
           projectShell.pack();
           projectShell.open ();
        } else {
           projectShell.dispose ();
        }
                
        teamShell.addListener (SWT.CLOSE, new Listener () {
           @Override
           public void handleEvent (Event event) {
              teamShell.dispose ();
           }
        });
                
        projectShell.addListener (SWT.CLOSE, new Listener () {
           @Override
           public void handleEvent (Event event) {
              projectShell.dispose ();
           }
        });
                
          while (!display.isDisposed ()) {
             if (teamShell.isDisposed () && projectShell.isDisposed ()) {
         break;
             }
           if (!display.readAndDispatch ()) {
              display.sleep ();
           }
        }
                
        display.dispose();
        */
    } catch (ParseException e) {
        reporter.error("explorer", "Parsing failed: " + e.getMessage());
        if (printDetails == true) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        reporter.error("explorer", "Failed to create a database connection: " + e.getMessage());
        if (printDetails == true) {
            e.printStackTrace();
        }
    } catch (SQLException e) {
        reporter.error("explorer", "Failed to create a database connection: " + e.getMessage());
        if (printDetails == true) {
            e.printStackTrace();
        }
    } catch (SemanticException e) {
        reporter.error("explorer", "Semantic Error: " + e.getMessage());
        if (printDetails == true) {
            e.printStackTrace();
        }
    } finally {
        if (model != null) {
            model.close();
        }
        if (pool != null) {
            pool.close();
        }
    }

    reporter.printSummary();
}

From source file:com.zimbra.kabuki.tools.img.ImageMerger.java

public static void main(String[] argv) throws Exception {
    // parse command-line
    CommandLineParser parser = new GnuParser();
    CommandLine cl = null;/*from  ww w.j a va  2s.  c  o m*/
    try {
        cl = parser.parse(OPTIONS, argv);
    } catch (ParseException pe) {
        System.err.println(pe);
        printUsageAndExit();
    }
    if (cl == null) {
        printUsageAndExit();
    }

    // handle options
    ImageMerger merger = new ImageMerger();
    List<File> inputDirs = new LinkedList<File>();
    if (cl.hasOption(O_INPUT)) {
        for (String dirname : cl.getOptionValue(O_INPUT).split("[;,]")) {
            File dir = new File(dirname);
            assertAndExit(dir.exists(), "directory %s doesn't exist", dir.toString());
            assertAndExit(dir.isDirectory(), "%s is not a directory", dir.toString());
            inputDirs.add(dir);
        }
    }
    if (cl.hasOption(O_OUTPUT)) {
        File dir = new File(cl.getOptionValue(O_OUTPUT));
        assertAndExit(dir.exists(), "directory %s doesn't exist", dir.toString());
        assertAndExit(dir.isDirectory(), "%s is not a directory", dir.toString());
        merger.setOutputDirectory(dir);
    }
    if (cl.hasOption(O_CSS_PATH) && cl.hasOption(O_CSS_FILENAME)) {
        merger.setCssPath(cl.getOptionValue(O_CSS_PATH));
        merger.setCssFilename(cl.getOptionValue(O_CSS_FILENAME));
        String cacheFilename = cl.getOptionValue(O_CACHE_FILENAME);
        if (cacheFilename != null) {
            merger.setCacheFilename(cacheFilename);
        }
    }
    if (cl.hasOption(O_JS_FILENAME)) {
        merger.setJsFilename(cl.getOptionValue(O_JS_FILENAME));
    }
    if (cl.hasOption(O_COPY)) {
        merger.setCopyFiles(true);
    }
    if (cl.hasOption(O_NO_APPEND)) {
        merger.setAppendOutput(false);
    }
    if (cl.hasOption(O_VERBOSE)) {
        merger.setVerbose(true);
    }
    if (cl.hasOption(O_DISABLED_IMAGES)) {
        printWarning("option -%s is deprecated", O_DISABLED_IMAGES);
    }
    if (cl.hasOption(O_SPACER_IMAGES)) {
        merger.setSpacerImagesPath(cl.getOptionValue(O_SPACER_IMAGES));
    }
    // process
    assertAndExit(inputDirs.size() > 0, "must specify input directories");
    merger.process(inputDirs);
}

From source file:edu.stanford.epadd.launcher.Splash.java

public static void main(String args[]) throws Exception {
    Splash splash = null;//  w w w  .  java2  s . co  m

    boolean headless = (System.getProperty("muse.mode.server") != null);
    if (!headless)
        splash = new Splash();
    else {
        System.out.println("Muse running in headless mode!");
        browserOpen = false;
    }

    tellUser(splash, "Setting up logging...");
    setupLogging();
    basicSetup(args);
    BASE_URL = "http://localhost:" + PORT + "/" + WEBAPP_NAME;
    MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.

    tellUser(splash, "Log file: " + debugFile + "***\n");

    out.println("Starting up ePADD on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    tellUser(splash, "Memory: " + getMemoryStats());

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! ePADD already running at: " + BASE_URL + ", will shut it down!");
        tellUser(splash, "ePADD already running at: " + BASE_URL + ", will shut it down!");
        killRunningServer(BASE_URL);

        boolean killed = false;
        int N_KILL_TRIES = 20, N_KILL_PERIOD_MILLIS = 3000;
        // check every 3 secs 20 times (total 1 minute) for the previous epadd to die
        // if it doesn't die after a minute, fail
        for (int i = 0; i < N_KILL_TRIES; i++) {
            try {
                Thread.sleep(N_KILL_PERIOD_MILLIS);
            } catch (InterruptedException ie) {
            }
            out.println("Checking " + MUSE_CHECK_URL);
            tellUser(splash, "Checking " + MUSE_CHECK_URL);
            try {
                urlAlive = isURLAlive(MUSE_CHECK_URL);
            } catch (Exception e) {
                out.println("Exception: " + e);
                e.printStackTrace(out);
            }
            if (!urlAlive)
                break;
        }

        if (!urlAlive) {
            out.println("Good. Shutdown succeeded, will restart");
            tellUser(splash, "Good. Shutdown succeeded, we'll restart ePADD.");
        } else {
            String message = "Previously running ePADD still alive despite attempt to shut it down, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL;
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n";
            aggressiveWarn(message, 2000);
            tellUser(splash, "Sorry, unable to kill previous ePADD. Quitting!");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException ie) {
            }
            if (splash != null)
                splash.close();
            return;
        }
    }

    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        setupResources();
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        tellUser(splash, "Starting ePADD at " + BASE_URL);

        server.start();

        PrintStream debugOut1 = err;
        try {
            File f = new File(debugFile);
            if (f.exists())
                f.delete(); // particular problem on windows :-(
            debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
        } catch (IOException ioe) {
            out.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
        }

        final PrintStream debugOut = debugOut1;

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    shutdownSessions();
                    server.stop();
                    server.destroy();
                    debugOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }));

        boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);

        if (success) {
            try {
                int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 
                tellUser(splash, "Setting up shutdown port...");

                new ShutdownThread(server, shutdownPort).start(); // this will start a non-daemon thread that keeps the process alive
                out.println("Listening for ePADD shutdown message on port " + shutdownPort);
                tellUser(splash, "Listening for ePADD shutdown message on port " + shutdownPort);

            } catch (Exception e) {
                out.println(
                        "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
            }

            try {
                setupSystemTrayIcon();
            } catch (Exception e) {
                out.println("Unable to setup system tray icon: " + e);
                e.printStackTrace(err);
            }

            // open browser window
            if (browserOpen) {
                preferredBrowser = null;
                // launch a browser here
                try {

                    String link;
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                    if (startPage != null) {
                        // startPage has to be absolute
                        link = "http://localhost:" + PORT + "/muse/" + startPage;
                    }

                    if (baseDir != null)
                        link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                    launchBrowser(link, splash);

                } catch (Exception e) {
                    out.println(
                            "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):");
                    e.printStackTrace(out);
                }
            }

        } else {
            out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
            tellUser(splash, "SORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING");
        }

        savedSystemOut = out;
        savedSystemErr = err;
        System.setOut(debugOut);
        System.setErr(debugOut);
        if (splash != null)
            splash.close();
    }
    // program should not halt here, as ShutdownThread is running as a non-daemon thread.
    // splashDemo.closeWindow();
}

From source file:net.yacy.yacy.java

/**
 * Main-method which is started by java. Checks for special arguments or
 * starts up the application.//from  www  .ja  v a2  s .  c  o m
 *
 * @param args
 *            Given arguments from the command line.
 */
public static void main(String args[]) {

    try {
        // check assertion status
        //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
        boolean assertionenabled = false;
        assert (assertionenabled = true) == true; // compare to true to remove warning: "Possible accidental assignement"
        if (assertionenabled)
            System.out.println("Asserts are enabled");

        // check memory amount
        System.gc();
        final long startupMemFree = MemoryControl.free();
        final long startupMemTotal = MemoryControl.total();

        // maybe go into headless awt mode: we have three cases depending on OS and one exception:
        // windows   : better do not go into headless mode
        // mac       : go into headless mode because an application is shown in gui which may not be wanted
        // linux     : go into headless mode because this does not need any head operation
        // exception : if the -gui option is used then do not go into headless mode since that uses a gui
        boolean headless = true;
        if (OS.isWindows)
            headless = false;
        if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui"))
            headless = false;
        System.setProperty("java.awt.headless", headless ? "true" : "false");

        String s = "";
        for (final String a : args)
            s += a + " ";
        yacyRelease.startParameter = s.trim();

        File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/'));
        File dataRoot = applicationRoot;
        //System.out.println("args.length=" + args.length);
        //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]");
        if ((args.length >= 1)
                && (args[0].toLowerCase(Locale.ROOT).equals("-startup") || args[0].equals("-start"))) {
            // normal start-up of yacy
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        } else if (args.length >= 1 && args[0].toLowerCase(Locale.ROOT).equals("-gui")) {
            // start-up of yacy with gui
            if (args.length > 1) {
                if (args[1].startsWith(File.separator)) {
                    /* data root folder provided as an absolute path */
                    dataRoot = new File(args[1]);
                } else {
                    /* data root folder provided as a path relative to the user home folder */
                    dataRoot = new File(System.getProperty("user.home").replace('\\', '/'), args[1]);
                }
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, true);
        } else if ((args.length >= 1)
                && ((args[0].toLowerCase(Locale.ROOT).equals("-shutdown")) || (args[0].equals("-stop")))) {
            // normal shutdown of yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            shutdown(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-update"))) {
            // aut-update yacy
            if (args.length == 2)
                applicationRoot = new File(args[1]);
            update(applicationRoot);
        } else if ((args.length >= 1) && (args[0].toLowerCase(Locale.ROOT).equals("-version"))) {
            // show yacy version
            System.out.println(copyright);
        } else if ((args.length > 1) && (args[0].toLowerCase(Locale.ROOT).equals("-config"))) {
            // set config parameter. Special handling of adminAccount=user:pwd (generates md5 encoded password)
            // on Windows parameter should be enclosed in doublequotes to accept = sign (e.g. -config "port=8090" "port.ssl=8043")
            File f = new File(dataRoot, "DATA/SETTINGS/");
            if (!f.exists()) {
                mkdirsIfNeseccary(f);
            } else {
                if (new File(dataRoot, "DATA/yacy.running").exists()) {
                    System.out.println("please restart YaCy");
                }
            }
            // use serverSwitch to read config properties (including init values from yacy.init
            serverSwitch ss = new serverSwitch(dataRoot, applicationRoot, "defaults/yacy.init",
                    "DATA/SETTINGS/yacy.conf");

            for (int icnt = 1; icnt < args.length; icnt++) {
                String cfg = args[icnt];
                int pos = cfg.indexOf('=');
                if (pos > 0) {
                    String cmd = cfg.substring(0, pos);
                    String val = cfg.substring(pos + 1);

                    if (!val.isEmpty()) {
                        if (cmd.equalsIgnoreCase(SwitchboardConstants.ADMIN_ACCOUNT)) { // special command to set adminusername and md5-pwd
                            int cpos = val.indexOf(':'); //format adminAccount=adminname:adminpwd
                            if (cpos >= 0) {
                                String username = val.substring(0, cpos);
                                String pwdtxt = val.substring(cpos + 1);
                                if (!username.isEmpty()) {
                                    ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME, username);
                                    System.out.println("Set property "
                                            + SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME + " = " + username);
                                } else {
                                    username = ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_USER_NAME,
                                            "admin");
                                }
                                ss.setConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5,
                                        "MD5:" + Digest.encodeMD5Hex(username + ":"
                                                + ss.getConfig(SwitchboardConstants.ADMIN_REALM, "YaCy") + ":"
                                                + pwdtxt));
                                System.out.println("Set property " + SwitchboardConstants.ADMIN_ACCOUNT_B64MD5
                                        + " = " + ss.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, ""));
                            }
                        } else {
                            ss.setConfig(cmd, val);
                            System.out.println("Set property " + cmd + " = " + val);
                        }
                    }
                } else {
                    System.out.println(
                            "skip parameter " + cfg + " (equal sign missing, put parameter in doublequotes)");
                }
                System.out.println();
            }
        } else {
            if (args.length == 1) {
                applicationRoot = new File(args[0]);
            }
            preReadSavedConfigandInit(dataRoot);
            startup(dataRoot, applicationRoot, startupMemFree, startupMemTotal, false);
        }
    } finally {
        ConcurrentLog.shutdown();
    }
}

From source file:org.fcrepo.client.test.PerformanceTests.java

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

    if (args.length < 8 || args.length > 9) {
        usage();/* w  ww.  j av a 2 s .  com*/
    }

    String host = args[0];
    String port = args[1];
    String username = args[2];
    String password = args[3];
    String itr = args[4];
    String thrds = args[5];
    String output = args[6];
    String name = args[7];
    String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;

    if (args.length == 9 && !args[8].equals("")) {
        context = args[8];
    }

    if (host == null || host.startsWith("$") || port == null || port.startsWith("$") || username == null
            || username.startsWith("$") || password == null || password.startsWith("$") || itr == null
            || itr.startsWith("$") || thrds == null || thrds.startsWith("$") || output == null
            || output.startsWith("$") || name == null || name.startsWith("$")) {
        usage();
    }
    name = name.replaceAll(",", ";");
    iterations = Integer.parseInt(itr);
    threads = Integer.parseInt(thrds);

    boolean newFile = true;
    File outputFile = new File(output);

    File tempFile = null;
    BufferedReader reader = null;
    String line = "";
    if (outputFile.exists()) {
        newFile = false;

        // Create a copy of the file to read from
        tempFile = File.createTempFile("performance-test", "tmp");
        BufferedReader input = new BufferedReader(new FileReader(outputFile));
        PrintStream tempOut = new PrintStream(tempFile);

        while ((line = input.readLine()) != null) {
            tempOut.println(line);
        }
        input.close();
        tempOut.close();

        reader = new BufferedReader(new FileReader(tempFile));
    }
    PrintStream out = new PrintStream(outputFile);

    if (newFile) {
        out.println(
                "--------------------------------------------------------------" + " Performance Test Results "
                        + "--------------------------------------------------------------");
    }

    PerformanceTests tests = new PerformanceTests();
    tests.init(host, port, context, username, password);
    System.out.println("Running Ingest Round-Trip Test...");
    long ingestResults = tests.runIngestTest();
    System.out.println("Running AddDatastream Round-Trip Test...");
    long addDsResults = tests.runAddDatastreamTest();
    System.out.println("Running ModifyDatastreamByReference Round-Trip Test...");
    long modifyRefResults = tests.runModifyDatastreamByRefTest();
    System.out.println("Running ModifyDatastreamByValue Round-Trip Test...");
    long modifyValResults = tests.runModifyDatastreamByValueTest();
    System.out.println("Running PurgeDatastream Round-Trip Test...");
    long purgeDsResults = tests.runPurgeDatastreamTest();
    System.out.println("Running PurgeObject Round-Trip Test...");
    long purgeObjectResults = tests.runPurgeObjectTest();
    System.out.println("Running GetDatastream Round-Trip Test...");
    long getDatastreamResults = tests.runGetDatastreamTest();
    System.out.println("Running GetDatastreamREST Round-Trip Test...");
    long getDatastreamRestResults = tests.runGetDatastreamRestTest();
    System.out.println("Running Throughput Tests...");
    long[] tpResults = tests.runThroughputTests();
    System.out.println("Running Threaded Throughput Tests...");
    long[] tptResults = tests.runThreadedThroughputTests();

    if (newFile) {
        out.println(
                "1. Test performing each operation in isolation. Time (in ms) is the average required to perform each operation.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + ingestResults + ", " + addDsResults + ", " + modifyRefResults + ", "
            + modifyValResults + ", " + purgeDsResults + ", " + purgeObjectResults + ", "
            + getDatastreamResults / iterations + ", " + getDatastreamRestResults / iterations);

    out.println();
    if (newFile) {
        out.println("2. Operations-Per-Second based on results listed in item 1.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestPerSecond = 1000 / (double) ingestResults;
    double addDsPerSecond = 1000 / (double) addDsResults;
    double modifyRefPerSecond = 1000 / (double) modifyRefResults;
    double modifyValPerSecond = 1000 / (double) modifyValResults;
    double purgeDsPerSecond = 1000 / (double) purgeDsResults;
    double purgeObjPerSecond = 1000 / (double) purgeObjectResults;
    double getDatastreamPerSecond = 1000 / ((double) getDatastreamResults / iterations);
    double getDatastreamRestPerSecond = 1000 / ((double) getDatastreamRestResults / iterations);
    out.println(name + ", " + round(ingestPerSecond) + ", " + round(addDsPerSecond) + ", "
            + round(modifyRefPerSecond) + ", " + round(modifyValPerSecond) + ", " + round(purgeDsPerSecond)
            + ", " + round(purgeObjPerSecond) + ", " + round(getDatastreamPerSecond) + ", "
            + round(getDatastreamRestPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "3. Test performing operations back-to-back. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tpResults[0] + ", " + tpResults[1] + ", " + tpResults[2] + ", " + tpResults[3]
            + ", " + tpResults[4] + ", " + tpResults[5] + ", " + getDatastreamResults + ", "
            + getDatastreamRestResults);

    out.println();
    if (newFile) {
        out.println("4. Operations-Per-Second based on results listed in item 3.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double ingestItPerSecond = (double) (iterations * 1000) / tpResults[0];
    double addDsItPerSecond = (double) (iterations * 1000) / tpResults[1];
    double modifyRefItPerSecond = (double) (iterations * 1000) / tpResults[2];
    double modifyValItPerSecond = (double) (iterations * 1000) / tpResults[3];
    double purgeDsItPerSecond = (double) (iterations * 1000) / tpResults[4];
    double purgeObjItPerSecond = (double) (iterations * 1000) / tpResults[5];
    double getDsItPerSecond = (double) (iterations * 1000) / getDatastreamResults;
    double getDsRestItPerSecond = (double) (iterations * 1000) / getDatastreamRestResults;
    out.println(name + ", " + round(ingestItPerSecond) + ", " + round(addDsItPerSecond) + ", "
            + round(modifyRefItPerSecond) + ", " + round(modifyValItPerSecond) + ", "
            + round(purgeDsItPerSecond) + ", " + round(purgeObjItPerSecond) + ", " + round(getDsItPerSecond)
            + ", " + round(getDsRestItPerSecond));

    out.println();
    if (newFile) {
        out.println(
                "5. Test performing operations using a thread pool. Time (in ms) is that required to perform all iterations.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    out.println(name + ", " + tptResults[0] + ", " + tptResults[1] + ", " + tptResults[2] + ", " + tptResults[3]
            + ", " + tptResults[4] + ", " + tptResults[5] + ", " + tptResults[6] + ", " + tptResults[7]);

    out.println();
    if (newFile) {
        out.println("6. Operations-Per-Second based on results listed in item 5.");
        out.println(
                "test name, ingest, addDatastream, modifyDatastreamByReference, modifyDatastreamByValue, purgeDatastream, purgeObject, getDatastream, getDatastreamREST");
    } else {
        line = reader.readLine();
        while (line != null && line.length() > 2) {
            out.println(line);
            line = reader.readLine();
        }
    }
    double thrdIngestItPerSecond = (double) (iterations * 1000) / tptResults[0];
    double thrdAddDsItPerSecond = (double) (iterations * 1000) / tptResults[1];
    double thrdModifyRefItPerSecond = (double) (iterations * 1000) / tptResults[2];
    double thrdModifyValItPerSecond = (double) (iterations * 1000) / tptResults[3];
    double thrdPurgeDsItPerSecond = (double) (iterations * 1000) / tptResults[4];
    double thrdPurgeObjItPerSecond = (double) (iterations * 1000) / tptResults[5];
    double thrdGetDsItPerSecond = (double) (iterations * 1000) / tptResults[6];
    double thrdGetDsRestItPerSecond = (double) (iterations * 1000) / tptResults[7];
    out.println(name + ", " + round(thrdIngestItPerSecond) + ", " + round(thrdAddDsItPerSecond) + ", "
            + round(thrdModifyRefItPerSecond) + ", " + round(thrdModifyValItPerSecond) + ", "
            + round(thrdPurgeDsItPerSecond) + ", " + round(thrdPurgeObjItPerSecond) + ", "
            + round(thrdGetDsItPerSecond) + ", " + round(thrdGetDsRestItPerSecond));

    if (!newFile) {
        reader.close();
        tempFile.delete();
    }
    out.close();

    System.out.println("Performance Tests Complete.");
}

From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param cmdArgs Arguments./*from  w w  w . j  a  v a 2 s  .  c o m*/
 */
public static void main(String[] cmdArgs) {
    try {
        JFreeChartGraphPlotterArguments args = new JFreeChartGraphPlotterArguments();

        JCommander jCommander = jcommander(cmdArgs, args, "<graph-plotter>");

        if (args.help()) {
            jCommander.usage();

            return;
        }

        if (args.inputFolders().isEmpty()) {
            errorHelp("Input folders are not defined.");

            return;
        }

        List<String> inFoldersAsString = args.inputFolders();

        List<File> inFolders = new ArrayList<>(inFoldersAsString.size());

        for (String folderAsString : inFoldersAsString)
            inFolders.add(new File(folderAsString).getAbsoluteFile());

        for (File inFolder : inFolders) {
            if (!inFolder.exists()) {
                errorHelp("Folder does not exist: " + inFolder.getAbsolutePath());

                return;
            }
        }

        List<List<List<File>>> benchFolders = new ArrayList<>();

        for (File inFolder : inFolders) {
            File[] dirs0 = inFolder.listFiles();

            if (dirs0 == null || dirs0.length == 0)
                continue;

            List<File> dirs = new ArrayList<>(Arrays.asList(dirs0));

            Collections.sort(dirs, FILE_NAME_COMP);

            boolean multipleDrivers = false;

            for (File f : dirs) {
                if (f.isFile() && MULTIPLE_DRIVERS_MARKER_FILE.equals(f.getName())) {
                    multipleDrivers = true;

                    break;
                }
            }

            List<List<File>> mulDrvFiles = new ArrayList<>();

            if (multipleDrivers) {
                for (File f : dirs) {
                    List<File> files = getFiles(f);

                    if (files != null)
                        mulDrvFiles.add(files);
                }
            } else {
                List<File> files = getFiles(inFolder);

                if (files != null)
                    mulDrvFiles.add(files);
            }

            benchFolders.add(mergeMultipleDriverLists(mulDrvFiles));
        }

        if (benchFolders.isEmpty()) {
            errorHelp("Input folders are empty or have invalid structure: " + inFoldersAsString);

            return;
        }

        String outputFolder = outputFolder(inFolders);

        JFreeChartGenerationMode mode = args.generationMode();

        if (mode == COMPOUND)
            processCompoundMode(outputFolder, benchFolders, args);
        else if (mode == COMPARISON)
            processComparisonMode(outputFolder, benchFolders, args);
        else if (mode == STANDARD)
            processStandardMode(benchFolders, args);
        else
            errorHelp("Unknown generation mode: " + args.generationMode());
    } catch (ParameterException e) {
        errorHelp("Invalid parameter.", e);
    } catch (Exception e) {
        errorHelp("Failed to execute graph generator.", e);
    }
}

From source file:cl.utfsm.cdbChecker.CDBChecker.java

/**
 * Main function to run the cdbChecker tool.
 * System.exit(0/1) is used to return success if everything if fine or
 * failure in case errors were encountered.
 *//*from ww  w .  j av  a 2  s .co  m*/
public static void main(String[] args) {

    Logger logger = ClientLogManager.getAcsLogManager()
            .getLoggerForApplication(CDBChecker.class.getSimpleName(), false);
    CDBChecker cdbchecker = new CDBChecker(logger);
    cdbchecker.props = System.getProperties();

    /* Blank lines to see the output clearly */
    System.out.println("\n\n");

    /*
     * Retrieves the CDB path from the property, if given
     */
    String ACS_cdbpath = cdbchecker.props.getProperty("ACS.cdbpath");

    /* 
     * Check for Paths and flags received from command line
    * and sets accordiningly member variables.
    * These non explicit side effects should be avoided.
    */

    if (cdbchecker.checkArgs(args)) {
        //add panta@naoj 2009/10/05
        String pathsMulti[] = cdbchecker.XMLPath.split(File.pathSeparator);

        for (int i = 0; i < pathsMulti.length; i++) {
            File file_ = new File(pathsMulti[i]);
            if (!file_.exists()) {
                System.out.println("*** ImplLang Check: Specified path " + file_ + " does not exist");
                cdbchecker.setGlobalErrorFlag(true);
                cdbchecker.showEndResult();
                break;
            }
        }
        //add panta@naoj 2009/10/05 end

        //Creating the parser
        //         System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", "org.apache.xerces.parsers.XIncludeAwareParserConfiguration");
        cdbchecker.SP = new SAXParser();
        cdbchecker.xsd_targetns = new Hashtable<String, String>();

        //Download the required Schemas

        if (cdbchecker.verbose) {
            System.out.println("*** Reading required schema files");
        }

        if (cdbchecker.configLoader()) {
            if (cdbchecker.verbose) {
                System.out.println("*** Reading given schema files");
            }
            // Appends command line schema files, if any
            if (ACS_cdbpath != null) {
                // We assume that cdbchecker.XSDPath is at least initialised to the empty string and never null
                // Modify panta@naoj 2009/10/15
                if (cdbchecker.XSDPath == null) {
                    cdbchecker.XSDPath = ACS_cdbpath;
                } else {
                    cdbchecker.XSDPath = cdbchecker.XSDPath + ":" + ACS_cdbpath;
                }
            }
            if (cdbchecker.checkidl) {
                if (cdbchecker.verbose) {
                    System.out.println("*** Checking Idl Types");
                }
                cdbchecker.checkIdlTypes();
            }
            String paths[] = cdbchecker.XSDPath.split(File.pathSeparator);
            Vector<String> xsdFilenames = cdbchecker.getFilenames(paths, "xsd");

            if (cdbchecker.verbose)
                System.out.println("*** Reading given XML files");
            // We assume that cdbchecker.XMLPath is at least
            // initialised to the empty string and never null

            paths = cdbchecker.XMLPath.split(File.pathSeparator);
            Vector<String> XMLFilenames = cdbchecker.getFilenames(paths, "xml");

            // Fill the map with the targetNamespace and the filenames
            if (cdbchecker.verbose)
                System.out.println("*** Getting TargetNamespaces from schema files");
            cdbchecker.getTargetNamespace(xsdFilenames);

            // Validating Schemas
            if (cdbchecker.verbose)
                System.out.println("*** Validating Schemas");
            cdbchecker.validateSchemas(xsdFilenames);

            // Validating XML files
            if (cdbchecker.verbose)
                System.out.println("*** Validating XML files");
            cdbchecker.XMLValidate(XMLFilenames);

            // add panta@naoj 2009/10/05
            // checks if implLang matches, those written in XXComponents.xml and XXContainers.xml
            for (int i = 0; i < pathsMulti.length; i++) {
                cdbchecker.componentsFolder = pathsMulti[i] + File.separator + "MACI" + File.separator
                        + "Components";
                cdbchecker.containersFolder = pathsMulti[i] + File.separator + "MACI" + File.separator
                        + "Containers";

                File compFolder = new File(cdbchecker.componentsFolder);
                File contFolder = new File(cdbchecker.containersFolder);
                // System.out.println("compFolder: " + compFolder);
                // System.out.println("contFolder: " + contFolder);

                if (compFolder.exists() && contFolder.exists()) {
                    cdbchecker.setGlobalErrorFlag(cdbchecker.checkImplLangMatch(compFolder, contFolder));

                    // exit if error
                    if (cdbchecker.isGlobalErrorFlag()) {
                        break;
                    }
                }
            }
            // add panta@naoj 2009/10/05 end

        }
    } else {
        printUsage();
    }

    cdbchecker.cleanUp();

    cdbchecker.showEndResult();
}