Example usage for org.apache.commons.cli HelpFormatter HelpFormatter

List of usage examples for org.apache.commons.cli HelpFormatter HelpFormatter

Introduction

In this page you can find the example usage for org.apache.commons.cli HelpFormatter HelpFormatter.

Prototype

HelpFormatter

Source Link

Usage

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;//w ww  . j  a  va  2s.  com
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}

From source file:it.anyplace.sync.client.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("c", "config", false, "dump config");
    options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers");
    options.addOption("q", "query", true, "query directory server for device id");
    options.addOption("d", "discovery", true, "discovery local network for device id");
    options.addOption("p", "pull", true, "pull file from network");
    options.addOption("P", "push", true, "push file to network");
    options.addOption("o", "output", true, "set output file/directory");
    options.addOption("i", "input", true, "set input file/directory");
    options.addOption("lp", "list-peers", false, "list peer addresses");
    options.addOption("a", "address", true, "use this peer addresses");
    options.addOption("L", "list-remote", false, "list folder (root) content from network");
    options.addOption("I", "list-info", false, "dump folder info from network");
    options.addOption("li", "list-info", false, "list folder info from local db");
    //        options.addOption("l", "list-local", false, "list folder content from local (saved) index");
    options.addOption("s", "search", true, "search local index for <term>");
    options.addOption("D", "delete", true, "push delete to network");
    options.addOption("M", "mkdir", true, "push directory create to network");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;/*from   w  w  w .  ja va2s .  co  m*/
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile);
    FileUtils.cleanDirectory(configuration.getTemp());
    KeystoreHandler.newLoader().loadAndStore(configuration);
    if (cmd.hasOption("c")) {
        logger.info("configuration =\n{}", configuration.newWriter().dumpToString());
    } else {
        logger.trace("configuration =\n{}", configuration.newWriter().dumpToString());
    }
    logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());

    if (cmd.hasOption("sp")) {
        List<String> peers = Lists.newArrayList(Lists.transform(
                Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() {
                    @Override
                    public String apply(String input) {
                        return input.trim();
                    }
                }));
        logger.info("set peers = {}", peers);
        configuration.edit().setPeers(Collections.<DeviceInfo>emptyList());
        for (String peer : peers) {
            KeystoreHandler.validateDeviceId(peer);
            configuration.edit().addPeers(new DeviceInfo(peer, null));
        }
        configuration.edit().persistNow();
    }

    if (cmd.hasOption("q")) {
        String deviceId = cmd.getOptionValue("q");
        logger.info("query device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId);
        logger.info("server response = {}", deviceAddresses);
    }
    if (cmd.hasOption("d")) {
        String deviceId = cmd.getOptionValue("d");
        logger.info("discovery device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId);
        logger.info("local response = {}", deviceAddresses);
    }

    if (cmd.hasOption("p")) {
        String path = cmd.getOptionValue("p");
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) {
            InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete()
                    .getInputStream();
            String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName();
            File file;
            if (cmd.hasOption("o")) {
                File param = new File(cmd.getOptionValue("o"));
                file = param.isDirectory() ? new File(param, fileName) : param;
            } else {
                file = new File(fileName);
            }
            FileUtils.copyInputStreamToFile(inputStream, file);
            logger.info("saved file to = {}", file.getAbsolutePath());
        }
    }
    if (cmd.hasOption("P")) {
        String path = cmd.getOptionValue("P");
        File file = new File(cmd.getOptionValue("i"));
        checkArgument(!path.startsWith("/")); //TODO check path syntax
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file),
                        folder, path)) {
            while (!fileUploadObserver.isCompleted()) {
                fileUploadObserver.waitForProgressUpdate();
                logger.debug("upload progress {}", fileUploadObserver.getProgressMessage());
            }
            logger.info("uploaded file to network");
        }
    }
    if (cmd.hasOption("D")) {
        String path = cmd.getOptionValue("D");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("delete path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDelete(folder, path)) {
            observer.waitForComplete();
            logger.info("deleted path");
        }
    }
    if (cmd.hasOption("M")) {
        String path = cmd.getOptionValue("M");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("dir path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDir(folder, path)) {
            observer.waitForComplete();
            logger.info("uploaded dir to network");
        }
    }
    if (cmd.hasOption("L")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            client.waitForRemoteIndexAquired();
            for (String folder : client.getIndexHandler().getFolderList()) {
                try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder()
                        .setFolder(folder).build()) {
                    logger.info("list folder = {}", indexBrowser.getFolder());
                    for (FileInfo fileInfo : indexBrowser.listFiles()) {
                        logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1),
                                fileInfo.getPath(), fileInfo.describeSize());
                    }
                }
            }
        }
    }
    if (cmd.hasOption("I")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            if (cmd.hasOption("a")) {
                String deviceId = cmd.getOptionValue("a").substring(0, 63),
                        address = cmd.getOptionValue("a").substring(64);
                try (BlockExchangeConnectionHandler connection = client.getConnection(
                        DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) {
                    client.getIndexHandler().waitForRemoteIndexAquired(connection);
                }
            } else {
                client.waitForRemoteIndexAquired();
            }
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("li")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("lp")) {
        try (SyncthingClient client = new SyncthingClient(configuration);
                DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler()
                        .newDeviceAddressSupplier()) {
            String deviceAddressesStr = "";
            for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) {
                deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : "
                        + deviceAddress.getAddress();
            }
            logger.info("device addresses:\n{}\n", deviceAddressesStr);
        }
    }
    if (cmd.hasOption("s")) {
        String term = cmd.getOptionValue("s");
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) {
            client.waitForRemoteIndexAquired();
            logger.info("search term = '{}'", term);
            IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term);
            if (event.hasGoodResults()) {
                logger.info("search results for term = '{}' :", term);
                for (FileInfo fileInfo : event.getResultList()) {
                    logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(),
                            fileInfo.describeSize());
                }
            } else if (event.hasTooManyResults()) {
                logger.info("too many results found for term = '{}'", term);
            } else {
                logger.info("no result found for term = '{}'", term);
            }
        }
    }
    //        if (cmd.hasOption("l")) {
    //            String indexDump = new IndexHandler(configuration).dumpIndex();
    //            logger.info("index dump = \n\n{}\n", indexDump);
    //        }
    IOUtils.closeQuietly(configuration);
}

