Example usage for org.apache.commons.cli CommandLine getArgList

List of usage examples for org.apache.commons.cli CommandLine getArgList

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:edu.usc.scrc.PriorityPruner.CommandLineOptions.java

/**
 * Parses command line arguments for the help-option and prints help message
 * in case this option is encountered.//from  ww w  .j a  va 2  s  .  co  m
 * 
 * @param helpOptions
 *            collection containing the help option
 * @param options
 *            collection of Option-objects (all other options)
 * @param args
 *            command line arguments
 * @throws PriorityPrunerException
 *             if problems are encountered during parsing
 */
@SuppressWarnings("unchecked")
private boolean helpParse(Options helpOptions, Options options, String[] args) throws PriorityPrunerException {
    try {
        CommandLine helpCommandLine = new GnuParser().parse(helpOptions, args, true);
        //String empty = "";
        if (helpCommandLine.hasOption("h")) {
            printHelp();
            return true;
        } // checks list of arguments manually to make sure help is printed
          // correctly
        else {
            List<String> list = new ArrayList<String>();
            list = helpCommandLine.getArgList();
            if (list.contains("-h") || list.contains("--help") || list.contains("-help")) {
                printHelp();
                return true;
            }
        }
    } catch (ParseException e) {
        throw new PriorityPrunerException(
                "Invalid command line options. Type \"-h\" option to view a list of available program options.");
    }
    return false;
}

From source file:com.logicmonitor.ft.jmxstat.JMXStatMain.java

/**
 * @param args : arguments array/*from   ww w . j  a v  a  2 s . c o m*/
 * @return Run Parameter
 */
private static RunParameter ARGSAnalyser(String[] args) {

    Options options = new Options();
    options.addOption(new Option("h", "help", false, "show this help message"))
            .addOption(new Option("u", true, "User name for remote process"))
            .addOption(new Option("p", true, "Password for remote process"))
            .addOption(new Option("f", true, "Path to the configure file"))
            .addOption(new Option("t", true, "Exit after scanning jmx-paths n times"))
            .addOption(new Option("i", true, "Interval between two scan tasks, unit is second"))
            .addOption(new Option("a", false, "Show alias names instead of jmx paths"));

    CommandLineParser parser = new BasicParser();
    RunParameter runParameter = new RunParameter();
    ArrayList<JMXInPath> inputtedPaths = new ArrayList<JMXInPath>();
    try {
        CommandLine cli = parser.parse(options, args);
        if (args.length == 0 || cli.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jmxstat jmxURL [jmx path lists]", "To view statuses of jmx paths:", options,
                    "@Support by LogicMonitor", true);
            exit(0);
        }

        runParameter.setValid(true);
        if (cli.hasOption('a')) {
            runParameter.setShowAliasTitle(true);
        }
        if (cli.hasOption('f')) {
            List<JMXInPath> paths_from_file = getPathsFromFile(cli.getOptionValue('f'));
            inputtedPaths.addAll(paths_from_file);
        }
        if (cli.hasOption('t')) {
            try {
                int times = Integer.valueOf(cli.getOptionValue('t'));
                if (times < 0)
                    System.out.println("The argument after <-t> is useless here since it's a negative number.");
                else
                    runParameter.setTimes(times);
            } catch (Exception e) {
                runParameter.setValid(false);
                runParameter.setValidInfo(
                        runParameter.getValidInfo() + "Argument after <-t> should be an integer\n");
            }
        }
        if (cli.hasOption('u')) {
            runParameter.setUsername(cli.getOptionValue('u'));
        }
        if (cli.hasOption('p')) {
            runParameter.setPassword(cli.getOptionValue('p'));
        }
        if (cli.hasOption('i')) {
            try {
                int interval = Integer.valueOf(cli.getOptionValue('i'));
                if (interval < 0)
                    System.err.println("The interval value is negative! Using default set!");
                else {
                    runParameter.setInterval(interval);
                }
            } catch (Exception e) {
                runParameter.setValid(false);
                runParameter.setValidInfo(
                        runParameter.getValidInfo() + "Argument after <-i> should be an integer\n");
            }
        }
        List<String> others = cli.getArgList();
        boolean jmxurl_found = false;
        for (String other : others) {
            if (other.toLowerCase().startsWith("service:jmx")) {
                if (jmxurl_found) {
                    runParameter.setValid(false);
                    runParameter.setValidInfo(runParameter.getValidInfo() + "multiple jmxurl found\n");
                    return runParameter;
                } else {
                    jmxurl_found = true;
                    runParameter.setSurl(other.toLowerCase());
                }
            } else {
                inputtedPaths.add(new JMXInPath(other));
            }
        }
        if (!jmxurl_found) {
            runParameter.setValid(false);
            runParameter.setValidInfo(runParameter.getValidInfo()
                    + "No jmxurl found. The jmxurl should start with \"service:jmx\" \n");
        }
    } catch (ParseException e) {
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "Exception caught while parse arguments!\n");
    }

    if (inputtedPaths.isEmpty()) {
        runParameter.setValid(false);
        runParameter.setValidInfo(runParameter.getValidInfo() + "No jmx paths inputted");
    } else {
        runParameter.setPaths(inputtedPaths);
    }
    return runParameter;
}

