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

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

Introduction

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

Prototype

OptionGroup

Source Link

Usage

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//from  w  w  w .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:com.enioka.jqm.tools.Main.java

/**
 * Startup method for the packaged JAR//  www.j  a va2s  .  co m
 * 
 * @param args
 *            0 is node name
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Helpers.setLogFileName("cli");
    Option o00 = OptionBuilder.withArgName("nodeName").hasArg().withDescription("name of the JQM node to start")
            .isRequired().create("startnode");
    Option o01 = OptionBuilder.withDescription("display help").withLongOpt("help").create("h");
    Option o11 = OptionBuilder.withArgName("applicationname").hasArg()
            .withDescription("name of the application to launch").isRequired().create("enqueue");
    Option o21 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("path of the XML configuration file to import").isRequired()
            .create("importjobdef");
    Option o31 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("export all queue definitions into an XML file").isRequired()
            .create("exportallqueues");
    OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("export some queue definitions into an XML file").isRequired()
            .create("exportqueuefile");
    OptionBuilder.withArgName("queues").hasArg().withDescription("queues to export").withValueSeparator(',')
            .isRequired().create("queue");
    Option o51 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("import all queue definitions from an XML file").isRequired()
            .create("importqueuefile");
    Option o61 = OptionBuilder.withArgName("nodeName").hasArg()
            .withDescription("creates a JQM node of this name, or updates it if it exists. Implies -u.")
            .isRequired().create("createnode");
    Option o71 = OptionBuilder.withDescription("display JQM engine version").withLongOpt("version").create("v");
    Option o81 = OptionBuilder.withDescription("upgrade JQM database").withLongOpt("upgrade").create("u");
    Option o91 = OptionBuilder.withArgName("jobInstanceId").hasArg()
            .withDescription("get job instance status by ID").isRequired().withLongOpt("getstatus").create("g");
    Option o101 = OptionBuilder.withArgName("password").hasArg()
            .withDescription("creates or resets root admin account password").isRequired().withLongOpt("root")
            .create("r");
    Option o111 = OptionBuilder.withArgName("option").hasArg()
            .withDescription(
                    "ws handling. Possible values are: enable, disable, ssl, nossl, internalpki, externalapi")
            .isRequired().withLongOpt("gui").create("w");
    Option o121 = OptionBuilder.withArgName("id[,logfilepath]").hasArg().withDescription("single launch mode")
            .isRequired().withLongOpt("gui").create("s");
    Option o131 = OptionBuilder.withArgName("resourcefile").hasArg()
            .withDescription("resource parameter file to use. Default is resources.xml")
            .withLongOpt("resources").create("p");
    Option o141 = OptionBuilder.withArgName("login,password,role1,role2,...").hasArgs(Option.UNLIMITED_VALUES)
            .withValueSeparator(',')
            .withDescription("Create or update a JQM account. Roles must exist beforehand.").create("U");

    Options options = new Options();
    OptionGroup og1 = new OptionGroup();
    og1.setRequired(true);
    og1.addOption(o00);
    og1.addOption(o01);
    og1.addOption(o11);
    og1.addOption(o21);
    og1.addOption(o31);
    og1.addOption(o51);
    og1.addOption(o61);
    og1.addOption(o71);
    og1.addOption(o81);
    og1.addOption(o91);
    og1.addOption(o101);
    og1.addOption(o111);
    og1.addOption(o121);
    og1.addOption(o141);
    options.addOptionGroup(og1);
    OptionGroup og2 = new OptionGroup();
    og2.addOption(o131);
    options.addOptionGroup(og2);

    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(160);

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

        // Other db connection?
        if (line.getOptionValue(o131.getOpt()) != null) {
            jqmlogger.info("Using resource XML file " + line.getOptionValue(o131.getOpt()));
            Helpers.resourceFile = line.getOptionValue(o131.getOpt());
        }

        // Set db connection
        Helpers.registerJndiIfNeeded();

        // Enqueue
        if (line.getOptionValue(o11.getOpt()) != null) {
            enqueue(line.getOptionValue(o11.getOpt()));
        }
        // Get status
        if (line.getOptionValue(o91.getOpt()) != null) {
            getStatus(Integer.parseInt(line.getOptionValue(o91.getOpt())));
        }
        // Import XML
        else if (line.getOptionValue(o21.getOpt()) != null) {
            importJobDef(line.getOptionValue(o21.getOpt()));
        }
        // Start engine
        else if (line.getOptionValue(o00.getOpt()) != null) {
            startEngine(line.getOptionValue(o00.getOpt()));
        }
        // Export all Queues
        else if (line.getOptionValue(o31.getOpt()) != null) {
            exportAllQueues(line.getOptionValue(o31.getOpt()));
        }
        // Import queues
        else if (line.getOptionValue(o51.getOpt()) != null) {
            importQueues(line.getOptionValue(o51.getOpt()));
        }
        // Create node
        else if (line.getOptionValue(o61.getOpt()) != null) {
            createEngine(line.getOptionValue(o61.getOpt()));
        }
        // Upgrade
        else if (line.hasOption(o81.getOpt())) {
            upgrade();
        }
        // Help
        else if (line.hasOption(o01.getOpt())) {
            formatter.printHelp("java -jar jqm-engine.jar", options, true);
        }
        // Version
        else if (line.hasOption(o71.getOpt())) {
            jqmlogger.info("Engine version: " + Helpers.getMavenVersion());
        }
        // Root password
        else if (line.hasOption(o101.getOpt())) {
            root(line.getOptionValue(o101.getOpt()));
        }
        // Web options
        else if (line.hasOption(o111.getOpt())) {
            ws(line.getOptionValue(o111.getOpt()));
        }
        // Web options
        else if (line.hasOption(o121.getOpt())) {
            single(line.getOptionValue(o121.getOpt()));
        }
        // User handling
        else if (line.hasOption(o141.getOpt())) {
            user(line.getOptionValues(o141.getOpt()));
        }
    } catch (ParseException exp) {
        jqmlogger.fatal("Could not read command line: " + exp.getMessage());
        formatter.printHelp("java -jar jqm-engine.jar", options, true);
        return;
    }
}

From source file:edu.harvard.hul.ois.fits.Fits.java

public static void main(String[] args) throws FitsException, IOException, ParseException, XMLStreamException {
    Fits fits = new Fits();

    Options options = new Options();
    options.addOption("i", true, "input file or directory");
    options.addOption("r", false, "process directories recursively when -i is a directory ");
    options.addOption("o", true, "output file");
    options.addOption("h", false, "print this message");
    options.addOption("v", false, "print version information");
    OptionGroup outputOptions = new OptionGroup();
    Option stdxml = new Option("x", false, "convert FITS output to a standard metadata schema");
    Option combinedStd = new Option("xc", false,
            "output using a standard metadata schema and include FITS xml");
    outputOptions.addOption(stdxml);//from  ww w. j  av  a  2s . com
    outputOptions.addOption(combinedStd);
    options.addOptionGroup(outputOptions);

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

    if (cmd.hasOption("h")) {
        fits.printHelp(options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println(Fits.VERSION);
        System.exit(0);
    }
    if (cmd.hasOption("r")) {
        traverseDirs = true;
    } else {
        traverseDirs = false;
    }

    if (cmd.hasOption("i")) {
        String input = cmd.getOptionValue("i");
        File inputFile = new File(input);

        if (inputFile.isDirectory()) {
            String outputDir = cmd.getOptionValue("o");
            if (outputDir == null || !(new File(outputDir).isDirectory())) {
                throw new FitsException(
                        "When FITS is run in directory processing mode the output location must be a diretory");
            }
            fits.doDirectory(inputFile, new File(outputDir), cmd.hasOption("x"), cmd.hasOption("xc"));
        } else {
            FitsOutput result = fits.doSingleFile(inputFile);
            fits.outputResults(result, cmd.getOptionValue("o"), cmd.hasOption("x"), cmd.hasOption("xc"), false);
        }
    } else {
        System.err.println("Invalid CLI options");
        fits.printHelp(options);
        System.exit(-1);
    }

    System.exit(0);
}

From source file:com.example.bigquery.QuerySample.java

/** Prompts the user for the required parameters to perform a query. */
public static void main(final String[] args)
        throws IOException, InterruptedException, TimeoutException, ParseException {
    Options options = new Options();

    // Use an OptionsGroup to choose which sample to run.
    OptionGroup samples = new OptionGroup();
    samples.addOption(Option.builder().longOpt("runSimpleQuery").build());
    samples.addOption(Option.builder().longOpt("runStandardSqlQuery").build());
    samples.addOption(Option.builder().longOpt("runPermanentTableQuery").build());
    samples.addOption(Option.builder().longOpt("runUncachedQuery").build());
    samples.addOption(Option.builder().longOpt("runBatchQuery").build());
    samples.isRequired();/*from  ww  w  . j a va  2 s.com*/
    options.addOptionGroup(samples);

    options.addOption(Option.builder().longOpt("query").hasArg().required().build());
    options.addOption(Option.builder().longOpt("destDataset").hasArg().build());
    options.addOption(Option.builder().longOpt("destTable").hasArg().build());
    options.addOption(Option.builder().longOpt("allowLargeResults").build());

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

    String query = cmd.getOptionValue("query");
    if (cmd.hasOption("runSimpleQuery")) {
        runSimpleQuery(query);
    } else if (cmd.hasOption("runStandardSqlQuery")) {
        runStandardSqlQuery(query);
    } else if (cmd.hasOption("runPermanentTableQuery")) {
        String destDataset = cmd.getOptionValue("destDataset");
        String destTable = cmd.getOptionValue("destTable");
        boolean allowLargeResults = cmd.hasOption("allowLargeResults");
        runQueryPermanentTable(query, destDataset, destTable, allowLargeResults);
    } else if (cmd.hasOption("runUncachedQuery")) {
        runUncachedQuery(query);
    } else if (cmd.hasOption("runBatchQuery")) {
        runBatchQuery(query);
    }
}

