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

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

Introduction

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

Prototype

public void setOptionComparator(Comparator comparator) 

Source Link

Document

Set the comparator used to sort the options when they output in help text Passing in a null parameter will set the ordering to the default mode

Usage

From source file:com.github.trohovsky.jira.analyzer.Main.java

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

    final Options options = new Options();
    options.addOption("u", true, "username");
    options.addOption("p", true, "password (optional, if not provided, the password is prompted)");
    options.addOption("h", false, "show this help");
    options.addOption("s", true,
            "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or"
                    + " 'per_month'");
    options.addOption("d", true, "CSV delimiter");

    // parsing of the command line arguments
    final CommandLineParser parser = new DefaultParser();
    CommandLine cmdLine = null;//from w  w w.  ja v  a  2s . c  o  m
    try {
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
            return;
        }
        if (cmdLine.getArgs().length != 3) {
            throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE"
                    + " PATH_TO_PARAMETER_FILE");
        }
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
        return;
    }
    final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d')
            : CSV_DELIMITER);

    final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]);
    final String jqlQueryTemplate = cmdLine.getArgs()[1];
    final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter);
    final String username = cmdLine.getOptionValue("u");
    String password = cmdLine.getOptionValue("p");
    final String strategy = cmdLine.getOptionValue("s");

    try {
        // initialization of the REST client
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        if (username != null) {
            if (password == null) {
                final Console console = System.console();
                final char[] passwordCharacters = console.readPassword("Password: ");
                password = new String(passwordCharacters);
            }
            restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password);
        } else {
            restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler());
        }
        final SearchRestClient searchRestClient = restClient.getSearchClient();

        // choosing of an analyzer strategy
        AnalyzerStrategy analyzer = null;
        if (strategy != null) {
            switch (strategy) {
            case "issues_total":
                analyzer = new IssuesTotalStrategy(searchRestClient);
                break;
            case "issues_per_month":
                analyzer = new IssuesPerMonthStrategy(searchRestClient);
                break;
            default:
                System.err.println("The strategy does not exist");
                return;
            }
        } else {
            analyzer = new IssuesTotalStrategy(searchRestClient);
        }

        // analyzing
        for (List<String> queryParameters : queryParametersData) {
            analyzer.analyze(jqlQueryTemplate, queryParameters);
        }
    } finally {
        // destroy the REST client, otherwise it stucks
        restClient.close();
    }
}

From source file:com.github.trohovsky.just.Main.java

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

    // parsing of command line
    final CommandLineParser parser = new GnuParser();

    final Options options = new Options();
    options.addOption("ai", true, "prefixes of classes from artifacts that will be included");
    options.addOption("ae", true, "prefixes of classes from artifacts that will be excluded");
    options.addOption("di", true, "prefixes of classes from dependencies that will be included");
    options.addOption("de", true, "prefixes of classes from dependencies that will be excluded");
    options.addOption("f", "flatten", false, "flatten report, display only used classes");
    options.addOption("p", "packages", false, "display package names instead of class names");
    options.addOption("u", "unused", false, "display unused classes from dependencies");
    options.addOption("h", "help", false, "print this help");

    CommandLine cmdLine = null;/*from   ww w.  j  a  va2  s  .com*/
    try {
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h')) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
            return;
        }
        if (cmdLine.getArgs().length == 0) {
            throw new ParseException("Missing ARTIFACT and/or DEPENDENCY.");
        } else if (cmdLine.getArgs().length > 2) {
            throw new ParseException(
                    "More that two arquments found, multiple ARTIFACTs DEPENDENCies should be separated by ','"
                            + " without whitespaces.");
        }

    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
        return;
    }

    // obtaining of values
    final String[] artifactPaths = cmdLine.getArgs()[0].split(",");
    final String[] dependencyPaths = cmdLine.getArgs().length == 2 ? cmdLine.getArgs()[1].split(",") : null;
    final String[] artifactIncludes = splitValues(cmdLine.getOptionValue("ai"));
    final String[] artifactExcludes = splitValues(cmdLine.getOptionValue("ae"));
    final String[] dependencyIncludes = splitValues(cmdLine.getOptionValue("di"));
    final String[] dependencyExcludes = splitValues(cmdLine.getOptionValue("de"));

    // validation of values
    if (dependencyPaths == null) {
        if (dependencyIncludes != null) {
            System.err.println("At least one dependency has to be specified to use option -di");
            return;
        }
        if (dependencyExcludes != null) {
            System.err.println("At least one dependency has to be specified to use option -de");
            return;
        }
        if (cmdLine.hasOption('u')) {
            System.err.println("At least one dependency has to be specified to use option -u");
            return;
        }
    }

    // execution
    Set<String> externalClasses = null;
    if (dependencyPaths != null) {
        externalClasses = Reader.from(dependencyPaths).includes(dependencyIncludes).excludes(dependencyExcludes)
                .listClasses();
    }

    if (cmdLine.hasOption('f') || cmdLine.hasOption('u')) {
        Set<String> dependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readDependencies();
        if (externalClasses != null) {
            dependencies = DependencyUtils.intersection(dependencies, externalClasses);
            if (cmdLine.hasOption('u')) {
                dependencies = DependencyUtils.subtract(externalClasses, dependencies);
            }
        }
        if (cmdLine.hasOption('p')) {
            dependencies = DependencyUtils.toPackageNames(dependencies);
        }
        Reporter.report(dependencies);
    } else {
        Map<String, Set<String>> classesWithDependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readClassesWithDependencies();
        if (externalClasses != null) {
            classesWithDependencies = DependencyUtils.intersection(classesWithDependencies, externalClasses);
        }
        if (cmdLine.hasOption('p')) {
            classesWithDependencies = DependencyUtils.toPackageNames(classesWithDependencies);
        }
        Reporter.report(classesWithDependencies);
    }
}