From source file:com.antsdb.saltedfish.storage.HBaseUtilMain.java

private void run(String[] args) throws Exception {

    CommandLine line = parse(getOptions(), args);

    if (line.getOptions().length == 0 || line.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("hbase-util", getOptions());
        return;// w ww  . j a v a  2s.  c om
    }

    // Connecting

    if (line.hasOption("config")) {
        connectUseConfig(line.getOptionValue("config"));
    } else {
        String zkserver = "localhost";
        if (line.hasOption("server")) {
            zkserver = line.getOptionValue("server");
        }
        connect(zkserver);
    }

    // connect to hbase

    try {
        // options

        this.noversion = line.hasOption("noversion");

        // commands

        if (line.hasOption("clean")) {
            delete_all();
        } else if (line.hasOption("list-ns")) {
            list_ns();
        } else if (line.hasOption("list-table")) {
            list_table();
        } else if (line.hasOption("dump")) {
            if (line.getArgList().size() >= 1) {
                dump(line.getArgList().get(0));
            } else {
                println("error: table name is missing");
            }
        } else if (line.hasOption("link")) {
            link();
        } else if (line.hasOption("get-sp")) {
            // read current SP
            read_sp();
        } else if (line.hasOption("update-sp")) {
            // update current sp to specified value
            String updateSpValue = line.getOptionValue("update-sp", "");
            try {
                long currentSp = Long.parseLong(updateSpValue);
                update_sp(currentSp);
            } catch (Exception ex) {
                println("Invalid current SP value - " + updateSpValue + "\n");
            }
        } else if (line.hasOption("update-sp-db")) {
            // udpate current sp from antsdb
            File home = checkAntsDBHome(line);
            if (home != null) {
                update_sp(home);
            }
        } else if (line.hasOption("sync")) {
            File home = checkAntsDBHome(line);
            if (home != null) {
                boolean ignoreError = line.hasOption("ignore-error");
                int cores = Runtime.getRuntime().availableProcessors();
                int threads = cores;
                if (line.hasOption("threads")) {
                    threads = Integer.parseInt(line.getOptionValue("threads"));
                    if (threads <= 0 || threads > 200) {
                        threads = cores;
                    }
                }

                String skipList = line.getOptionValue("skip", "").trim();
                String syncList = line.getOptionValue("tables", "").trim();
                String[] skipTables = null;
                String[] syncTables = null;
                if (skipList != null && !skipList.isEmpty()) {
                    skipTables = skipList.split(",");
                }
                if (syncList != null && !syncList.isEmpty()) {
                    syncTables = syncList.split(",");
                }

                sync_antsdb(home, skipTables, syncTables, ignoreError, threads);
            }
        } else if (line.hasOption("compare")) {
            // udpate current sp from antsdb
            File home = checkAntsDBHome(line);
            if (home != null) {
                boolean ignoreError = line.hasOption("ignore-error");
                String skipList = line.getOptionValue("skip", "").trim();
                String syncList = line.getOptionValue("tables", "").trim();
                String[] skipTables = null;
                String[] syncTables = null;
                if (skipList != null && !skipList.isEmpty()) {
                    skipTables = skipList.split(",");
                }
                if (syncList != null && !syncList.isEmpty()) {
                    syncTables = syncList.split(",");
                }

                // update current sp to specified value
                int rows = 200;
                String s = line.getOptionValue("compare", "");
                try {
                    rows = Integer.parseInt(s);
                    if (rows < 0)
                        throw new Exception();
                } catch (Exception ex) {
                    println("Invalid compare rows count - " + s + "\n");
                }

                compare_hbase_rows(home, rows, skipTables, syncTables, ignoreError);
            }
        } else if (line.hasOption("checkrow")) {
            // udpate current sp from antsdb
            File home = checkAntsDBHome(line);
            if (home != null) {
                String table = line.getOptionValue("tables", "").trim();
                String key = line.getOptionValue("checkrow", "").trim();
                if (table == null || table.isEmpty()) {
                    println("No talbe specified.");
                } else if (key == null || key.isEmpty()) {
                    println("No row key specified,");
                } else {
                    checkRow(home, table, key);
                }
            }
        } else {
            println("error: command is missing");
        }
    }

    finally {

        // alway disconnect from hbase
        disconnect();
    }
}

From source file:javancss.Javancss.java

/**
 * This is the constructor used in the main routine in
 * javancss.Main.//from  w  ww .java2  s .  c o  m
 * Other constructors might be helpful to use Javancss out
 * of other programs.
 */
