Example usage for org.apache.commons.cli Options getOption

List of usage examples for org.apache.commons.cli Options getOption

Introduction

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

Prototype

public Option getOption(String opt) 

Source Link

Document

Retrieve the Option matching the long or short name specified.

Usage

From source file:boa.evaluator.BoaEvaluator.java

public static void main(final String[] args) {
    final Options options = new Options();

    options.addOption("i", "input", true, "input Boa source file (*.boa)");
    options.addOption("d", "data", true, "path to local data directory");
    options.addOption("o", "output", true, "output directory");

    options.getOption("i").setRequired(true);
    options.getOption("d").setRequired(true);

    try {//from w  w  w.  j  a v  a 2 s  .c  om
        if (args.length == 0) {
            printHelp(options, null);
            return;
        } else {
            final CommandLine cl = new PosixParser().parse(options, args);

            if (cl.hasOption('i') && cl.hasOption('d')) {
                final BoaEvaluator evaluator;
                try {
                    if (cl.hasOption('o')) {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'),
                                cl.getOptionValue('o'));
                    } else {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'));
                    }
                } catch (final IOException e) {
                    System.err.print(e);
                    return;
                }

                if (!evaluator.compile()) {
                    System.err.println("Compilation Failed");
                    return;
                }

                final long start = System.currentTimeMillis();
                evaluator.evaluate();
                final long end = System.currentTimeMillis();

                System.out.println("Total Time Taken: " + (end - start));
                System.out.println(evaluator.getResults());
            } else {
                printHelp(options, "missing required options: -i <arg> and -d <arg>");
                return;
            }
        }
    } catch (final org.apache.commons.cli.ParseException e) {
        printHelp(options, e.getMessage());
    }
}

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;//from  w w  w .j a va2s.  c o m
    try {
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

From source file:com.sr.eb.compiler.Main.java

public static void main(String[] args) throws Throwable {
    try {//from   w  ww .  java2s.  co m
        Options options = new Options();

        options.addOption("v", "verbose", false, "Enables verbose compiler output.");
        options.addOption("ee", "easterEgg", false, "Enables compiler easter eggs, DO NOT USE!");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.getArgs().length > 0) {
            int start = -1;
            while (true) {
                start++;
                if (options.getOption(cmd.getArgs()[start]) == null)
                    break;
            }

            String[] sourceFiles = Arrays.copyOfRange(cmd.getArgs(), start, cmd.getArgs().length);

            // TODO
        } else {
            System.out.println("Expected source files, got none!");
            System.out.println("Usage: ebc [options] <source files>");
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    /* ----- Testing ----- */
    Lexer lexer = Lexer.newInstance();
    Parser parser = Parser.newInstance();

    try (InputStream in = new FileInputStream("test.eb")) {
        lexer.reset(Utils.readAll(in));
    }

    List<Token> tokens = lexer.tokenize();
    parser.reset(tokens);
    SyntaxTree t = parser.parse();

    ASTPrettyPrinter.print(t);
}

From source file:com.spotify.cassandra.opstools.CountTombstones.java

/**
 * Counts the number of tombstones, per row, in a given SSTable
 *
 * Assumes RandomPartitioner, standard columns and UTF8 encoded row keys
 *
 * Does not require a cassandra.yaml file or system tables.
 *
 * @param args command lines arguments//  ww  w.j  a  va  2 s.com
 *
 * @throws java.io.IOException on failure to open/read/write files or output streams
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s [-l] <sstable> [<sstable> ...]%n", CountTombstones.class.getName());

    final Options options = new Options();
    options.addOption("l", "legend", false, "Include column name explanation");
    options.addOption("p", "partitioner", true, "The partitioner used by database");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.getArgs().length < 1) {
        System.err.println("You must supply at least one sstable");
        System.err.println(usage);
        System.exit(1);
    }

    // Fake DatabaseDescriptor settings so we don't have to load cassandra.yaml etc
    Config.setClientMode(true);
    String partitionerName = String.format("org.apache.cassandra.dht.%s",
            options.hasOption("p") ? options.getOption("p") : "RandomPartitioner");
    try {
        Class<?> clazz = Class.forName(partitionerName);
        IPartitioner partitioner = (IPartitioner) clazz.newInstance();
        DatabaseDescriptor.setPartitioner(partitioner);
    } catch (Exception e) {
        throw new RuntimeException("Can't instantiate partitioner " + partitionerName);
    }

    PrintStream out = System.out;

    for (String arg : cmd.getArgs()) {
        String ssTableFileName = new File(arg).getAbsolutePath();

        Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);

        run(descriptor, cmd, out);
    }

    System.exit(0);
}

From source file:eu.clarin.cmdi.vlo.importer.MetadataImporter.java

/**
 * @param args//from  ww  w  . j  a  va2 s .  com
 * @throws MalformedURLException
 * @throws IOException
 */
public static void main(String[] args) throws MalformedURLException, IOException {

    // path to the configuration file
    String configFile = null;

    // use the Apache cli framework for getting command line parameters
    Options options = new Options();

    // Data root list passed from command line with -l option
    String cldrList = null;

    /**
     * Add a "c" option, the option indicating the specification of an XML
     * configuration file
     *
     * "l" option - to specify which data roots (from config file) to import
     * imports all by default
     */
    options.addOption("c", true, "-c <file> : use parameters specified in <file>");
    options.addOption("l", true,
            "-l <dataroot> [ ' ' <dataroot> ]* :  space separated list of dataroots to be processed.\n"
                    + "If dataroot is not specified in config file it will be ignored.");
    options.getOption("l").setOptionalArg(true);

    CommandLineParser parser = new PosixParser();

    try {
        // parse the command line arguments
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("c")) {

            // the "c" option was specified, now get its value
            configFile = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("l")) {
            cldrList = cmd.getOptionValue("l");
        }

    } catch (org.apache.commons.cli.ParseException ex) {

        /**
         * Caught an exception caused by command line parsing. Try to get
         * the name of the configuration file by querying the system
         * property.
         */
        String message = "Command line parsing failed. " + ex.getMessage();
        LOG.error(message);
        System.err.println(message);
    }

    if (configFile == null) {

        String message;

        message = "Could not get config file name via the command line, trying the system properties.";
        LOG.info(message);

        String key;

        key = "configFile";
        configFile = System.getProperty(key);
    }

    if (configFile == null) {

        String message;

        message = "Could not get filename as system property either - stopping.";
        LOG.error(message);
    } else {
        // read the configuration from the externally supplied file
        final URL configUrl;
        if (configFile.startsWith("file:")) {
            configUrl = new URL(configFile);
        } else {
            configUrl = new File(configFile).toURI().toURL();
        }
        System.out.println("Reading configuration from " + configUrl.toString());
        LOG.info("Reading configuration from " + configUrl.toString());
        final XmlVloConfigFactory configFactory = new XmlVloConfigFactory(configUrl);
        MetadataImporter.config = configFactory.newConfig();
        MetadataImporter.languageCodeUtils = new LanguageCodeUtils(MetadataImporter.config);

        // optionally, modify the configuration here
        // create and start the importer
        MetadataImporter importer = new MetadataImporter(cldrList);
        importer.startImport();

        // finished importing
        if (MetadataImporter.config.printMapping()) {
            File file = new File("xsdMapping.txt");
            FacetMappingFactory.printMapping(file);
            LOG.info("Printed facetMapping in " + file);
        }
    }
}

From source file:Cresendo.java

public static void main(String[] args) {
    String cfgFileReceiver = null; // Path to config file for eif receiver agent
    String cfgFileEngine = null; // Path to config file for xml event engine
    Options opts = null; // Command line options
    HelpFormatter hf = null; // Command line help formatter

    // Setup the message record which will contain text written to the log file
    ///*  w ww  .  ja  v a  2  s  . com*/
    // The message logger object is created when the "-l" is processed
    // as this object need to be associated with a log file
    //
    LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", "");

    // Get the directory separator (defaults to "/")
    //
    dirSep = System.getProperty("file.separator", "/");

    // Initialise the structure containing the event handler objects
    //
    Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10);

    // Process the command line arguments
    //
    try {
        opts = new Options();
        hf = new HelpFormatter();

        opts.addOption("h", "help", false, "Command line arguments help");
        opts.addOption("i", "instance name", true, "Name of cresendo instance");
        opts.addOption("l", "log dir", true, "Path to log file directory");
        opts.addOption("c", "config dir", true, "Path to configuarion file directory");

        opts.getOption("l").setRequired(true);
        opts.getOption("c").setRequired(true);

        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opts, args);

        // Print out some help and exit
        //
        if (cl.hasOption('h')) {
            hf.printHelp("Options", opts);
            System.exit(0);
        }

        // Set the instance name
        //
        if (cl.hasOption('i')) {
            instanceName = cl.getOptionValue('i'); // Set to something other than "default"
        }

        // Setup the message and trace logging objects for the EventEngine
        //
        if (cl.hasOption('l')) {
            // Setup the the paths to the message, trace and status log files
            //
            logDir = cl.getOptionValue("l");

            logPath = logDir + dirSep + instanceName + "-engine.log";
            tracePath = logDir + dirSep + instanceName + "-engine.trace";
            statusPath = logDir + dirSep + instanceName + "-engine.status";
        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'l' is a required option", opts);
            System.exit(1);
        }

        // Read the receiver and engine config files in the config directory
        //
        if (cl.hasOption('c')) {
            // Setup and check path to eif config file for TECAgent receiver object
            //
            configDir = cl.getOptionValue("c");
            cfgFileReceiver = configDir + dirSep + instanceName + ".conf";
            checkConfigFile(cfgFileReceiver);

            // Setup and check path to xml config file for the EventEngine
            //
            cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml";
            checkConfigFile(cfgFileEngine);

        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'c' is a required option", opts);
            System.exit(1);
        }
    } catch (UnrecognizedOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingArgumentException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }

    // Main program
    //
    try {
        // =====================================================================
        // Setup the message, trace and status logger objects
        //
        try {
            msgHandler = new FileHandler("cresendo", "message handler", logPath);
            msgHandler.openDevice();

            msgLogger = new MessageLogger("cresendo", "message log");
            msgLogger.addHandler(msgHandler);

            trcHandler = new FileHandler("cresendo", "trace handler", tracePath);
            trcHandler.openDevice();

            trcLogger = new TraceLogger("cresendo", "trace log");
            trcLogger.addHandler(trcHandler);

            statLogger = new StatusLogger(statusPath);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Add the shutdown hook
        //
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName));

        // ---------------------------------------------------------------------
        // =====================================================================
        // Load and parse the xml event engine configuration file
        //
        //
        msg.setText("Loading xml engine from: '" + cfgFileEngine + "'");

        try {
            XMLConfiguration xmlProcessor = new XMLConfiguration();
            xmlProcessor.setFileName(cfgFileEngine);

            // Validate the xml against a document type declaration
            //
            xmlProcessor.setValidating(true);

            // Don't interpolate the tag contents by splitting them on a delimiter
            // (ie by default a comma)
            //
            xmlProcessor.setDelimiterParsingDisabled(true);

            // This will throw a ConfigurationException if the xml document does not
            // conform to its dtd.  By doing this we hopefully catch any errors left
            // behind after the xml configuration file has been edited.
            //
            xmlProcessor.load();

            // Setup the trace flag
            //
            ConfigurationNode engine = xmlProcessor.getRootNode();
            List rootAttribute = engine.getAttributes();

            for (Iterator it = rootAttribute.iterator(); it.hasNext();) {
                ConfigurationNode attr = (ConfigurationNode) it.next();

                String attrName = attr.getName();
                String attrValue = (String) attr.getValue();

                if (attrValue == null || attrValue == "") {
                    System.err.println("\n  Error: The value of the attribute '" + attrName + "'"
                            + "\n         in the xml file '" + cfgFileEngine + "'" + "\n         is not set");
                    System.exit(1);
                }

                if (attrName.matches("trace")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        trcLogger.setLogging(true);
                    }
                }

                if (attrName.matches("status")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        statLogger.setLogging(true);
                    } else {
                        statLogger.setLogging(false);
                    }
                }

                if (attrName.matches("interval")) {
                    if (!attrValue.matches("[0-9]+")) {
                        System.err.println("\n  Error: The value of the interval attribute in: '"
                                + cfgFileEngine + "'" + "\n         should only contain digits from 0 to 9."
                                + "\n         It currently contains: '" + attrValue + "'");
                        System.exit(1);
                    }

                    statLogger.setInterval(Integer.parseInt(attrValue));
                }
            }

            // Now build and instantiate the list of classes that will process events
            // received by the TECAgent receiver in a chain like manner.
            //
            List classes = xmlProcessor.configurationsAt("class");

            for (Iterator it = classes.iterator(); it.hasNext();) {
                HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();

                // sub contains now all data contained in a single <class></class> tag set
                //
                String className = sub.getString("name");

                // Log message
                //
                msg.setText(msg.getText() + "\n  Instantiated event handler class: '" + className + "'");

                // The angle brackets describing the class of object held by the
                // Vector are implemented by Java 1.5 and have 2 effects.
                //
                // 1. The list accepts only elements of that class and nothing else
                // (Of course thanks to Auto-Wrap you can also add double-values)
                //
                // 2. the get(), firstElement() ... Methods don't return a Object, but
                //    they deliver an element of the class.
                //
                Vector<Class> optTypes = new Vector<Class>(10, 10);
                Vector<Object> optValues = new Vector<Object>(10, 10);

                for (int i = 0; i <= sub.getMaxIndex("option"); i++) {
                    Object optValue = null;
                    String optVarName = sub.getString("option(" + i + ")[@varname]");
                    String optJavaType = sub.getString("option(" + i + ")[@javatype]");

                    // Use the specified java type in order to make the method call
                    // to the heirarchical sub object [painful :-((]
                    //
                    if (optJavaType.matches("byte")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getByte("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("short")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getShort("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("int")) {
                        optTypes.addElement(int.class);
                        optValue = sub.getInt("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("long")) {
                        optTypes.addElement(long.class);
                        optValue = sub.getLong("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("float")) {
                        optTypes.addElement(float.class);
                        optValue = sub.getFloat("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("double")) {
                        optTypes.addElement(double.class);
                        optValue = sub.getDouble("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("boolean")) {
                        optTypes.addElement(boolean.class);
                        optValue = sub.getBoolean("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = false; // Set to something nullish
                        }
                    } else if (optJavaType.matches("String")) {
                        optTypes.addElement(String.class);
                        optValue = sub.getString("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = ""; // Set it to something nullish
                        }
                    } else {
                        System.err.println(
                                "Error: Unsupported java type found in xml config: '" + optJavaType + "'");
                        System.exit(1);
                    }

                    // Add option value element
                    //
                    //              System.out.println("Option value is: '" + optValue.toString() + "'\n");
                    //
                    optValues.addElement(optValue);

                    // Append to message text
                    //
                    String msgTemp = msg.getText();
                    msgTemp += "\n      option name: '" + optVarName + "'";
                    msgTemp += "\n      option type: '" + optJavaType + "'";
                    msgTemp += "\n     option value: '" + optValues.lastElement().toString() + "'";
                    msg.setText(msgTemp);
                }

                try {
                    // Instantiate the class with the java reflection api
                    //
                    Class klass = Class.forName(className);

                    // Setup an array of paramater types in order to retrieve the matching constructor
                    //
                    Class[] types = optTypes.toArray(new Class[optTypes.size()]);

                    // Get the constructor for the class which matches the parameter types
                    //
                    Constructor konstruct = klass.getConstructor(types);

                    // Create an instance of the event handler
                    //
                    IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray());

                    // Add the instance to the list of event handlers
                    //
                    eventHandler.addElement(eventProcessor);

                } catch (InvocationTargetException e) {
                    System.err.println("Error: " + e.toString());
                    System.exit(1);
                } catch (ClassNotFoundException e) {
                    System.err.println("Error: class name not found: '" + className + "' \n" + e.toString());
                    System.exit(1);
                } catch (Exception e) {
                    System.err.println(
                            "Error: failed to instantiate class: '" + className + "' \n" + e.toString());
                    System.exit(1);
                }
            }
        } catch (ConfigurationException cex) // Something went wrong loading the xml file
        {
            System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString());
            System.exit(1);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // ---------------------------------------------------------------------
        // =====================================================================
        // Setup the TECAgent receiver 
        // 
        Reader cfgIn = null;

        try {
            cfgIn = new FileReader(cfgFileReceiver);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Start the TECAgent receiver and register the event engine handler
        //
        TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false);

        EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger);

        receiver.registerListener(ee);

        // Construct message and send it to the message log
        //
        String text = "\n  Cresendo instance '" + instanceName + "' listening for events on port '"
                + receiver.getConfigVal("ServerPort") + "'";

        msg.setText(msg.getText() + text);
        msgLogger.log(msg); // Send message to log

        // ---------------------------------------------------------------------
        // =====================================================================
        // Initiate status logging
        //
        if (statLogger.isLogging()) {
            int seconds = statLogger.getInterval();

            while (true) {
                try {
                    statLogger.log();
                } catch (Exception ex) {
                    System.err.println("\n  An error occurred while writing to '" + statusPath + "'" + "\n  '"
                            + ex.toString() + "'");
                }

                Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds
            }
        }

        // ---------------------------------------------------------------------
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }
}