From source file:br.ufpb.dicomflow.integrationAPI.tools.SendService.java

public static void main(final String args[]) {

    try {/*from   w  ww . j  a  v  a  2s  .  co  m*/
        CommandLine cl = parseComandLine(args);

        CLIUtils.configureLog(cl);

        CLIUtils.configureProperties(properties, cl, CLIUtils.SEND_PROPERTIES);

        CLIUtils.configureEncryptProperties(signer, privateKey, cipher, cl);

        configureService(service, cl);

        sendService(cl);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new Comparator<Option>() {

            @Override
            public int compare(Option o1, Option o2) {
                return 0;
            }
        });

        formatter.printHelp(rb.getString("send-usage"), rb.getString("send-description"), opts,
                rb.getString("send-example"), true);
    } catch (PropertyNotFoundException e) {
        Logger.ef(e, rb.getString("load-property-exception"));
    } catch (JAXBException e) {
        Logger.ef(e, rb.getString("load-service-exception"));
    } catch (ClassNotFoundException e) {
        Logger.ef(e, rb.getString("load-service-exception"));
    } catch (UnrecoverableKeyException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (KeyStoreException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (NoSuchAlgorithmException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (CertificateException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (FileNotFoundException e) {
        Logger.ef(e, rb.getString("load-file-exception"));
    } catch (IOException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    }

}

From source file:jfractus.app.Main.java

public static void main(String[] args) {
    createCommandLineOptions();/*from ww  w .  ja  v  a  2s  .c  om*/
    GnuParser parser = new GnuParser();
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setOptionComparator(null);

    CommandLine cmdLine = null;

    try {
        cmdLine = parser.parse(cliOptions, args);
    } catch (ParseException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    }

    String functionsLibPaths = cmdLine.getOptionValue("libraries");
    int threadsNum = FractusPreferencesFactory.prefs.getThreadsNumber();
    Dimension outSize = new Dimension(FractusPreferencesFactory.prefs.getDefaultImageWidth(),
            FractusPreferencesFactory.prefs.getDefaultImageHeight());
    AntialiasConfig aaConfig = FractusPreferencesFactory.prefs.getDefaultAntialiasConfig();
    boolean printProgress = cmdLine.hasOption("progress");

    try {
        String threadsNumString = cmdLine.getOptionValue("threads");
        String imageSizeString = cmdLine.getOptionValue("image-size");
        String aaMethodString = cmdLine.getOptionValue("antialias");
        String samplingSizeString = cmdLine.getOptionValue("sampling-size");

        if (functionsLibPaths != null)
            FunctionsLoaderFactory.loader.setClassPathsFromString(functionsLibPaths);

        if (aaMethodString != null) {
            if (aaMethodString.equals("none"))
                aaConfig.setMethod(AntialiasConfig.Method.NONE);
            else if (aaMethodString.equals("normal"))
                aaConfig.setMethod(AntialiasConfig.Method.NORMAL);
            else
                throw new BadValueOfArgumentException("Bad value of argument");
        }
        if (threadsNumString != null)
            threadsNum = Integer.valueOf(threadsNumString).intValue();
        if (imageSizeString != null)
            parseSize(imageSizeString, outSize);
        if (samplingSizeString != null) {
            Dimension samplingSize = new Dimension();
            parseSize(samplingSizeString, samplingSize);
            aaConfig.setSamplingSize(samplingSize.width, samplingSize.height);
        }

        if (cmdLine.hasOption("save-prefs")) {
            FunctionsLoaderFactory.loader.putClassPathsToPrefs();
            FractusPreferencesFactory.prefs.setThreadsNumber(threadsNum);
            FractusPreferencesFactory.prefs.setDefaultImageSize(outSize.width, outSize.height);
            FractusPreferencesFactory.prefs.setDefaultAntialiasConfig(aaConfig);
        }
    } catch (ArgumentParseException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    } catch (NumberFormatException e) {
        System.err.println(Resources.getString("CLIParseError"));
        return;
    } catch (BadValueOfArgumentException e) {
        System.err.println(Resources.getString("CLIBadValueError"));
        return;
    }

    if (cmdLine.hasOption('h') || (cmdLine.hasOption('n') && cmdLine.getArgs().length < 2)) {
        helpFormatter.printHelp(Resources.getString("CLISyntax"), cliOptions);
        return;
    }

    if (!cmdLine.hasOption('n')) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    } else {
        String[] cmdArgs = cmdLine.getArgs();
        try {
            FractalDocument fractal = new FractalDocument();
            fractal.readFromFile(new File(cmdArgs[0]));
            FractalRenderer renderer = new FractalRenderer(outSize.width, outSize.height, aaConfig, fractal);
            FractalImageWriter imageWriter = new FractalImageWriter(renderer, cmdArgs[1]);

            renderer.setThreadNumber(threadsNum);
            renderer.prepareFractal();
            if (printProgress) {
                renderer.addRenderProgressListener(new CMDLineProgressEventListener());
                imageWriter.addImageWriterProgressListener(new CMDLineImageWriteProgressListener());
            }

            imageWriter.write();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:br.ufpb.dicomflow.integrationAPI.tools.ReadService.java

public static void main(final String args[]) {

    try {/*w ww. j  a  v  a2 s  .  com*/
        CommandLine cl = parseComandLine(args);

        CLIUtils.configureLog(cl);

        CLIUtils.configureProperties(properties, cl, CLIUtils.READ_PROPERTIES);

        CLIUtils.configureEncryptProperties(cipher, privateKey, signer, cl);

        configureFilterProperties(filter, cl);

        readService(cl);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new Comparator<Option>() {

            @Override
            public int compare(Option o1, Option o2) {
                return 0;
            }
        });

        formatter.printHelp(rb.getString("read-usage"), rb.getString("read-description"), opts,
                rb.getString("read-example"), true);
    } catch (PropertyNotFoundException e) {
        Logger.ef(e, rb.getString("load-property-exception"));
    } catch (UnrecoverableKeyException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (KeyStoreException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (NoSuchAlgorithmException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (CertificateException e) {
        Logger.ef(e, rb.getString("load-encrypt-exception"));
    } catch (FileNotFoundException e) {
        Logger.ef(e, rb.getString("load-file-exception"));
    } catch (IOException e) {
        Logger.ef(e, rb.getString("load-file-exception"));
    } catch (NumberFormatException e) {
        Logger.ef(e, rb.getString("load-filter-exception"));
    } catch (java.text.ParseException e) {
        Logger.ef(e, rb.getString("load-filter-exception"));
    } catch (JAXBException e) {
        Logger.ef(e, rb.getString("load-service-exception"));
    }

}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*from  ww  w . j a v  a  2s.  co  m*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java

public static void main(String[] args) throws GenerationException, IOException {

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }/*from  w  ww .  j a v  a2 s  . co m*/

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);

        LOGGER.info("Start loading the package");
        Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);

        Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        metamodelResource.getContents().add(_package);
        LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed);
        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (ClassNotFoundException t) {
        System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(stringWriter.toString());
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java

public static void main(String[] args) throws GenerationException, IOException {

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//from  w w  w. j ava 2s. co m

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        //         String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);
        //         
        //         LOGGER.info("Start loading the package");
        //         Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        //         EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);
        //         
        //         Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        //          metamodelResource.getContents().add(_package);
        //          LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        ISpecimenConfiguration config = new DagMetamodelConfig(range, seed);
        IGenerator generator = new DagGenerator(config, config.getSeed());

        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(DEGREE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        //         for (Resource rsc : resourceSet.getResources()) {
        //            if (rsc.getContents().get(0) instanceof DAG) {
        //               
        //            }
        //               
        //         }

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:lineage.LineageEngine.java

public static void main(String[] args) {
    Options options = new Options();
    // Commands/* www .j  av a2 s. co  m*/
    options.addOption("build", false, "Construct the sample lineage trees");

    // Input/Output/Display
    options.addOption("i", true, "Input file path [required]");
    options.addOption("o", true, "Output file path (default: input file with suffix .trees.txt)");
    options.addOption("cp", false, "Input data represents cell prevalaence (CP) values");
    options.addOption("sampleProfile", false,
            "Input file contains the SSNV sample presence-absence profile (this will disable the default SSNV calling step)");
    options.addOption("n", "normal", true,
            "Normal sample column id in the list of samples, 0-based (e.g 0 is the first column) [required without -sampleProfile]");
    options.addOption("clustersFile", true, "SSNV clusters file path");
    options.addOption("s", "save", true, "Maximum number of output trees to save (default: 1)");
    options.addOption("showNetwork", "net", false, "Display the constraint network");
    options.addOption("showTree", "tree", true, "Number of top-ranking trees to display (default: 0)");

    // SSNV filtering / calling
    options.addOption("maxVAFAbsent", "absent", true,
            "Maximum VAF to robustly consider an SSNV as absent from a sample [required without -sampleProfile]");
    options.addOption("minVAFPresent", "present", true,
            "Minimum VAF to robustly consider an SSNV as present in a sample [required without -sampleProfile]");
    options.addOption("maxVAFValid", true, "Maximum allowed VAF in a sample (default: 0.6)");
    options.addOption("minProfileSupport", true,
            "Minimum number of robust SSNVs required for a group presence-absence profile to be labeled robust (default: 2)");

    // Network Construction / Tree Search
    options.addOption("minClusterSize", true,
            "Minimum size a cluster must have to be a considered a node in the network (default: 2)");
    options.addOption("minPrivateClusterSize", true,
            "Minimum size a private mutation cluster must have to be a considered a node in the network (default: 1)");
    options.addOption("minRobustNodeSupport", true,
            "Minimum number of robust SSNVs required for a node to be labeled robust during tree search: non-robust nodes can be removed from the network when no valid lineage trees are found (default: 2)");
    options.addOption("maxClusterDist", true,
            "Maximum mean VAF difference up to which two clusters can be collapsed (default: 0.2)");
    options.addOption("c", "completeNetwork", false,
            "Add all possible edges to the constraint network (default: private nodes are connected only to closest level parents; only nodes with no other parents are descendants of root)");
    options.addOption("e", true, "VAF error margin (default: 0.1)");
    options.addOption("nTreeQPCheck", true,
            "Number of top-ranking trees on which the QP consistency check is run, we have not seen this check fail in practice (default: 0, for best performance)");

    options.addOption("v", "verbose", false, "Verbose mode");
    options.addOption("h", "help", false, "Print usage");

    // display order
    ArrayList<Option> optionsList = new ArrayList<Option>();
    optionsList.add(options.getOption("build"));

    optionsList.add(options.getOption("i"));
    optionsList.add(options.getOption("o"));
    optionsList.add(options.getOption("cp"));
    optionsList.add(options.getOption("sampleProfile"));
    optionsList.add(options.getOption("n"));
    optionsList.add(options.getOption("clustersFile"));
    optionsList.add(options.getOption("s"));
    optionsList.add(options.getOption("net"));
    optionsList.add(options.getOption("tree"));
    optionsList.add(options.getOption("maxVAFAbsent"));
    optionsList.add(options.getOption("minVAFPresent"));
    optionsList.add(options.getOption("maxVAFValid"));
    optionsList.add(options.getOption("minProfileSupport"));
    optionsList.add(options.getOption("minClusterSize"));
    optionsList.add(options.getOption("minPrivateClusterSize"));
    optionsList.add(options.getOption("minRobustNodeSupport"));
    optionsList.add(options.getOption("maxClusterDist"));
    optionsList.add(options.getOption("c"));
    optionsList.add(options.getOption("e"));
    optionsList.add(options.getOption("nTreeQPCheck"));
    optionsList.add(options.getOption("v"));
    optionsList.add(options.getOption("h"));

    CommandLineParser parser = new BasicParser();
    CommandLine cmdLine = null;
    HelpFormatter hf = new HelpFormatter();
    hf.setOptionComparator(new OptionComarator<Option>(optionsList));
    try {
        cmdLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        hf.printHelp("lichee", options);
        System.exit(-1);
    }

    // Set-up input args
    Args params = new Args();
    if (cmdLine.hasOption("i")) {
        params.inputFileName = cmdLine.getOptionValue("i");
    } else {
        System.out.println("Required parameter: input file path [-i]");
        hf.printHelp("lichee", options);
        System.exit(-1);
    }
    if (cmdLine.hasOption("o")) {
        params.outputFileName = cmdLine.getOptionValue("o");
    } else {
        params.outputFileName = params.inputFileName + TREES_TXT_FILE_EXTENSION;
    }
    if (cmdLine.hasOption("clustersFile")) {
        params.clustersFileName = cmdLine.getOptionValue("clustersFile");
    }
    if (cmdLine.hasOption("sampleProfile")) {
        Parameters.INPUT_FORMAT = Format.SNV_WITH_PROFILE;
    }

    if (cmdLine.hasOption("n")) {
        params.normalSampleId = Integer.parseInt(cmdLine.getOptionValue("n"));
    } else if (!cmdLine.hasOption("sampleProfile")) {
        System.out.println("Required parameter: normal sample id [-n]");
        hf.printHelp("lichee", options);
        System.exit(-1);
    }
    if (cmdLine.hasOption("showTree")) {
        params.numShow = Integer.parseInt(cmdLine.getOptionValue("showTree"));
    }
    if (cmdLine.hasOption("showNetwork")) {
        params.showNetwork = true;
    }
    if (cmdLine.hasOption("s")) {
        params.numSave = Integer.parseInt(cmdLine.getOptionValue("s"));
    }

    if (cmdLine.hasOption("maxVAFAbsent")) {
        Parameters.MAX_VAF_ABSENT = Double.parseDouble(cmdLine.getOptionValue("maxVAFAbsent"));
    } else if (!cmdLine.hasOption("sampleProfile")) {
        System.out.println("Required parameter: -maxVAFAbsent");
        hf.printHelp("lichee", options);
        System.exit(-1);
    }
    if (cmdLine.hasOption("minVAFPresent")) {
        Parameters.MIN_VAF_PRESENT = Double.parseDouble(cmdLine.getOptionValue("minVAFPresent"));
    } else if (!cmdLine.hasOption("sampleProfile")) {
        System.out.println("Required parameter: -minVAFPresent");
        hf.printHelp("lichee", options);
        System.exit(-1);
    }
    if (cmdLine.hasOption("maxVAFValid")) {
        Parameters.MAX_ALLOWED_VAF = Double.parseDouble(cmdLine.getOptionValue("maxVAFValid"));
    }
    if (cmdLine.hasOption("minProfileSupport")) {
        Parameters.MIN_GROUP_PROFILE_SUPPORT = Integer.parseInt(cmdLine.getOptionValue("minProfileSupport"));
    }
    if (cmdLine.hasOption("minClusterSize")) {
        Parameters.MIN_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minClusterSize"));
    }
    if (cmdLine.hasOption("minPrivateClusterSize")) {
        Parameters.MIN_PRIVATE_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minPrivateClusterSize"));
    }
    if (cmdLine.hasOption("minRobustNodeSupport")) {
        Parameters.MIN_ROBUST_CLUSTER_SUPPORT = Integer
                .parseInt(cmdLine.getOptionValue("minRobustNodeSupport"));
    }
    if (cmdLine.hasOption("maxClusterDist")) {
        Parameters.MAX_COLLAPSE_CLUSTER_DIFF = Double.parseDouble(cmdLine.getOptionValue("maxClusterDist"));
    }
    if (cmdLine.hasOption("c")) {
        Parameters.ALL_EDGES = true;
    }
    if (cmdLine.hasOption("cp")) {
        Parameters.CP = true;
        Parameters.VAF_MAX = 1.0;
        Parameters.MAX_ALLOWED_VAF = 1.0;
    }
    if (cmdLine.hasOption("e")) {
        Parameters.VAF_ERROR_MARGIN = Double.parseDouble(cmdLine.getOptionValue("e"));
    }
    if (cmdLine.hasOption("nTreeQPCheck")) {
        Parameters.NUM_TREES_FOR_CONSISTENCY_CHECK = Integer.parseInt(cmdLine.getOptionValue("nTreeQPCheck"));
    }
    if (cmdLine.hasOption("h")) {
        new HelpFormatter().printHelp(" ", options);
    }
    // logger
    ConsoleHandler h = new ConsoleHandler();
    h.setFormatter(new LogFormatter());
    h.setLevel(Level.INFO);
    logger.setLevel(Level.INFO);
    if (cmdLine.hasOption("v")) {
        h.setLevel(Level.FINEST);
        logger.setLevel(Level.FINEST);
    }
    logger.addHandler(h);
    logger.setUseParentHandlers(false);

    if (cmdLine.hasOption("build")) {
        buildLineage(params);

    } else {
        new HelpFormatter().printHelp("lichee", options);
        System.exit(-1);
    }
}

From source file:fr.inria.atlanmod.instantiator.SpecimenGenerator.java

public static void main(String[] args) throws GenerationException, IOException {

    Options options = new Options();

    configureOptions(options);/*from  w ww  .  j av  a 2 s  .  co m*/

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String metamodel = commandLine.getOptionValue(METAMODEL);
        DefaultModelGenerator modelGen = new DefaultModelGenerator(URI.createFileURI(metamodel));

        if (commandLine.hasOption(ADDITIONAL_METAMODEL)) {
            for (String additionalMetamodel : commandLine.getOptionValues(ADDITIONAL_METAMODEL)) {
                URI additionalMetamodelUri = URI.createFileURI(additionalMetamodel);
                Resource resource = new XMIResourceImpl(additionalMetamodelUri);
                resource.load(Collections.emptyMap());
                registerPackages(resource);
            }
        }

        if (commandLine.hasOption(OUTPUT_DIR)) {
            String outDir = commandLine.getOptionValue(OUTPUT_DIR);
            modelGen.setSamplesPath(Paths.get(outDir));
        } else {
            modelGen.setSamplesPath(Paths.get("."));
        }
        if (commandLine.hasOption(N_MODELS)) {
            int models = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
            modelGen.setSetSize(new int[] { models });
        } else {
            modelGen.setSetSize(new int[] { 1 });
        }
        if (commandLine.hasOption(SIZE)) {
            long size = ((Number) commandLine.getParsedOptionValue(SIZE)).longValue();
            modelGen.setModelsSize(new long[] { size });
        } else {
            modelGen.setModelsSize(new long[] { 1000 });
        }
        if (commandLine.hasOption(SEED)) {
            long seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
            modelGen.setSeed(seed);
        } else {
            modelGen.setSeed(System.currentTimeMillis());
        }
        modelGen.runGeneration();
    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(TerminalFactory.get().getWidth(), 80));
        } catch (Throwable t) {
            // Nothing to do...
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    }
}