public Javancss(String[] args) throws IOException {
    Options options = new Options();
    options.addOption(OptionBuilder.create("help"));
    options.addOption(OptionBuilder.create("version"));
    options.addOption(OptionBuilder.create("debug"));
    options.addOption(OptionBuilder.withDescription("Counts the program NCSS (default).").create("ncss"));
    options.addOption(
            OptionBuilder.withDescription("Assembles a statistic on package level.").create("package"));
    options.addOption(OptionBuilder.withDescription("Counts the object NCSS.").create("object"));
    options.addOption(OptionBuilder.withDescription("Counts the function NCSS.").create("function"));
    options.addOption(OptionBuilder.withDescription("The same as '-function -object -package'.").create("all"));
    options.addOption(OptionBuilder
            .withDescription("Opens a GUI to present the '-all' output in tabbed panels.").create("gui"));
    options.addOption(OptionBuilder.withDescription("Output in XML format.").create("xml"));
    options.addOption(OptionBuilder.withDescription("Output file name. By default output goes to standard out.")
            .create("out"));
    options.addOption(OptionBuilder.withDescription("Recurse to subdirs.").create("recursive"));
    options.addOption(OptionBuilder
            .withDescription("Encoding used while reading source files (default: platform encoding).").hasArg()
            .create("encoding"));

    CommandLine cl;

    try {
        cl = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.err.println("javancss: " + e.getMessage());
        System.err.println("Try `javancss -help' for more information.");
        return;
    }

    if (cl.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("javancss [options] @srcfiles.txt | *.java | <directory> | <stdin>", options);

        return;
    }

    if (cl.hasOption("version")) {
        System.out.println(
                "JavaNCSS " + getClass().getPackage().getSpecificationVersion() + " by Chr. Clemens Lee & co");
        return;
    }

    if (cl.hasOption("debug")) {
        log.setLevel(Level.FINE);
    }

    setEncoding(cl.getOptionValue("encoding"));
    setXML(cl.hasOption("xml"));

    // the arguments (the files) to be processed
    _vJavaSourceFiles = findFiles(cl.getArgList(), cl.hasOption("recursive"));

    if (cl.hasOption("gui")) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }

        JavancssFrame pJavancssFrame = new JavancssFrame(cl.getArgList());
        /* final Thread pThread = Thread.currentThread(); */
        pJavancssFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent event) {
                setExit();
            }
        });
        pJavancssFrame.setVisible(true);

        try {
            _measureRoot(newReader(System.in));
        } catch (Throwable pThrowable) {
            // shouldn't we print something here?
            // error details have been written into lastError
        }

        pJavancssFrame.showJavancss(this);
        pJavancssFrame.setSelectedTab(JavancssFrame.S_PACKAGES);

        return;
    }

    // this initiates the measurement
    try {
        _measureRoot(newReader(System.in));
    } catch (Throwable pThrowable) {
        log.fine("Javancss.<init>(String[]).e: " + pThrowable);
        pThrowable.printStackTrace(System.err);
    }
    if (getLastErrorMessage() != null) {
        System.err.println(getLastErrorMessage() + "\n");
        if (getNcss() <= 0) {
            return;
        }
    }

    String sOutputFile = cl.getOptionValue("out");
    OutputStream out = System.out;
    if (sOutputFile != null) {
        try {
            out = new FileOutputStream(normalizeFileName(sOutputFile));
        } catch (Exception exception) {
            System.err.println("Error opening output file '" + sOutputFile + "': " + exception.getMessage());
            sOutputFile = null;
        }
    }
    // TODO: encoding configuration support for result output
    final PrintWriter pw = useXML() ? new PrintWriter(new OutputStreamWriter(out, "UTF-8"))
            : new PrintWriter(out);
    try {

        format(pw, cl.hasOption("package"), cl.hasOption("object"), cl.hasOption("function"),
                cl.hasOption("all"));

    } finally {
        if (sOutputFile != null) {
            pw.close();
        } else {
            // stdout is used: don't close but ensure everything is flushed
            pw.flush();
        }
    }
}

From source file:com.marklogic.shell.command.rm.java