From source file:de.prozesskraft.pkraft.Merge.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file//from  ww w. j  a  v  a2  s  . c  o  m
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] instance you want to merge another instance into.")
            //            .isRequired()
            .create("instance");

    Option oguest = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] this instance will be merged into -instance.")
            //            .isRequired()
            .create("guest");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oguest);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("merge", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }
    if (!(commandline.hasOption("guest"))) {
        System.err.println("at least one option -guest is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);

    String[] pathToGuest = commandline.getOptionValues("guest");

    String baseDir = null;
    if (commandline.hasOption("basedir")) {
        java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath());
            exiter();
        } else if (!fileBaseDir.isDirectory()) {
            System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath());
            exiter();
        }
        baseDir = commandline.getOptionValue("basedir");
    }

    // ueberpruefen ob die process.pmb files vorhanden sind
    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }
    for (String pathGuest : pathToGuest) {
        java.io.File fileGuest = new java.io.File(pathGuest);

        // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
        if (!fileGuest.exists()) {
            System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath());
            exiter();
        }
    }

    // base - instance einlesen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    p1.setOutfilebinary(pathToInstance);
    Process p2 = p1.readBinary();

    // alle guests einlesen
    ArrayList<Process> alleGuests = new ArrayList<Process>();
    for (String actPathGuest : pathToGuest) {
        Process p30 = new Process();
        p30.setInfilebinary(actPathGuest);
        Process pGuest = p30.readBinary();

        // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind
        if (!p2.getName().equals(pGuest.getName())) {
            System.err.println("error: instances are not from the same type (-instance=" + p2.getName()
                    + " != -guest=" + pGuest.getName());
            exiter();
        }

        // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind
        if (!p2.getVersion().equals(pGuest.getVersion())) {
            System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!="
                    + pGuest.getVersion());
            exiter();
        }

        alleGuests.add(pGuest);
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p3 = new Process();
    p3.setInfilebinary(pathToInstance);
    Process process = p3.readBinary();

    // den main-prozess ueber die static function klonen
    // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess);
                // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir()
                        + "/process.pmb";
                System.err.println("info: calling: " + call2);

                try {
                    java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
                } catch (IOException e) {
                    System.err.println("error: " + e.getMessage());
                }
            }
        }
    }

    // alle dependent steps der zielinstanz einsammeln
    // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden
    Map<Step, String> dependentSteps = new HashMap<Step, String>();

    // alle guest prozesse merge durchfuehren
    for (Process actGuestProcess : alleGuests) {
        System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary());

        // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren
        for (Step actStep : actGuestProcess.getStep()) {
            if (actStep.isAFannedMultistep()) {
                System.err.println("info: merging from guest instance step " + actStep.getName());
                Step clonedStepForIntegrationInClonedProcess = actStep.clone();
                if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) {
                    System.err.println("info: merging step successfully.");
                    // die downstream steps vom merge-punkt merken
                    for (Step actStepToResetBecauseOfDependency : clonedProcess
                            .getStepDependent(actStep.getName())) {
                        dependentSteps.put(actStepToResetBecauseOfDependency, "dummy");
                    }

                    // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden
                    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                    if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null
                            && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) {
                        String call5 = ini.get("apps", "pradar-attend") + " -instance "
                                + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb";
                        System.err.println("info: calling: " + call5);
                        try {
                            java.lang.Process sysproc = Runtime.getRuntime().exec(call5);
                        } catch (IOException e) {
                            System.err.println("error: " + e.getMessage());
                        }
                    }
                } else {
                    System.err.println("error: merging step failed.");
                }
            } else {
                System.err.println("debug: because it's not a multistep, ignoring from guest instance step "
                        + actStep.getName());
            }
        }
    }

    // alle steps downstream der merge-positionen resetten
    for (Step actStep : dependentSteps.keySet()) {
        actStep.resetBecauseOfDependency();
    }

    // speichern der ergebnis instanz
    clonedProcess.writeBinary();

    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
    String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir()
            + "/process.pmb";
    System.err.println("info: calling: " + call2);

    try {
        java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
    } catch (IOException e) {
        System.err.println("error: " + e.getMessage());
    }

}