From source file:com.example.dlp.Redact.java

/** Command line application to redact strings, images using the Data Loss Prevention API. */
public static void main(String[] args) throws Exception {
    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);/*w  ww  . java2  s.  com*/
    Option stringOption = new Option("s", "string", true, "redact string");
    optionsGroup.addOption(stringOption);

    Option fileOption = new Option("f", "file path", true, "redact input file path");
    optionsGroup.addOption(fileOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build();

    commandLineOptions.addOption(minLikelihoodOption);

    Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build();
    commandLineOptions.addOption(replaceOption);

    Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build();
    infoTypesOption.setArgs(Option.UNLIMITED_VALUES);
    commandLineOptions.addOption(infoTypesOption);

    Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false)
            .build();
    commandLineOptions.addOption(outputFilePathOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(Redact.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_");

    List<InfoType> infoTypesList = new ArrayList<>();
    String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt());
    if (infoTypes != null) {
        for (String infoType : infoTypes) {
            infoTypesList.add(InfoType.newBuilder().setName(infoType).build());
        }
    }
    Likelihood minLikelihood = Likelihood.valueOf(
            cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name()));

    // string inspection
    if (cmd.hasOption("s")) {
        String source = cmd.getOptionValue(stringOption.getOpt());
        redactString(source, replacement, minLikelihood, infoTypesList);
    } else if (cmd.hasOption("f")) {
        String filePath = cmd.getOptionValue(fileOption.getOpt());
        String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt());
        redactImage(filePath, minLikelihood, infoTypesList, outputFilePath);
    }
}