public void execute(Environment env, String commandline) {
    if (commandline != null && commandline.length() > 0) {
        // XXX need to be a shell environment because we are getting input
        // from the user
        if (env instanceof Shell) {
            Shell shell = (Shell) env;/*from   w  ww  .j  av  a2s . c o m*/
            String[] tokens = commandline.split("\\s+");
            CommandLineParser parser = new PosixParser();
            CommandLine cmd = null;
            try {
                cmd = parser.parse(options, tokens);
            } catch (ParseException e) {
                env.outputException(e);
                return;
            }

            String xpath = cmd.getOptionValue("x");
            if (xpath != null && xpath.length() > 0) {
                String key = "n";
                if (cmd.hasOption("f")) {
                    key = "y";
                } else {
                    try {
                        key = shell.getConsole()
                                .readLine("remove all documents matching '" + xpath + "'? (N|y) ");
                    } catch (IOException e) {
                        shell.outputLine("Failed to read char from console");
                        shell.outputException(e);
                    }
                }
                if (key.equalsIgnoreCase("y")) {
                    String query = "concat(xs:string(count(for $n in (" + xpath + ")"
                            + " return (xdmp:document-delete(base-uri($n)), <done/>))), "
                            + "\" documents removed.\");";
                    Session session = shell.getContentSource().newSession();
                    AdhocQuery request = session.newAdhocQuery(query);
                    try {
                        shell.outputResultSequence(session.submitRequest(request));
                    } catch (RequestException e) {
                        shell.outputException(e);
                    }
                } else {
                    shell.outputLine("");
                }
            } else {
                for (Iterator i = cmd.getArgList().iterator(); i.hasNext();) {
                    String uri = (String) i.next();
                    String key = "n";
                    if (cmd.hasOption("f")) {
                        key = "y";
                    } else {
                        try {
                            key = shell.getConsole().readLine("remove '" + uri + "'? (N|y) ");
                        } catch (IOException e) {
                            shell.outputLine("Failed to read char from console");
                            shell.outputException(e);
                        }
                    }
                    if (key.equalsIgnoreCase("y")) {
                        String query = "if(doc(\"" + uri + "\")) then xdmp:document-delete(\"" + uri + "\") "
                                + "else \"Document not found.\"";
                        Session session = shell.getContentSource().newSession();
                        AdhocQuery request = session.newAdhocQuery(query);
                        try {
                            shell.outputResultSequence(session.submitRequest(request));
                        } catch (RequestException e) {
                            shell.outputException(e);
                        }
                    } else {
                        shell.outputLine("");
                    }
                }
            }
        }
    } else {
        env.outputLine("Please specify document(s) to remove. See help rm.");
    }
}

From source file:com.planet57.gshell.util.cli2.CliProcessor.java

public void process(final String... args) throws Exception {
    checkNotNull(args);// ww  w . j av  a 2 s.co m
    if (log.isTraceEnabled()) {
        log.trace("Processing: {}", Arrays.toString(args));
    }

    CliParser parser = flavor.create();
    log.trace("Parser: {}", parser);

    CommandLine cl;
    try {
        cl = parser.parse(createOptions(), args, stopAtNonOption);
    } catch (UnrecognizedOptionException e) {
        throw new ProcessingException(messages.UNDEFINED_OPTION(e.getOption()));
    } catch (MissingArgumentException e) {
        OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor();
        throw new ProcessingException(messages.MISSING_OPERAND(desc.getSyntax(), desc.getToken()));
    } catch (ParseException e) {
        throw new ProcessingException(e);
    }

    Set<CliDescriptor> present = new HashSet<>();
    boolean override = false;

    if (log.isTraceEnabled()) {
        log.trace("Parsed options: {}", Arrays.toString(cl.getOptions()));
    }

    for (Object tmp : cl.getOptions()) {
        Opt opt = (Opt) tmp;
        log.trace("Processing option: {}", opt);

        OptionDescriptor desc = opt.getDescriptor();
        present.add(desc);

        // Track the override, this is used to handle when --help present, but a required arg/opt is missing
        if (!override) {
            override = desc.getOverride();
        }

        Handler handler = Handlers.create(desc);
        String[] values = opt.getValues();

        if (values == null || values.length == 0) {
            // Set the value
            handler.handle(opt.getValue());
        } else {
            // Set the values
            for (String value : values) {
                handler.handle(value);
            }
        }
    }

    log.trace("Remaining arguments: {}", cl.getArgList());

    int i = 0;
    for (final String arg : cl.getArgs()) {
        log.trace("Processing argument: {}", arg);

        // Check if we allow an argument or we have overflowed
        if (i >= argumentDescriptors.size()) {
            throw new ProcessingException(argumentDescriptors.size() == 0 ? messages.NO_ARGUMENT_ALLOWED(arg)
                    : messages.TOO_MANY_ARGUMENTS(arg));
        }

        ArgumentDescriptor desc = argumentDescriptors.get(i);
        present.add(desc);

        // For single-valued args, increment the argument index, else let the multivalued handler consume it
        if (!desc.isMultiValued()) {
            i++;
        }

        // Set the value
        Handler handler = Handlers.create(desc);
        handler.handle(arg);
    }

    // Check for any required arguments which were not present
    if (!override) {
        try {
            parser.ensureRequiredOptionsPresent();
        } catch (MissingOptionException e) {
            throw new ProcessingException(messages.REQUIRED_OPTION_MISSING(e.getMissingOptions()));
        }

        for (ArgumentDescriptor arg : argumentDescriptors) {
            if (arg.isRequired() && !present.contains(arg)) {
                throw new ProcessingException(messages.REQUIRED_ARGUMENT_MISSING(arg.getToken()));
            }
        }
    }

    // TODO: Handle setting defaults
}

From source file:cz.pecina.retro.ondra.CommandLineProcessor.java

/**
 * Creates an instance of the command line procssor.
 *
 * @param hardware the hardware object to operate on
 *///from  ww  w .  j a v  a2  s.  co m