From source file:de.huberlin.wbi.cuneiform.cmdline.main.Main.java

public static void main(String[] args)
        throws IOException, ParseException, InterruptedException, NotDerivableException {

    CommandLine cmd;/*from   w  w  w.j a  v a  2 s  .c o m*/
    Options opt;
    BaseRepl repl;
    BaseCreActor cre;
    Path sandbox;
    ExecutorService executor;
    TicketSrcActor ticketSrc;
    JsonSummary summary;
    Path summaryPath;
    Log statLog;
    int nthread;
    Path workDir;

    statLog = LogFactory.getLog("statLogger");

    executor = Executors.newCachedThreadPool();
    try {

        opt = getOptions();
        cmd = parse(args, opt);
        config(cmd);

        if (cmd.hasOption('h')) {

            System.out.println("CUNEIFORM - A Functional Workflow Language\nversion " + BaseRepl.LABEL_VERSION
                    + " build " + BaseRepl.LABEL_BUILD);
            new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

            return;
        }

        if (cmd.hasOption('r'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_R, cmd.getOptionValue('r'));

        if (cmd.hasOption('y'))
            Invocation.putLibPath(ForeignLambdaExpr.LANGID_PYTHON, cmd.getOptionValue('y'));

        if (cmd.hasOption('l'))
            sandbox = Paths.get(cmd.getOptionValue("l"));
        else
            sandbox = Paths.get(System.getProperty("user.home")).resolve(".cuneiform");

        sandbox = sandbox.toAbsolutePath();

        if (cmd.hasOption('c'))
            LocalThread.deleteIfExists(sandbox);

        if (cmd.hasOption('t'))
            nthread = Integer.valueOf(cmd.getOptionValue('t'));
        else
            nthread = Runtime.getRuntime().availableProcessors();

        if (cmd.hasOption('w'))
            workDir = Paths.get(cmd.getOptionValue('w'));
        else
            workDir = Paths.get(System.getProperty("user.dir"));

        workDir = workDir.toAbsolutePath();

        switch (platform) {

        case PLATFORM_LOCAL:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            cre = new LocalCreActor(sandbox, workDir, nthread);
            break;

        case PLATFORM_HTCONDOR:

            if (!Files.exists(sandbox))
                Files.createDirectories(sandbox);

            if (cmd.hasOption('m')) { // MAX_TRANSFER SIZE
                String maxTransferSize = cmd.getOptionValue('m');
                try {
                    cre = new CondorCreActor(sandbox, maxTransferSize);
                } catch (Exception e) {
                    System.out.println("INVALID '-m' option value: " + maxTransferSize
                            + "\n\nCUNEIFORM - A Functional Workflow Language\nversion "
                            + BaseRepl.LABEL_VERSION + " build " + BaseRepl.LABEL_BUILD);
                    new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

                    return;
                }
            } else {
                cre = new CondorCreActor(sandbox);
            }

            break;

        default:
            throw new RuntimeException("Platform not recognized.");
        }

        executor.submit(cre);
        ticketSrc = new TicketSrcActor(cre);
        executor.submit(ticketSrc);
        executor.shutdown();

        switch (format) {

        case FORMAT_CF:

            if (cmd.hasOption("i"))
                repl = new InteractiveRepl(ticketSrc, statLog);
            else
                repl = new CmdlineRepl(ticketSrc, statLog);
            break;

        case FORMAT_DAX:
            repl = new DaxRepl(ticketSrc, statLog);
            break;

        default:
            throw new RuntimeException("Format not recognized.");
        }

        if (cmd.hasOption("i")) {

            // run in interactive mode
            BaseRepl.run(repl);

            return;
        }

        // run in quiet mode

        if (inputFileVector.length > 0)

            for (Path f : inputFileVector)
                repl.interpret(readFile(f));

        else
            repl.interpret(readStdIn());

        Thread.sleep(3 * Actor.DELAY);
        while (repl.isBusy())
            Thread.sleep(Actor.DELAY);

        if (cmd.hasOption("s")) {

            summary = new JsonSummary(ticketSrc.getRunId(), sandbox, repl.getAns());
            summaryPath = Paths.get(cmd.getOptionValue("s"));
            summaryPath = summaryPath.toAbsolutePath();
            try (BufferedWriter writer = Files.newBufferedWriter(summaryPath, Charset.forName("UTF-8"))) {

                writer.write(summary.toString());
            }

        }

    } finally {
        executor.shutdownNow();
    }

}

From source file:com.couchbase.roadrunner.RoadRunner.java

/**
 * Initialize the RoadRunner.// w  w w  .  ja v  a  2s . co m
 *
 * This method is responsible for parsing the passed in command line arguments
 * and also dispatch the bootstrapping of the actual workload runner.
 *
 * @param args Command line arguments to be passed in.
 */
public static void main(final String[] args) {
    CommandLine params = null;
    try {
        params = parseCommandLine(args);
    } catch (ParseException ex) {
        LOGGER.error("Exception while parsing command line!", ex);
        System.exit(-1);
    }

    if (params.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roadrunner", getCommandLineOptions());
        System.exit(0);
    }

    GlobalConfig config = GlobalConfig.fromCommandLine(params);
    WorkloadDispatcher dispatcher = new WorkloadDispatcher(config);

    LOGGER.info("Running with Config: " + config.toString());

    try {
        LOGGER.debug("Initializing ClientHandlers.");
        dispatcher.init();
    } catch (Exception ex) {
        LOGGER.error("Error while initializing the ClientHandlers: ", ex);
        System.exit(-1);
    }

    Stopwatch workloadStopwatch = new Stopwatch().start();
    try {
        LOGGER.info("Running Workload.");
        dispatcher.dispatchWorkload();
    } catch (Exception ex) {
        LOGGER.error("Error while running the Workload: ", ex);
        System.exit(-1);
    }
    workloadStopwatch.stop();

    LOGGER.debug("Finished Workload.");

    LOGGER.info("==== RESULTS ====");

    dispatcher.prepareMeasures();

    long totalOps = dispatcher.getTotalOps();
    long measuredOps = dispatcher.getMeasuredOps();

    LOGGER.info("Operations: measured " + measuredOps + "ops out of total " + totalOps + "ops.");

    Map<String, List<Stopwatch>> measures = dispatcher.getMeasures();
    for (Map.Entry<String, List<Stopwatch>> entry : measures.entrySet()) {
        Histogram h = new Histogram(60 * 60 * 1000, 5);
        for (Stopwatch watch : entry.getValue()) {
            h.recordValue(watch.elapsed(TimeUnit.MICROSECONDS));
        }

        LOGGER.info("Percentile (microseconds) for \"" + entry.getKey() + "\" Workload:");
        LOGGER.info("   50%:" + (Math.round(h.getValueAtPercentile(0.5) * 100) / 100) + "   75%:"
                + (Math.round(h.getValueAtPercentile(0.75) * 100) / 100) + "   95%:"
                + (Math.round(h.getValueAtPercentile(0.95) * 100) / 100) + "   99%:"
                + (Math.round(h.getValueAtPercentile(0.99) * 100) / 100));
    }

    LOGGER.info("Elapsed: " + workloadStopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");

    List<Stopwatch> elapsedThreads = dispatcher.getThreadElapsed();
    long shortestThread = 0;
    long longestThread = 0;
    for (Stopwatch threadWatch : elapsedThreads) {
        long threadMs = threadWatch.elapsed(TimeUnit.MILLISECONDS);
        if (longestThread == 0 || threadMs > longestThread) {
            longestThread = threadMs;
        }
        if (shortestThread == 0 || threadMs < shortestThread) {
            shortestThread = threadMs;
        }
    }

    LOGGER.info("Shortest Thread: " + shortestThread + "ms");
    LOGGER.info("Longest Thread: " + longestThread + "ms");

}

From source file:edu.usc.pgroup.floe.flake.FlakeService.java

/**
 * Entry point for the flake./* w  w  w  . j a  v a 2 s.c  om*/
 *
 * @param args commandline arguments. (TODO)
 */
public static void main(final String[] args) {

    Options options = buildOptions();

    CommandLineParser parser = new BasicParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FlakeService", options);
        return;
    }

    String pid = line.getOptionValue("pid");
    String id = line.getOptionValue("id");
    String cid = line.getOptionValue("cid");
    String appName = line.getOptionValue("appname");
    String token = line.getOptionValue("token");
    String jar = null;
    if (line.hasOption("jar")) {
        jar = line.getOptionValue("jar");
    }

    LOGGER.info("pid: {}, id:{}, cid:{}, app:{}, jar:{}", pid, id, cid, appName, jar);
    try {
        new FlakeService(pid, id, cid, appName, jar).start();
    } catch (Exception e) {
        LOGGER.error("Exception while creating flake: {}", e);
        return;
    }
}

From source file:com.github.enr.markdownj.extras.MarkdownApp.java

public static void main(String[] args) {
    MarkdownApp app = new MarkdownApp();
    app.log().debug("Markdown app starting with args: {}", Arrays.toString(args));
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("s", "source", true, "The source directory for markdown files");
    options.addOption("d", "destination", true, "The destination directory for html files");
    options.addOption("h", "header", true, "The path to the html header file");
    options.addOption("f", "footer", true, "The path to the html footer file");
    options.addOption("t", "code-template", true, "The template for code blocks");
    options.addOption("e", "extensions", true,
            "A comma separated list of file extensions to process. If setted, files with extension not in list won't be processed");
    options.addOption("c", "char-encoding", true, "The encoding to read and write files");
    HelpFormatter formatter = new HelpFormatter();
    String helpHeader = String.format("%s", MarkdownApp.class.getName());
    try {//from w  w w .j a v  a2  s  . c  o m
        CommandLine line = parser.parse(options, args);
        app.process(line);
    } catch (ParseException e) {
        app.log().warn(e.getMessage(), e);
        formatter.printHelp(helpHeader, options);
    }
}

From source file:com.mozilla.bagheera.consumer.KafkaHBaseConsumer.java

public static void main(String[] args) {
    OptionFactory optFactory = OptionFactory.getInstance();
    Options options = KafkaConsumer.getOptions();
    options.addOption(optFactory.create("tbl", "table", true, "HBase table name.").required());
    options.addOption(optFactory.create("f", "family", true, "Column family."));
    options.addOption(optFactory.create("q", "qualifier", true, "Column qualifier."));
    options.addOption(//  ww w .  ja  va 2  s. co m
            optFactory.create("b", "batchsize", true, "Batch size (number of messages per HBase flush)."));
    options.addOption(optFactory.create("pd", "prefixdate", false, "Prefix key with salted date."));

    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Create a sink for storing data
        SinkConfiguration sinkConfig = new SinkConfiguration();
        if (cmd.hasOption("numthreads")) {
            sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
        }
        if (cmd.hasOption("batchsize")) {
            sinkConfig.setInt("hbasesink.hbase.batchsize", Integer.parseInt(cmd.getOptionValue("batchsize")));
        }
        sinkConfig.setString("hbasesink.hbase.tablename", cmd.getOptionValue("table"));
        sinkConfig.setString("hbasesink.hbase.column.family", cmd.getOptionValue("family", "data"));
        sinkConfig.setString("hbasesink.hbase.column.qualifier", cmd.getOptionValue("qualifier", "json"));
        sinkConfig.setBoolean("hbasesink.hbase.rowkey.prefixdate", cmd.hasOption("prefixdate"));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(HBaseSink.class, sinkConfig);
        sh.addLast(sinkFactory);

        // Set the sink factory for consumer storage
        consumer.setSinkFactory(sinkFactory);

        prepareHealthChecks();

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(KafkaHBaseConsumer.class.getName(), options);
    }
}