From source file:com.example.dlp.DeIdentification.java

/**
 * Command line application to de-identify data using the Data Loss Prevention API.
 * Supported data format: strings//from  w w w. j  a  v  a  2 s  .  c om
 */
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option deidentifyMaskingOption = new Option("m", "mask", true, "deid with character masking");
    optionsGroup.addOption(deidentifyMaskingOption);

    Option deidentifyFpeOption = new Option("f", "fpe", true, "deid with FFX FPE");
    optionsGroup.addOption(deidentifyFpeOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option maskingCharacterOption = Option.builder("maskingCharacter").hasArg(true).required(false).build();
    commandLineOptions.addOption(maskingCharacterOption);

    Option numberToMaskOption = Option.builder("numberToMask").hasArg(true).required(false).build();
    commandLineOptions.addOption(numberToMaskOption);

    Option alphabetOption = Option.builder("commonAlphabet").hasArg(true).required(false).build();
    commandLineOptions.addOption(alphabetOption);

    Option wrappedKeyOption = Option.builder("wrappedKey").hasArg(true).required(false).build();
    commandLineOptions.addOption(wrappedKeyOption);

    Option keyNameOption = Option.builder("keyName").hasArg(true).required(false).build();
    commandLineOptions.addOption(keyNameOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(DeIdentification.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    if (cmd.hasOption("m")) {
        // deidentification with character masking
        int numberToMask = Integer.parseInt(cmd.getOptionValue(numberToMaskOption.getOpt(), "0"));
        char maskingCharacter = cmd.getOptionValue(maskingCharacterOption.getOpt(), "*").charAt(0);
        String val = cmd.getOptionValue(deidentifyMaskingOption.getOpt());
        deIdentifyWithMask(val, maskingCharacter, numberToMask);
    } else if (cmd.hasOption("f")) {
        // deidentification with FPE
        String wrappedKey = cmd.getOptionValue(wrappedKeyOption.getOpt());
        String keyName = cmd.getOptionValue(keyNameOption.getOpt());
        String val = cmd.getOptionValue(deidentifyFpeOption.getOpt());
        FfxCommonNativeAlphabet alphabet = FfxCommonNativeAlphabet.valueOf(
                cmd.getOptionValue(alphabetOption.getOpt(), FfxCommonNativeAlphabet.ALPHA_NUMERIC.name()));
        deIdentifyWithFpe(val, alphabet, keyName, wrappedKey);
    }
}

From source file:com.github.andreax79.meca.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("X", "suppress-output", false, "don't create the output file");

    OptionGroup boundariesOptions = new OptionGroup();
    boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)"));
    boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries"));
    boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries"));
    boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries"));
    options.addOptionGroup(boundariesOptions);

    OptionGroup colorOptions = new OptionGroup();
    colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)"));
    colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme"));
    colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme"));
    options.addOptionGroup(colorOptions);

    options.addOption(OptionBuilder.withLongOpt("rule").withDescription("rule number (required)").hasArg()
            .withArgName("rule").create());

    options.addOption(OptionBuilder.withLongOpt("width").withDescription("space width (required)").hasArg()
            .withArgName("width").create());

    options.addOption(OptionBuilder.withLongOpt("steps").withDescription("number of steps (required)").hasArg()
            .withArgName("steps").create());

    options.addOption(OptionBuilder.withLongOpt("alpha").withDescription("memory factor (default 0)").hasArg()
            .withArgName("alpha").create());

    options.addOption(OptionBuilder.withLongOpt("pattern").withDescription("inititial pattern").hasArg()
            .withArgName("pattern").create());

    options.addOption("s", "single-seed", false, "single cell seed");
    options.addOption("si", "single-seed-inverse", false, "all 1 except one cell");

    options.addOption(OptionBuilder.withLongOpt("update-patter")
            .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")").hasArg()
            .withArgName("updatepatter").create());

    // test/*from w  w w.  j a  v  a  2  s . com*/
    // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" };

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (!line.hasOption("rule"))
            throw new ParseException("no rule number (use --rule=XX)");
        int rule;
        try {
            rule = Integer.parseInt(line.getOptionValue("rule"));
            if (rule < 0 || rule > 15)
                throw new ParseException("invalid rule number");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid rule number");
        }

        if (!line.hasOption("width"))
            throw new ParseException("no space width (use --width=XX)");
        int width;
        try {
            width = Integer.parseInt(line.getOptionValue("width"));
            if (width < 1)
                throw new ParseException("invalid width");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid width");
        }

        if (!line.hasOption("steps"))
            throw new ParseException("no number of steps (use --steps=XX)");
        int steps;
        try {
            steps = Integer.parseInt(line.getOptionValue("steps"));
            if (width < 1)
                throw new ParseException("invalid number of steps");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid number of steps");
        }

        double alpha = 0;
        if (line.hasOption("alpha")) {
            try {
                alpha = Double.parseDouble(line.getOptionValue("alpha"));
                if (alpha < 0 || alpha > 1)
                    throw new ParseException("invalid alpha");
            } catch (NumberFormatException ex) {
                throw new ParseException("invalid alpha");
            }
        }

        String pattern = null;
        if (line.hasOption("pattern")) {
            pattern = line.getOptionValue("pattern");
            if (pattern != null)
                pattern = pattern.trim();
        }

        if (line.hasOption("single-seed"))
            pattern = "S";
        else if (line.hasOption("single-seed-inverse"))
            pattern = "SI";

        UpdatePattern updatePatter = UpdatePattern.synchronous;
        if (line.hasOption("update-patter")) {
            try {
                updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter"));
            } catch (IllegalArgumentException ex) {
                throw new ParseException(ex.getMessage());
            }
        }

        Boundaries boundaries = Boundaries.periodic;
        if (line.hasOption("periodic"))
            boundaries = Boundaries.periodic;
        else if (line.hasOption("fixed"))
            boundaries = Boundaries.fixed;
        else if (line.hasOption("adiabatic"))
            boundaries = Boundaries.adiabatic;
        else if (line.hasOption("reflective"))
            boundaries = Boundaries.reflective;

        ColorScheme colorScheme = ColorScheme.noColor;
        if (line.hasOption("black-white"))
            colorScheme = ColorScheme.noColor;
        else if (line.hasOption("activation-color"))
            colorScheme = ColorScheme.activationColor;
        else if (line.hasOption("omega-color"))
            colorScheme = ColorScheme.omegaColor;

        Output output = Output.all;
        if (line.hasOption("suppress-output"))
            output = Output.noOutput;

        Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme);

    } catch (ParseException ex) {
        System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>");
        System.err.println();
        System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata");
        System.err.println();
        System.err.println("This program is free software; you can redistribute it and/or modify it");
        System.err.println("under the terms of the GNU General Public License as published by the");
        System.err.println("Free Software Foundation; either version 2 of the License, or (at your");
        System.err.println("option) any later version.");
        System.err.println();
        System.err.println("This program is distributed in the hope that it will be useful, but");
        System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY");
        System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License");
        System.err.println("for more details.");
        System.err.println();
        System.err.println("You should have received a copy of the GNU General Public License along");
        System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,");
        System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)");
        System.err.println();
        System.err.println(ex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("main", options);

    } catch (IOException ex) {
        System.err.println("IO exception:" + ex.getMessage());
    }

}