public CommandLineProcessor(final Hardware hardware) {
    log.fine("New CommandLineProcessor creation started");
    this.hardware = hardware;

    // build options
    log.fine("Building options");
    options.addOption(
            Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build());
    options.addOption(
            Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build());
    options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE")
            .desc(Application.getString(this, "option.language")).build());
    options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE")
            .desc(Application.getString(this, "option.pixelSize")).build());
    options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR")
            .desc(Application.getString(this, "option.address")).build());
    options.addOption(Option.builder("o").longOpt("ROM-file").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.ROM")).build());
    options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR")
            .valueSeparator(',').desc(Application.getString(this, "option.binary")).build());
    options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.intelHex")).build());
    options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.xml")).build());
    options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.snapshot")).build());
    options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.writeSnapshot")).build());
    options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR")
            .desc(Application.getString(this, "option.speedUp")).build());
    options.addOption(
            Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build());
    options.addOption(Option.builder("G").longOpt("no-opengl")
            .desc(Application.getString(this, "option.noOpenGL")).build());
    log.finer("Options set up");

    // parse the command line
    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, Parameters.arguments);
    } catch (final Exception exception) {
        usage();
        error();
    }
    log.finer("Command line parsed");

    // load default snapshot if exists
    boolean success = false;
    for (String name : DEFAULT_SNAPSHOT_NAMES) {
        final File defaultSnapshot = new File(name);
        if (defaultSnapshot.canRead()) {
            try {
                new Snapshot(hardware).read(defaultSnapshot);
            } catch (final RuntimeException exception) {
                log.fine("Error reading default snapshot");
                System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                error();
            }
            log.fine("Default snapshot read from the current directory");
            success = true;
            break;
        }
    }
    if (!success) {
        for (String name : DEFAULT_SNAPSHOT_NAMES) {
            final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name);
            if (defaultSnapshot.canRead()) {
                try {
                    new Snapshot(hardware).read(defaultSnapshot);
                } catch (final Exception exception) {
                    log.fine("Error reading default snapshot");
                    System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                    error();
                }
                log.fine("Default snapshot read from the user's home directory");
                break;
            }
        }
    }
    log.finer("Default files processed");

    // process the options
    if (!line.getArgList().isEmpty()) {
        usage();
        error();
    }
    if (line.hasOption("?")) {
        log.finer("Processing -?");
        usage();
        System.exit(0);
    }
    if (line.hasOption("V")) {
        log.finer("Processing -V");
        System.out.println(Application.getString(this, "longAppName") + " "
                + Application.getString(this, "version") + " @VERSION@");
        System.exit(0);
    }
    try {
        for (Option option : line.getOptions()) {
            switch (option.getOpt()) {
            case "l":
                log.finer("Processing -l");
                final String language = option.getValue();
                if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) {
                    System.out.println(Application.getString(this, "error.unsupportedLanguage"));
                    error();
                }
                UserPreferences.setLocale(language);
                break;
            case "p":
                log.finer("Processing -p");
                final int pixelSize = Integer.parseInt(option.getValue());
                if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) {
                    System.out.println(Application.getString(this, "error.unsupportedPixelSize"));
                    error();
                }
                UserPreferences.setPixelSize(pixelSize);
                break;
            case "o":
                log.finer("Processing -o");
                fileNameROM = option.getValue();
                break;
            case "a":
                log.finer("Processing -a");
                int address = Integer.parseInt(option.getValue(), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                Parameters.cpu.setPC(address);
                break;
            case "b":
                log.finer("Processing -b");
                File file = new File(option.getValue(0));
                address = Integer.parseInt(option.getValue(1), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address);
                break;
            case "h":
                log.finer("Processing -h");
                file = new File(option.getValue());
                new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "x":
                log.finer("Processing -x");
                file = new File(option.getValue());
                new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "s":
                log.finer("Processing -s");
                file = new File(option.getValue());
                new Snapshot(hardware).read(file);
                break;
            case "w":
                log.finer("Processing -w");
                file = new File(option.getValue());
                new Snapshot(hardware).write(file);
                System.exit(0);
                break;
            case "S":
                log.finer("Processing -S");
                Parameters.speedUp = Integer.parseInt(option.getValue());
                if (Parameters.speedUp < 1) {
                    System.out.println(Application.getString(this, "error.nonPositiveSpeedUp"));
                    error();
                }
                break;
            case "g":
                log.finer("Processing -g");
                Parameters.openGL = true;
                break;
            case "G":
                log.finer("Processing -G");
                Parameters.openGL = false;
                break;
            }
        }
    } catch (final Exception exception) {
        usage();
        error();
    }

    log.fine("New CommandLineProcessor creation completed");
}

From source file:cz.pecina.retro.pmd85.CommandLineProcessor.java

/**
 * Creates an instance of the command line procssor.
 *
 * @param hardware the hardware object to operate on
 *//*  w w w .j av  a 2  s . c o m*/