From source file:cross.io.PropertyFileGenerator.java

/**
 *
 * @param args/*from   ww w . j  a va 2s.co m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("f", true, "base directory for output of files");
    Option provOptions = new Option("p", true,
            "Comma separated list of provider classes to create Properties for");
    provOptions.setRequired(true);
    provOptions.setValueSeparator(',');
    options.addOption(provOptions);
    CommandLineParser parser = new PosixParser();
    HelpFormatter hf = new HelpFormatter();
    try {
        File basedir = null;
        List<String> providers = Collections.emptyList();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("f")) {
            basedir = new File(cmd.getOptionValue("f"));
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        if (cmd.hasOption("p")) {
            String[] str = cmd.getOptionValues("p");
            providers = Arrays.asList(str);
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        for (String provider : providers) {
            createProperties(provider, basedir);
        }
    } catch (ParseException ex) {
        Logger.getLogger(PropertyFileGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.genentech.chemistry.tool.SDFFilter.java

public static void main(String args[]) {
    String usage = "java sdfFilter [options]\n" + "Filters out molecules that contain the following:\n"
            + "1. More than maxHeavy atoms (default is 100)\n" + "2. Have more than one component\n"
            + "3. Does not have any atoms\n" + "4. Have invalid atoms, like R, * etc ...\n"
            + "5. Have atomic number greater than 53 (Iodine)";

    // create Options object
    Options options = new Options();
    // add  options
    options.addOption("h", false, "");
    options.addOption("in", true, "inFile in OE formats: Ex: a.sdf or .sdf");
    options.addOption("out", true, "outFile in OE formats. Ex: a.sdf or .sdf");
    options.addOption("filtered", true, "Optional: filteredFile in OE formats. Ex: a.sdf or .sdf");
    options.addOption("maxHeavy", true, "Number of heavy atom cutoff. Default is 100");
    CommandLineParser parser = new PosixParser();

    try {/* w w w. jav a2s .  c  o m*/
        CommandLine cmd = parser.parse(options, args);
        String inFile = cmd.getOptionValue("in");
        if (inFile == null) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        String outFile = cmd.getOptionValue("out");
        if (outFile == null) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        String filteredFile = null;
        if (cmd.hasOption("filtered")) {
            filteredFile = cmd.getOptionValue("filtered");
        }

        int maxHeavy = 100;
        if (cmd.hasOption("maxHeavy")) {
            maxHeavy = Integer.parseInt(cmd.getOptionValue("maxHeavy"));
            maxAtoms = maxHeavy;
        }

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        oemolistream ifs = new oemolistream(inFile);
        oemolostream ofs = new oemolostream(outFile);
        oemolostream ffs = null;
        if (filteredFile != null) {
            ffs = new oemolostream(filteredFile);
        }
        /*it appears that we don't have license to molprop toolkit
        oeisstream iss = new oeisstream();
        OEFilter filter = new OEFilter(iss);
        filter.SetTypeCheck(true);
        oechem.OEThrow.SetLevel(OEErrorLevel.Warning);
        */

        OEGraphMol mol = new OEGraphMol();

        while (oechem.OEReadMolecule(ifs, mol)) {
            //            if (passFilters(mol, filter)) { //needs license to molprop toolkit
            if (passFilters(mol)) {
                oechem.OEWriteMolecule(ofs, mol);
            } else {
                if (ffs != null) {
                    oechem.OEWriteMolecule(ffs, mol);
                }
            }
        }

    } catch (ParseException e) { // TODO print explaination
        throw new Error(e);
    }
}