From source file:imageviewer.util.PasswordGenerator.java

public static void main(String[] args) {

    Option help = new Option("help", "Print this message");
    Option file = OptionBuilder.withArgName("file").hasArg().withDescription("Password filename")
            .create("file");
    Option addUser = OptionBuilder.withArgName("add").hasArg().withDescription("Add user profile")
            .create("add");
    Option removeUser = OptionBuilder.withArgName("remove").hasArg().withDescription("Remove user profile")
            .create("remove");
    Option updateUser = OptionBuilder.withArgName("update").hasArg().withValueSeparator()
            .withDescription("Update user profile").create("update");

    file.setRequired(true);//from w  ww  .j av a 2 s .c  o  m
    OptionGroup og = new OptionGroup();
    og.addOption(addUser);
    og.addOption(removeUser);
    og.addOption(updateUser);
    og.setRequired(true);

    Options o = new Options();
    o.addOption(help);
    o.addOption(file);
    o.addOptionGroup(og);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(o, args);
        PasswordGenerator pg = new PasswordGenerator(line);
        pg.execute();
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Unknown argument: " + uoe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println("Missing argument: " + moe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.KafkaAvroSerDesApp.java

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

    Option sendMessages = Option.builder("sm").longOpt("send-messages").desc("Send Messages to Kafka")
            .type(Boolean.class).build();
    Option consumeMessages = Option.builder("cm").longOpt("consume-messages")
            .desc("Consume Messages from Kafka").type(Boolean.class).build();

    Option dataFileOption = Option.builder("d").longOpt("data-file").hasArg().desc("Provide a data file")
            .type(String.class).build();
    Option producerFileOption = Option.builder("p").longOpt("producer-config").hasArg()
            .desc("Provide a Kafka producer config file").type(String.class).build();
    Option schemaOption = Option.builder("s").longOpt("schema-file").hasArg().desc("Provide a schema file")
            .type(String.class).build();

    Option consumerFileOption = Option.builder("c").longOpt("consumer-config").hasArg()
            .desc("Provide a Kafka Consumer config file").type(String.class).build();

    OptionGroup groupOpt = new OptionGroup();
    groupOpt.addOption(sendMessages);//  ww w  . ja  v  a2s.  c  om
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    Options options = new Options();
    options.addOptionGroup(groupOpt);
    options.addOption(dataFileOption);
    options.addOption(producerFileOption);
    options.addOption(schemaOption);
    options.addOption(consumerFileOption);

    //showHelpMessage(args, options);

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("sm")) {
            if (commandLine.hasOption("p") && commandLine.hasOption("d") && commandLine.hasOption("s")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("p"),
                        commandLine.getOptionValue("s"));
                kafkaAvroSerDesApp.sendMessages(commandLine.getOptionValue("d"));
            } else {
                LOG.error("please provide following options for sending messages to Kafka");
                LOG.error("-d or --data-file");
                LOG.error("-s or --schema-file");
                LOG.error("-p or --producer-config");
            }
        } else if (commandLine.hasOption("cm")) {
            if (commandLine.hasOption("c")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("c"));
                kafkaAvroSerDesApp.consumeMessages();
            } else {
                LOG.error("please provide following options for consuming messages from Kafka");
                LOG.error("-c or --consumer-config");
            }
        }
    } catch (ParseException e) {
        LOG.error("Please provide all the options ", e);
    } catch (Exception e) {
        LOG.error("Failed to send/receive messages ", e);
    }

}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.TruckEventsKafkaAvroSerDesApp.java

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

    Option sendMessages = Option.builder("sm").longOpt("send-messages").desc("Send Messages to Kafka")
            .type(Boolean.class).build();
    Option consumeMessages = Option.builder("cm").longOpt("consume-messages")
            .desc("Consume Messages from Kafka").type(Boolean.class).build();

    Option dataFileOption = Option.builder("d").longOpt("data-file").hasArg().desc("Provide a data file")
            .type(String.class).build();
    Option producerFileOption = Option.builder("p").longOpt("producer-config").hasArg()
            .desc("Provide a Kafka producer config file").type(String.class).build();
    Option schemaOption = Option.builder("s").longOpt("schema-file").hasArg().desc("Provide a schema file")
            .type(String.class).build();

    Option consumerFileOption = Option.builder("c").longOpt("consumer-config").hasArg()
            .desc("Provide a Kafka Consumer config file").type(String.class).build();

    OptionGroup groupOpt = new OptionGroup();
    groupOpt.addOption(sendMessages);/*  w w  w.  j  ava 2s. com*/
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    Options options = new Options();
    options.addOptionGroup(groupOpt);
    options.addOption(dataFileOption);
    options.addOption(producerFileOption);
    options.addOption(schemaOption);
    options.addOption(consumerFileOption);

    //showHelpMessage(args, options);

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("sm")) {
            if (commandLine.hasOption("p") && commandLine.hasOption("d") && commandLine.hasOption("s")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("p"), commandLine.getOptionValue("s"));
                truckEventsKafkaAvroSerDesApp.sendMessages(commandLine.getOptionValue("d"));
            } else {
                LOG.error("please provide following options for sending messages to Kafka");
                LOG.error("-d or --data-file");
                LOG.error("-s or --schema-file");
                LOG.error("-p or --producer-config");
            }
        } else if (commandLine.hasOption("cm")) {
            if (commandLine.hasOption("c")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("c"));
                truckEventsKafkaAvroSerDesApp.consumeMessages();
            } else {
                LOG.error("please provide following options for consuming messages from Kafka");
                LOG.error("-c or --consumer-config");
            }
        }
    } catch (ParseException e) {
        LOG.error("Please provide all the options ", e);
    } catch (Exception e) {
        LOG.error("Failed to send/receive messages ", e);
    }

}