public CommandLineProcessor(final Hardware hardware) {
    log.fine("New CommandLineProcessor creation started");
    this.hardware = hardware;

    // build options
    log.fine("Building options");
    options.addOption(
            Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build());
    options.addOption(
            Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build());
    options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE")
            .desc(Application.getString(this, "option.language")).build());
    options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE")
            .desc(Application.getString(this, "option.pixelSize")).build());
    options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR")
            .desc(Application.getString(this, "option.address")).build());
    options.addOption(Option.builder("o").longOpt("ROM-file").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.ROM")).build());
    options.addOption(Option.builder("m").longOpt("RMM-file").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.RMM")).build());
    options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR")
            .valueSeparator(',').desc(Application.getString(this, "option.binary")).build());
    options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.intelHex")).build());
    options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.xml")).build());
    options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.snapshot")).build());
    options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.writeSnapshot")).build());
    options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR")
            .desc(Application.getString(this, "option.speedUp")).build());
    options.addOption(
            Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build());
    options.addOption(Option.builder("G").longOpt("no-opengl")
            .desc(Application.getString(this, "option.noOpenGL")).build());
    log.finer("Options set up");

    // parse the command line
    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, Parameters.arguments);
    } catch (final Exception exception) {
        usage();
        error();
    }
    log.finer("Command line parsed");

    // load default snapshot if exists
    boolean success = false;
    for (String name : DEFAULT_SNAPSHOT_NAMES) {
        final File defaultSnapshot = new File(name);
        if (defaultSnapshot.canRead()) {
            try {
                new Snapshot(hardware).read(defaultSnapshot);
            } catch (final RuntimeException exception) {
                log.fine("Error reading default snapshot");
                System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                error();
            }
            log.fine("Default snapshot read from the current directory");
            success = true;
            break;
        }
    }
    if (!success) {
        for (String name : DEFAULT_SNAPSHOT_NAMES) {
            final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name);
            if (defaultSnapshot.canRead()) {
                try {
                    new Snapshot(hardware).read(defaultSnapshot);
                } catch (final Exception exception) {
                    log.fine("Error reading default snapshot");
                    System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                    error();
                }
                log.fine("Default snapshot read from the user's home directory");
                break;
            }
        }
    }
    log.finer("Default files processed");

    // process the options
    if (!line.getArgList().isEmpty()) {
        usage();
        error();
    }
    if (line.hasOption("?")) {
        log.finer("Processing -?");
        usage();
        System.exit(0);
    }
    if (line.hasOption("V")) {
        log.finer("Processing -V");
        System.out.println(Application.getString(this, "longAppName") + " "
                + Application.getString(this, "version") + " @VERSION@");
        System.exit(0);
    }
    try {
        for (Option option : line.getOptions()) {
            switch (option.getOpt()) {
            case "l":
                log.finer("Processing -l");
                final String language = option.getValue();
                if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) {
                    System.out.println(Application.getString(this, "error.unsupportedLanguage"));
                    error();
                }
                UserPreferences.setLocale(language);
                break;
            case "p":
                log.finer("Processing -p");
                final int pixelSize = Integer.parseInt(option.getValue());
                if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) {
                    System.out.println(Application.getString(this, "error.unsupportedPixelSize"));
                    error();
                }
                UserPreferences.setPixelSize(pixelSize);
                break;
            case "o":
                log.finer("Processing -o");
                fileNameROM = option.getValue();
                break;
            case "m":
                log.finer("Processing -m");
                fileNameRMM = option.getValue();
                break;
            case "a":
                log.finer("Processing -a");
                int address = Integer.parseInt(option.getValue(), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                Parameters.cpu.setPC(address);
                break;
            case "b":
                log.finer("Processing -b");
                File file = new File(option.getValue(0));
                address = Integer.parseInt(option.getValue(1), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address);
                break;
            case "h":
                log.finer("Processing -h");
                file = new File(option.getValue());
                new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "x":
                log.finer("Processing -x");
                file = new File(option.getValue());
                new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "s":
                log.finer("Processing -s");
                file = new File(option.getValue());
                new Snapshot(hardware).read(file);
                break;
            case "w":
                log.finer("Processing -w");
                file = new File(option.getValue());
                new Snapshot(hardware).write(file);
                System.exit(0);
                break;
            case "S":
                log.finer("Processing -S");
                Parameters.speedUp = Integer.parseInt(option.getValue());
                if (Parameters.speedUp < 1) {
                    System.out.println(Application.getString(this, "error.nonPositiveSpeedUp"));
                    error();
                }
                break;
            case "g":
                log.finer("Processing -g");
                Parameters.openGL = true;
                break;
            case "G":
                log.finer("Processing -G");
                Parameters.openGL = false;
                break;
            }
        }
    } catch (final Exception exception) {
        usage();
        error();
    }

    log.fine("New CommandLineProcessor creation completed");
}

From source file:cz.pecina.retro.pmi80.CommandLineProcessor.java