From source file:at.ac.tuwien.inso.subcat.miner.MinerRunner.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("h", "help", false, "Show this options");
    options.addOption("m", "miner-help", false, "Show miner specific options");
    options.addOption("d", "db", true, "The database to process (required)");
    options.addOption("p", "project", true, "The project ID to process");
    options.addOption("P", "list-projects", false, "List all registered projects");
    options.addOption("v", "verbose", false, "Show details");

    options.addOption(null, "bug-repo", true, "Bug Repository URL");
    options.addOption(null, "bug-product", true, "Bug Product Name");
    options.addOption(null, "bug-tracker", true, "Bug Tracker name (e.g. bugzilla)");
    options.addOption(null, "bug-account", true, "Bug account name");
    options.addOption(null, "bug-passwd", true, "Bug account password");
    options.addOption(null, "bug-enable-untrusted", false, "Accept untrusted certificates");
    options.addOption(null, "bug-threads", true, "Thread count used in bug miners");
    options.addOption(null, "bug-cooldown-time", true, "Bug cooldown time");
    options.addOption(null, "bug-miner-option", true, "Bug miner specific option. Format: <option-name>:value");
    options.addOption(null, "bug-update", false, "Mine all changes since the last run");
    options.getOption("bug-miner-option").setArgs(Option.UNLIMITED_VALUES);

    options.addOption(null, "src-path", true, "Local source repository path");
    options.addOption(null, "src-remote", true, "Remote address");
    options.addOption(null, "src-passwd", true, "Source repository account password");
    options.addOption(null, "src-account", true, "Source repository account name");
    options.addOption(null, "src-miner-option", true,
            "Source miner specific option. Format: <option-name>:value");
    options.getOption("src-miner-option").setArgs(Option.UNLIMITED_VALUES);

    final Reporter reporter = new Reporter(true);
    reporter.startTimer();//from  w ww  .ja  va2  s . co m

    boolean printTraces = false;
    Settings settings = new Settings();
    ModelPool pool = null;

    CommandLineParser parser = new PosixParser();

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

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

        if (cmd.hasOption("miner-help")) {
            init();
            for (MetaData meta : registeredMiner) {
                System.out.println(meta.name());
                for (Entry<String, ParamType> opt : meta.getSpecificParams().entrySet()) {
                    System.out.println("  - " + opt.getKey() + " (" + opt.getValue() + ")");
                }
            }
            return;
        }

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

        printTraces = cmd.hasOption("verbose");
        pool = new ModelPool(cmd.getOptionValue("db"), 2);

        if (cmd.hasOption("list-projects")) {
            Model model = pool.getModel();

            for (Project proj : model.getProjects()) {
                System.out.println("  " + proj.getId() + ": " + proj.getDate());
            }

            model.close();
            return;
        }

        Project project;
        Model model = pool.getModel();
        boolean hasSrcInfos = false;
        boolean hasBugInfos = false;
        if (cmd.hasOption("project")) {
            try {
                int projId = Integer.parseInt(cmd.getOptionValue("project"));
                project = model.getProject(projId);
            } catch (NumberFormatException e) {
                reporter.error("post-processor", "Invalid project ID");
                reporter.printSummary();
                return;
            }

            if (project == null) {
                reporter.error("post-processor", "Invalid project ID");
                reporter.printSummary();
                return;
            }

            List<String> flags = model.getFlags(project);
            hasBugInfos = flags.contains(Model.FLAG_BUG_INFO);
            hasSrcInfos = flags.contains(Model.FLAG_SRC_INFO);
        } else {
            project = model.addProject(new Date(), null, settings.bugTrackerName, settings.bugRepository,
                    settings.bugProductName, null);
        }
        model.close();

        //
        // Source Repository Mining:
        //

        settings.srcLocalPath = cmd.getOptionValue("src-path");
        settings.srcRemote = cmd.getOptionValue("src-remote");
        settings.srcRemotePw = cmd.getOptionValue("src-passwd");
        settings.srcRemoteUser = cmd.getOptionValue("src-account");

        if (settings.srcRemotePw == null || settings.srcRemoteUser == null) {
            if (settings.srcRemotePw != null) {
                reporter.error("miner", "--src-passwd should only be used in combination with --src-account");
                reporter.printSummary();
                return;
            } else if (settings.srcRemoteUser != null) {
                reporter.error("miner", "--src-account should only be used in combination with --src-passwd");
                reporter.printSummary();
                return;
            }
        }

        if (settings.srcRemoteUser != null && settings.srcRemote == null) {
            reporter.error("miner", "--src-account should only be used in combination with --src-remote");
            reporter.printSummary();
            return;
        }

        if (settings.srcLocalPath != null && hasSrcInfos) {
            reporter.error("miner", "Source repository updates are not supported yet.");
            reporter.printSummary(true);
            return;
        }

        //
        // Bug Repository Mining:
        //

        settings.bugRepository = cmd.getOptionValue("bug-repo");
        settings.bugProductName = cmd.getOptionValue("bug-product");
        settings.bugTrackerName = cmd.getOptionValue("bug-tracker");
        settings.bugEnableUntrustedCertificates = cmd.hasOption("bug-enable-untrusted");
        settings.bugLoginUser = cmd.getOptionValue("bug-account");
        settings.bugLoginPw = cmd.getOptionValue("bug-passwd");

        settings.bugUpdate = cmd.hasOption("bug-update");
        boolean includeBugs = false;
        if (settings.bugUpdate) {
            if (project.getBugTracker() == null || project.getDomain() == null) {
                reporter.error("miner",
                        "flag --bug-update is requires previously mined bugs. Use --bug-repository, --bug-product and --bug-tracker.");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugTrackerName != null) {
                reporter.warning("miner", "flag --bug-tracker without effect");
            }
            if (settings.bugProductName != null) {
                reporter.warning("miner", "flag --bug-product without effect");
            }
            if (settings.bugRepository != null) {
                reporter.warning("miner", "flag --bug-repository without effect");
            }

            settings.bugTrackerName = project.getBugTracker();
            settings.bugProductName = project.getProduct();
            settings.bugRepository = project.getDomain();
            includeBugs = true;
        } else if (settings.bugRepository != null && settings.bugProductName != null
                && settings.bugTrackerName != null) {
            if (hasBugInfos == false) {
                // The user is trying to append bug tracker information to a existing project.
            } else if (!settings.bugTrackerName.equalsIgnoreCase(project.getBugTracker())
                    || !settings.bugProductName.equalsIgnoreCase(project.getProduct())
                    || !settings.bugRepository.equalsIgnoreCase(project.getDomain())) {
                reporter.error("miner",
                        "There are already previously mined bugs for this project. Use --bug-update to update the database.");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugRepository == null) {
                reporter.error("miner", "flag --bug-repository is required");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugProductName == null) {
                reporter.error("miner", "flag --bug-product is required");
                reporter.printSummary(true);
                return;
            }
            includeBugs = true;
        }

        if (includeBugs) {
            if (settings.bugLoginPw == null || settings.bugLoginUser == null) {
                if (settings.bugLoginPw != null) {
                    reporter.error("miner",
                            "--bug-passwd should only be used in combination with --bug-account");
                    reporter.printSummary();
                    return;
                } else if (settings.bugLoginUser != null) {
                    reporter.error("miner",
                            "--bug-account should only be used in combination with --bug-passwd");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-threads")) {
                try {
                    settings.bugThreads = Integer.parseInt(cmd.getOptionValue("bug-threads"));
                } catch (Exception e) {
                    reporter.error("miner", "--bug-threads: Invalid parameter type");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-cooldown-time")) {
                try {
                    settings.bugCooldownTime = Integer.parseInt(cmd.getOptionValue("bug-cooldown-time"));
                } catch (Exception e) {
                    reporter.error("miner", "--bug-cooldown-time: Invalid parameter type");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-miner-option")) {
                for (String str : cmd.getOptionValues("bug-miner-option")) {
                    addSpecificParameter(settings.bugSpecificParams, str);
                }
            }

            if (cmd.hasOption("src-miner-option")) {
                for (String str : cmd.getOptionValues("src-miner-option")) {
                    addSpecificParameter(settings.srcSpecificParams, str);
                }
            }
        } else {
            if (settings.bugLoginPw != null) {
                reporter.error("miner", "--bug-passwd should only be used in combination with --bug-account");
                reporter.printSummary();
                return;
            }
            if (settings.bugLoginUser != null) {
                reporter.error("miner", "--bug-account should only be used in combination with --bug-account");
                reporter.printSummary();
                return;
            }
            if (settings.bugRepository != null) {
                reporter.error("miner",
                        "--bug-repo should only be used in combination with --bug-product and --bug-tracker");
                reporter.printSummary();
                return;
            }
            if (settings.bugProductName != null) {
                reporter.error("miner",
                        "--bug-product should only be used in combination with --bug-repo and --bug-tracker");
                reporter.printSummary();
                return;
            }
            if (settings.bugTrackerName != null) {
                reporter.error("miner",
                        "--bug-tracker should only be used in combination with --bug-repo and --bug-product");
                reporter.printSummary();
                return;
            }
            if (settings.bugEnableUntrustedCertificates) {
                reporter.error("miner",
                        "--bug-enable-untrusted should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (settings.bugUpdate) {
                reporter.error("miner",
                        "--bug-update should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-threads")) {
                reporter.error("miner",
                        "--bug-threads should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-cooldown-time")) {
                reporter.error("miner",
                        "--bug-cooldown-time should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-miner-option")) {
                reporter.error("miner",
                        "--bug-miner-option should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
        }

        //
        // Run:
        //

        MinerRunner runner = new MinerRunner(pool, project, settings, reporter);
        if (cmd.hasOption("verbose")) {
            runner.addListener(new MinerListener() {
                private Map<Miner, Integer> totals = new HashMap<Miner, Integer>();

                @Override
                public void start(Miner miner) {
                }

                @Override
                public void end(Miner miner) {
                }

                @Override
                public void stop(Miner miner) {
                }

                @Override
                public void tasksTotal(Miner miner, int count) {
                    totals.put(miner, count);
                }

                @Override
                public void tasksProcessed(Miner miner, int processed) {
                    Integer total = totals.get(miner);
                    reporter.note(miner.getName(),
                            "status: " + processed + "/" + ((total == null) ? "0" : total));
                }
            });
        }

        runner.run();
    } catch (ParameterException e) {
        reporter.error(e.getMiner().getName(), e.getMessage());
    } catch (ParseException e) {
        reporter.error("miner", "Parsing failed: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        reporter.error("miner", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (SQLException e) {
        reporter.error("miner", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (MinerException e) {
        reporter.error("miner", "Mining Error: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } finally {
        if (pool != null) {
            pool.close();
        }
    }

    reporter.printSummary(true);
}

From source file:gpframework.RunExperiment.java

/**
 * Application's entry point.//from   ww w  . jav  a 2 s  .c o  m
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//from w  ww .ja v a2 s  . c o m
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:lineage.LineageEngine.java

public static void main(String[] args) {
    Options options = new Options();
    // Commands//from w  ww  .  ja v a  2s  .  c o 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);
    }
}