/**
 * Creates an instance of the command line procssor.
 *
 * @param hardware the hardware object to operate on
 */// w  w  w . jav  a 2s.  c  o  m
public CommandLineProcessor(final Hardware hardware) {
    log.fine("New CommandLineProcessor creation started");
    this.hardware = hardware;

    // build options
    log.fine("Building options");
    options.addOption(
            Option.builder("?").longOpt("help").desc(Application.getString(this, "option.help")).build());
    options.addOption(
            Option.builder("V").longOpt("version").desc(Application.getString(this, "option.version")).build());
    options.addOption(Option.builder("l").longOpt("language").hasArg().argName("CODE")
            .desc(Application.getString(this, "option.language")).build());
    options.addOption(Option.builder("p").longOpt("pixel-size").hasArg().argName("SIZE")
            .desc(Application.getString(this, "option.pixelSize")).build());
    options.addOption(Option.builder("a").longOpt("address").hasArg().argName("ADDR")
            .desc(Application.getString(this, "option.address")).build());
    options.addOption(Option.builder("O").longOpt("start-rom").hasArg().argName("ADDR")
            .desc(Application.getString(this, "option.startRom")).build());
    options.addOption(Option.builder("A").longOpt("start-ram").hasArg().argName("ADDR")
            .desc(Application.getString(this, "option.startRam")).build());
    options.addOption(Option.builder("b").longOpt("binary").hasArgs().numberOfArgs(2).argName("FILE>,<ADDR")
            .valueSeparator(',').desc(Application.getString(this, "option.binary")).build());
    options.addOption(Option.builder("h").longOpt("intel-hex").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.intelHex")).build());
    options.addOption(Option.builder("x").longOpt("xml").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.xml")).build());
    options.addOption(Option.builder("s").longOpt("snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.snapshot")).build());
    options.addOption(Option.builder("w").longOpt("write-snapshot").hasArg().argName("FILE")
            .desc(Application.getString(this, "option.writeSnapshot")).build());
    options.addOption(Option.builder("S").longOpt("speed-up").hasArg().argName("FACTOR")
            .desc(Application.getString(this, "option.speedUp")).build());
    options.addOption(
            Option.builder("g").longOpt("opengl").desc(Application.getString(this, "option.openGL")).build());
    options.addOption(Option.builder("G").longOpt("no-opengl")
            .desc(Application.getString(this, "option.noOpenGL")).build());
    log.finer("Options set up");

    // parse the command line
    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, Parameters.arguments);
    } catch (final Exception exception) {
        usage();
        error();
    }
    log.finer("Command line parsed");

    // load default snapshot if exists
    boolean success = false;
    for (String name : DEFAULT_SNAPSHOT_NAMES) {
        final File defaultSnapshot = new File(name);
        if (defaultSnapshot.canRead()) {
            try {
                new Snapshot(hardware).read(defaultSnapshot);
            } catch (final Exception exception) {
                log.fine("Error reading default snapshot");
                System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                error();
            }
            log.fine("Default snapshot read from the current directory");
            success = true;
            break;
        }
    }
    if (!success) {
        for (String name : DEFAULT_SNAPSHOT_NAMES) {
            final File defaultSnapshot = new File(new File(System.getProperty("user.home")), name);
            if (defaultSnapshot.canRead()) {
                try {
                    new Snapshot(hardware).read(defaultSnapshot);
                } catch (final RuntimeException exception) {
                    log.fine("Error reading default snapshot");
                    System.out.println(Application.getString(this, "error.errorDefaultShapshot"));
                    error();
                }
                log.fine("Default snapshot read from the user's home directory");
                break;
            }
        }
    }
    log.finer("Default files processed");

    // process the options
    if (!line.getArgList().isEmpty()) {
        usage();
        error();
    }
    if (line.hasOption("?")) {
        log.finer("Processing -?");
        usage();
        System.exit(0);
    }
    if (line.hasOption("V")) {
        log.finer("Processing -V");
        System.out.println(Application.getString(this, "longAppName") + " "
                + Application.getString(this, "version") + " @VERSION@");
        System.exit(0);
    }
    try {
        for (Option option : line.getOptions()) {
            switch (option.getOpt()) {
            case "l":
                log.finer("Processing -l");
                final String language = option.getValue();
                if (!Arrays.asList(GeneralConstants.SUPPORTED_LOCALES).contains(language)) {
                    System.out.println(Application.getString(this, "error.unsupportedLanguage"));
                    error();
                }
                UserPreferences.setLocale(language);
                break;
            case "p":
                log.finer("Processing -p");
                final int pixelSize = Integer.parseInt(option.getValue());
                if (!Arrays.asList(GeneralConstants.PIXEL_SIZES).contains(pixelSize)) {
                    System.out.println(Application.getString(this, "error.unsupportedPixelSize"));
                    error();
                }
                UserPreferences.setPixelSize(pixelSize);
                break;
            case "a":
                log.finer("Processing -a");
                int address = Integer.parseInt(option.getValue(), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                Parameters.cpu.setPC(address);
                break;
            case "O":
                log.finer("Processing -O");
                final int startROM = Integer.parseInt(option.getValue());
                if ((startROM < 0) || (startROM > 64)) {
                    System.out.println(Application.getString(this, "error.unsupportedMemoryStart"));
                    error();
                }
                UserPreferences.setStartROM(startROM);
                break;
            case "A":
                log.finer("Processing -A");
                final int startRAM = Integer.parseInt(option.getValue());
                if ((startRAM < 0) || (startRAM > 64)) {
                    System.out.println(Application.getString(this, "error.unsupportedMemoryStart"));
                    error();
                }
                UserPreferences.setStartRAM(startRAM);
                break;
            case "b":
                log.finer("Processing -b");
                File file = new File(option.getValue(0));
                address = Integer.parseInt(option.getValue(1), 16);
                if ((address < 0) || (address >= 0x10000)) {
                    System.out.println(Application.getString(this, "error.invalidAddress"));
                    error();
                }
                new Raw(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file, address);
                break;
            case "h":
                log.finer("Processing -h");
                file = new File(option.getValue());
                new IntelHEX(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "x":
                log.finer("Processing -x");
                file = new File(option.getValue());
                new XML(hardware, DEFAULT_BANK, DEFAULT_BANK).read(file);
                break;
            case "s":
                log.finer("Processing -s");
                file = new File(option.getValue());
                new Snapshot(hardware).read(file);
                break;
            case "w":
                log.finer("Processing -w");
                file = new File(option.getValue());
                new Snapshot(hardware).write(file);
                System.exit(0);
                break;
            case "S":
                log.finer("Processing -S");
                Parameters.speedUp = Integer.parseInt(option.getValue());
                if (Parameters.speedUp < 1) {
                    System.out.println(Application.getString(this, "error.nonPositiveSpeedUp"));
                    error();
                }
                break;
            case "g":
                log.finer("Processing -g");
                Parameters.openGL = true;
                break;
            case "G":
                log.finer("Processing -G");
                Parameters.openGL = false;
                break;
            }
        }
    } catch (final Exception exception) {
        usage();
        error();
    }

    log.fine("New CommandLineProcessor creation completed");
}

From source file:com.cedarsoft.codegen.GeneratorCliSupport.java

public void run(@Nonnull String[] args) throws Exception {
    try {/* w  w  w.  j  a v a  2s . c o  m*/
        Options options = buildOptions();
        CommandLine commandLine;
        try {
            commandLine = new GnuParser().parse(options, args);
        } catch (MissingOptionException e) {
            printError(options, e.getMessage());
            return;
        }

        if (commandLine.hasOption(HELP_OPTION)) {
            printHelp(options);
            return;
        }

        File destination = new File(commandLine.getOptionValue(OPTION_DESTINATION));
        if (!destination.isDirectory()) {
            printError(options, "Destination <" + destination.getAbsolutePath() + "> is not a directory");
            return;
        }

        String resourceDestValue = commandLine.getOptionValue(OPTION_RESOURCES_DESTINATION);
        File resourcesDestination;
        if (resourceDestValue == null) {
            resourcesDestination = destination;
        } else {
            resourcesDestination = new File(resourceDestValue);
        }
        if (!resourcesDestination.isDirectory()) {
            printError(options, "Resources destination <" + resourcesDestination.getAbsolutePath()
                    + "> is not a directory");
            return;
        }

        File testDestination = new File(commandLine.getOptionValue(OPTION_TEST_DESTINATION));
        if (!testDestination.isDirectory()) {
            printError(options,
                    "Test destination <" + testDestination.getAbsolutePath() + "> is not a directory");
            return;
        }

        String testResourcesDestValue = commandLine.getOptionValue(OPTION_TEST_RESOURCES_DESTINATION);
        File testResourcesDestination;
        if (testResourcesDestValue == null) {
            testResourcesDestination = testDestination;
        } else {
            testResourcesDestination = new File(testResourcesDestValue);
        }
        if (!testResourcesDestination.isDirectory()) {
            printError(options, "Test resources destination <" + testResourcesDestination.getAbsolutePath()
                    + "> is not a directory");
            return;
        }

        List<? extends String> domainObjectNames = commandLine.getArgList();
        if (domainObjectNames.isEmpty()) {
            printError(options, "Missing class");
            return;
        }

        List<File> domainSourceFiles = new ArrayList<File>();
        for (String domainObjectName : domainObjectNames) {
            File domainSourceFile = new File(domainObjectName);
            if (!domainSourceFile.isFile()) {
                printError(options, "No source file found at <" + domainSourceFile.getAbsolutePath() + ">");
                return;
            }
            domainSourceFiles.add(domainSourceFile);
        }

        generator.run(domainSourceFiles, destination, resourcesDestination, testDestination,
                testResourcesDestination, null, logOut);
    } finally {
        logOut.flush();
        logOut.close();
    }
}