Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

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

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:org.cc.smali.main.java

/**
 * Run!//  ww w.  j ava2  s  .  co  m
 */
public static void main(String[] args) {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    int jobs = -1;
    boolean allowOdex = false;
    boolean verboseErrors = false;
    boolean printTokens = false;
    boolean experimental = false;

    int apiLevel = 15;

    String outputDexFile = "out.dex";

    String[] remainingArgs = commandLine.getArgs();

    Option[] options = commandLine.getOptions();

    for (int i = 0; i < options.length; i++) {
        Option option = options[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < options.length) {
                if (options[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            outputDexFile = commandLine.getOptionValue("o");
            break;
        case 'x':
            allowOdex = true;
            break;
        case 'X':
            experimental = true;
            break;
        case 'a':
            apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'V':
            verboseErrors = true;
            break;
        case 'T':
            printTokens = true;
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length == 0) {
        usage();
        return;
    }

    try {
        LinkedHashSet<File> filesToProcess = new LinkedHashSet<File>();

        for (String arg : remainingArgs) {
            File argFile = new File(arg);

            if (!argFile.exists()) {
                throw new RuntimeException("Cannot find file or directory \"" + arg + "\"");
            }

            if (argFile.isDirectory()) {
                getSmaliFilesInDir(argFile, filesToProcess);
            } else if (argFile.isFile()) {
                filesToProcess.add(argFile);
            }
        }

        if (jobs <= 0) {
            jobs = Runtime.getRuntime().availableProcessors();
            if (jobs > 6) {
                jobs = 6;
            }
        }

        boolean errors = false;

        final DexBuilder dexBuilder = DexBuilder.makeDexBuilder(apiLevel);
        ExecutorService executor = Executors.newFixedThreadPool(jobs);
        List<Future<Boolean>> tasks = Lists.newArrayList();

        final boolean finalVerboseErrors = verboseErrors;
        final boolean finalPrintTokens = printTokens;
        final boolean finalAllowOdex = allowOdex;
        final int finalApiLevel = apiLevel;
        final boolean finalExperimental = experimental;
        for (final File file : filesToProcess) {
            tasks.add(executor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return assembleSmaliFile(file, dexBuilder, finalVerboseErrors, finalPrintTokens,
                            finalAllowOdex, finalApiLevel, finalExperimental);
                }
            }));
        }

        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errors = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                }
                break;
            }
        }

        executor.shutdown();

        if (errors) {
            System.exit(1);
        }

        dexBuilder.writeTo(new FileDataStore(new File(outputDexFile)));
    } catch (RuntimeException ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL EXCEPTION:");
        ex.printStackTrace();
        System.exit(2);
    } catch (Throwable ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL ERROR:");
        ex.printStackTrace();
        System.exit(3);
    }
}

From source file:org.crazyt.xgogdownloader.Main.java

public static void main(String[] args) {
    Util util = new Util();
    Config.sVersionString = VERSION_STRING + VERSION_NUMBER;
    Config.sConfigDirectory = "xgogdownloader";
    Config.sCookiePath = "cookies.txt";
    Config.sConfigFilePath = "config.cfg";
    Config.sXMLDirectory = "xgogdownloader/xml";
    // Create xgogdownloader directories
    File path = Factory.newFile(Config.sXMLDirectory);
    if (!path.exists()) {
        if (!path.mkdirs()) {
            System.out.print("Failed to create directory: ");
            System.out.print(path);
            throw new RuntimeException("Failed to create directory. ");
        }/*from   ww  w .j a v a2s  .c  om*/
    }
    path = Factory.newFile(Config.sConfigDirectory);
    if (!path.exists()) {
        if (!path.mkdirs()) {
            System.out.print("Failed to create directory: ");
            System.out.print(path);
            throw new RuntimeException("Failed to create directory. ");
        }
    }
    // Create help text for --platform option
    String platform_text = "Select which installers are downloaded\n";
    int platform_sum = 0;
    for (int i = 0; i < GlobalConstants.PLATFORMS.size(); ++i) {
        platform_text += GlobalConstants.PLATFORMS.get(i).platformId + " = "
                + GlobalConstants.PLATFORMS.get(i).platformString + "\n";
        platform_sum += GlobalConstants.LANGUAGES.get(i).languageId;
    }
    platform_text += platform_sum + " = All";

    // Create help text for --language option
    String language_text = "Select which language installers are downloaded\n";
    int language_sum = 0;
    for (int i = 0; i < GlobalConstants.LANGUAGES.size(); ++i) {
        language_text += GlobalConstants.LANGUAGES.get(i).languageId + " = "
                + GlobalConstants.LANGUAGES.get(i).languageString + "\n";
        language_sum += GlobalConstants.LANGUAGES.get(i).languageId;
    }
    language_text += "Add the values to download multiple languages\nAll = " + language_sum + "\n"
            + "French + Polish = " + GlobalConstants.LANGUAGE_FR + "+" + GlobalConstants.LANGUAGE_PL + " = "
            + GlobalConstants.LANGUAGE_FR + GlobalConstants.LANGUAGE_PL;

    // Create help text for --check-orphans
    String[] orphans_regex_default = new String[] { "zip", "exe", "bin", "dmg", "old" };
    // List<File> files = (List<File>) FileUtils.listFiles(dir, extensions,
    // true);
    String check_orphans_text = "Check for orphaned files (files found on local filesystem that are not found on GOG servers). Sets regular expression filter (Perl syntax) for files to check. If no argument is given then the regex defaults to '"
            + StringUtils.join(orphans_regex_default, ",") + "'";

    CommandOptions options_cli_all = new CommandOptions();
    CommandOptions options_cli_no_cfg = new CommandOptions();
    ConfigOptions options_cli_cfg = new ConfigOptions();
    ConfigOptions options_cfg_only = new ConfigOptions();
    ConfigOptions options_cfg_all = new ConfigOptions();
    try {
        OptionValue<Boolean> bInsecure = new OptionValue<>(false);
        OptionValue<Boolean> bNoColor = new OptionValue<>(false);
        OptionValue<Boolean> bNoUnicode = new OptionValue<>(false);
        OptionValue<Boolean> bNoDuplicateHandler = new OptionValue<>(false);
        OptionValue<Boolean> bNoCover = new OptionValue<>(false);
        OptionValue<Boolean> bNoInstallers = new OptionValue<>(false);
        OptionValue<Boolean> bNoExtras = new OptionValue<>(false);
        OptionValue<Boolean> bNoPatches = new OptionValue<>(false);
        OptionValue<Boolean> bNoLanguagePacks = new OptionValue<>(false);
        OptionValue<Boolean> bNoRemoteXML = new OptionValue<>(false);
        OptionValue<Boolean> bNoSubDirectories = new OptionValue<>(false);

        OptionValue<String> sGame = new OptionValue<>("free");
        OptionValue<String> sToken = new OptionValue<>("");
        OptionValue<String> sSecret = new OptionValue<>("");
        OptionValue<String> sSearch = new OptionValue<>("");
        OptionValue<Boolean> bList = new OptionValue<>(false);
        OptionValue<Boolean> bDownload = new OptionValue<>(false);
        OptionValue<Integer> iDownloadRate = new OptionValue<>(0);

        // //switch to OptionBuilder
        // Commandline options (no config file)
        options_cli_no_cfg.addOption("debug", "d", false, "Print debug messages");
        options_cli_no_cfg.addOption("help", "h", false, "Print help message");
        options_cli_no_cfg.addOption("version", false, "Print version information");
        options_cli_no_cfg.addOption("versionUpdate", false, "Updates this program to the current version.");
        options_cli_no_cfg.addOption("login", true, "Login");
        // config.bLogin false
        options_cli_no_cfg.addOption(bList, "list", false, "List games");
        // config.bList false
        options_cli_no_cfg.addOption(sSearch, "search", true, "search games by title");
        options_cli_no_cfg.addOption("listdetails", "list-details", true, "List games with detailed info"); // config.bListDetails
        // false
        options_cli_no_cfg.addOption(bDownload, "download", false, "Download");
        // config.bDownload false
        options_cli_no_cfg.addOption("repair", true,
                "Repair downloaded files\nUse --repair --download to redownload files when filesizes don't match (possibly different version). Redownload will delete the old file"); // config.bRepair
        // false
        options_cli_no_cfg.addOption("game", true,
                "Set regular expression filter\nfor download/list/repair (Perl syntax)\nAliases: \"all\", \"free\""); // config.sGameRegex
        // ""
        options_cli_no_cfg.addOption("createxml", "create-xml", true,
                "Create GOG XML for file\n\"automatic\" to enable automatic XML creation"); // config.sXMLFile
        // ""
        options_cli_no_cfg.addOption("updatecheck", "update-check", true, "Check for update notifications");
        // config.bUpdateCheck false

        options_cli_no_cfg.addOption("checkorphans", "check-orphans", true, check_orphans_text);
        // config.sOrphanRegex ""

        options_cli_no_cfg.addOption("status", true,
                "Show status of files\n\nOutput format:\nstatuscode gamename filename filesize filehash\n\nStatus codes:\nOK - File is OK\nND - File is not downloaded\nMD5 - MD5 mismatch, different version");// config.bCheckStatus
        // false
        options_cli_no_cfg.addOption("saveconfig", "save-config", true,
                "Create config file with current settings");
        // config.bSaveConfig false

        options_cli_no_cfg.addOption("resetconfig", "reset-config", true, "Reset config settings to default");
        // config.bResetConfig false

        options_cli_no_cfg.addOption("report", true, "Save report of downloaded/repaired files");
        // config.bReport false

        // Commandline options (config file)
        options_cli_cfg.addOption("directory", true, "Set download directory");
        // config.sDirectory ""

        options_cli_cfg.addOption(iDownloadRate, "limitRate", true,
                "Limit download rate to value in kB\n0 = unlimited");
        // config.iDownloadRate 0

        options_cli_cfg.addOption("xmlDirectory", true, "Set directory for GOG XML files");
        // config.sXMLDirectory ""

        options_cli_cfg.addOption("chunkSize", true, "Chunk size (in MB) when creating XML");
        // config.iChunkSize 10

        options_cli_cfg.addOption("platform", true, platform_text);
        // config.iInstallerType GlobalConstants.PLATFORM_WINDOWS

        options_cli_cfg.addOption("language", true, language_text);
        // config.iInstallerLanguage GlobalConstants.LANGUAGE_EN

        options_cli_cfg.addOption("noInstallers", true, "Don't download/list/repair installers");
        // bNoInstallers false

        options_cli_cfg.addOption("noExtras", true, "Don't download/list/repair extras");
        // bNoExtras false

        options_cli_cfg.addOption("noPatches", true, "Don't download/list/repair patches");
        // bNoPatches false

        options_cli_cfg.addOption("noLanguagePacks", true, "Don't download/list/repair language packs");
        // bNoLanguagePacks false

        options_cli_cfg.addOption("noCover", true, "Don't download cover images");
        // bNoCover false

        options_cli_cfg.addOption("noRemoteXml", true, "Don't use remote XML for repair");
        // bNoRemoteXML false

        options_cli_cfg.addOption(bNoUnicode, "noUnicode", true, "Don't use Unicode in the progress bar");
        // bNoUnicode false

        options_cli_cfg.addOption(bNoColor, "noColor", true, "Don't use coloring in the progress bar");
        // bNoColor false

        options_cli_cfg.addOption("noDuplicateHandling", true,
                "Don't use duplicate handler for installers\nDuplicate installers from different languages are handled separately");// bNoDuplicateHandler
        // false
        options_cli_cfg.addOption("noSubdirectories", true,
                "Don't create subdirectories for extras, patches and language packs");
        // bNoSubDirectories false

        options_cli_cfg.addOption("verbose", true, "Print lots of information");

        options_cli_cfg.addOption("insecure", true, "Don't verify authenticity of SSL certificates");
        // bInsecure false

        options_cli_cfg.addOption("timeout", true,
                "Set timeout for connection\nMaximum time in seconds that connection phase is allowed to take");
        // config.iTimeout 10
        options_cli_cfg.addOption("retries", true, "Set maximum number of retries on failed download");
        // config.iRetries 3

        // Options read from config file
        options_cfg_only.addOption(sToken, "token", true, "oauth token");
        // config.sToken ""

        options_cfg_only.addOption(sSecret, "secret", true, "oauth secret");
        // config.sSecret ""

        options_cli_all.addOptions(options_cli_no_cfg);
        options_cli_all.addOptions(options_cli_cfg);

        options_cfg_all.addOptions(options_cfg_only);
        options_cfg_all.addOptions(options_cli_cfg);

        options_cfg_all.parse(Config.sConfigFilePath);

        // boost.program_options.store(boost.program_options
        // .parse_command_line(argc, args, options_cli_all), vm);

        CommandLineParser parser = new GnuParser();
        String[] args2;
        if (args.length == 0) {
            args2 = new String[] { "-help" };
        } else {
            args2 = args;
        }
        CommandLine cmd = parser.parse(options_cli_all, args2);
        options_cli_all.parseCmdLine(cmd);

        path = Factory.newFile(Config.sConfigDirectory);
        if (path.exists()) {
            Properties prop = new Properties();
            try {
                FileInputStream fileInputStream = new FileInputStream(
                        Config.sConfigDirectory + File.separatorChar + Config.sConfigFilePath);
                try {
                    prop.load(fileInputStream);
                } finally {
                    fileInputStream.close();
                }
            } catch (FileNotFoundException e) {
                System.out.println("Could not open config file: " + Config.sConfigDirectory + File.separatorChar
                        + Config.sConfigFilePath + ", creating new one.");
                Factory.newFile(Config.sConfigDirectory + File.separatorChar + Config.sConfigFilePath)
                        .createNewFile();
            }
        }

        if (cmd.hasOption("help")) {
            System.out.println(Config.sVersionString);
            System.out.println("Options:");
            for (Option option : (Collection<Option>) options_cli_all.getOptions()) {
                System.out.println(String.format("%20s\t-\t%s", option.getOpt(),
                        option.getDescription().replace("\n", String.format("\n%20s\t \t", ""))));
            }
            return;
        }
        if (cmd.hasOption("version")) {
            System.out.print(Config.sVersionString);
            return;
        }
        if (cmd.hasOption("versionUpdate")) {
            String sub = "xgogdownloader-";

            try {
                HttpClient client = Factory.createHttpClient();
                HttpGet request = new HttpGet("https://drone.io/github.com/TheCrazyT/xgogdownloader/files");
                request.setHeader("User-Agent", Main.USER_AGENT);
                HttpResponse response_full = client.execute(request);
                int result = response_full.getStatusLine().getStatusCode();

                if (result != HttpStatus.SC_OK) {
                    System.err.println("Error " + result);
                }
                String response = EntityUtils.toString(response_full.getEntity());
                Document html = Jsoup.parse(response);

                Iterator<org.jsoup.nodes.Element> iterator = html.getElementsByTag("div").iterator();
                while (iterator.hasNext()) {
                    org.jsoup.nodes.Element node = iterator.next();
                    String hash = "";
                    Elements spans = node.getElementsByTag("span");
                    Iterator<org.jsoup.nodes.Element> iterator2 = spans.iterator();
                    while (iterator2.hasNext()) {
                        org.jsoup.nodes.Element span = iterator2.next();
                        if (span.text().startsWith("SHA")) {
                            hash = span.text().substring(4, 44);
                            break;
                        }
                    }
                    if (!hash.isEmpty()) {
                        iterator2 = node.getElementsByTag("a").iterator();
                        while (iterator2.hasNext()) {
                            Element a = iterator2.next();
                            String url = a.attr("href");
                            if (a.text().startsWith(sub) && a.text().endsWith(".zip")) {
                                // TODO
                                System.out.println("... TODO ...");
                                System.out.println(url);
                                return;
                            }
                        }
                    }
                }

                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        if (cmd.hasOption("chunkSize")) {
            Config.iChunkSize <<= 20;
            // Convert chunk size from bytes to megabytes
        }

        if (cmd.hasOption("limitRate")) {
            Config.iDownloadRate = iDownloadRate.getValue();
            Config.iDownloadRate <<= 10;
            // Convert download rate from bytes to kilobytes
        }
        if (cmd.hasOption("check-orphans")) {
            if (Config.sOrphanRegex.isEmpty()) {
                Config.sOrphanRegex = StringUtils.join(orphans_regex_default, "|");
            }
        }

        Config.bDownload = bDownload.getValue();
        Config.sToken = sToken.getValue();
        Config.sSecret = sToken.getValue();
        Config.sSearch = sSearch.getValue();
        Config.sGameRegex = sGame.getValue();
        Config.bList = bList.getValue();

        Config.bVerifyPeer = !bInsecure.getValue();
        Config.bColor = !bNoColor.getValue();
        Config.bUnicode = !bNoUnicode.getValue();
        Config.bDuplicateHandler = !bNoDuplicateHandler.getValue();
        Config.bCover = !bNoCover.getValue();
        Config.bInstallers = !bNoInstallers.getValue();
        Config.bExtras = !bNoExtras.getValue();
        Config.bPatches = !bNoPatches.getValue();
        Config.bLanguagePacks = !bNoLanguagePacks.getValue();
        Config.bRemoteXML = !bNoRemoteXML.getValue();
        Config.bSubDirectories = !bNoSubDirectories.getValue();
    } catch (RuntimeException e) {
        System.err.println("Error: " + e.getMessage());
        throw e;
    } catch (java.lang.Exception e) {
        System.err.println("Exception of unknown type!");
        throw new RuntimeException(e);
    }

    if (Config.iInstallerType < GlobalConstants.PLATFORMS.get(0).platformId
            || Config.iInstallerType > platform_sum) {
        System.out.println("Invalid value for --platform");
        throw new RuntimeException("Invalid value for --platform");
    }

    if (Config.iInstallerLanguage < GlobalConstants.LANGUAGES.get(0).languageId
            || Config.iInstallerLanguage > language_sum) {
        System.out.println("Invalid value for --language");
        throw new RuntimeException("Invalid value for --language");
    }

    if (Config.sXMLDirectory != "") {
        // Make sure that xml directory doesn't have trailing slash
        if (Config.sXMLDirectory.charAt(Config.sXMLDirectory.length() - 1) == '/') {
            // config.sXMLDirectory.assign(config.sXMLDirectory.begin(),config.sXMLDirectory.end()
            // - 1);
        }
    }
    // Create GOG XML for a file
    if ((Config.sXMLFile != null) && !Config.sXMLFile.isEmpty() && !Config.sXMLFile.equals("automatic")) {
        util.createXML(Config.sXMLFile, Config.iChunkSize, Config.sXMLDirectory);
    }
    // Make sure that directory has trailing slash
    // if (Config.sDirectory != null && !Config.sDirectory.isEmpty()) {
    // if (Config.sDirectory.charAt(Config.sDirectory.length() - 1) != '/')
    // {
    // Config.sDirectory += "/";
    // }
    // }
    Downloader downloader = new Downloader();
    boolean result = downloader.init();

    if (Config.bLogin) {
        if (!result) {
            throw new RuntimeException("downloader.init failed");
        }
        return;
    } else if (Config.bSaveConfig) {
        // std.ofstream ofs = new
        // std.ofstream(config.sConfigFilePath.c_str());
        String ofs = null;
        if (ofs != null) {
            System.out.println("Saving config: " + Config.sConfigFilePath);
            /*
             * for (boost.program_options.variables_map.iterator it =
             * vm.begin(); it != vm.end(); ++it) { String option = it.first;
             * String option_value_string;
             * boost.program_options.variable_value option_value =
             * it.second;
             * 
             * try { if (option.equals(options_cfg_all.find(option,
             * false).long_name())) { if (!option_value.empty()) {
             * std.type_info type = option_value.value().type(); if (type ==
             * typeid(String)) { option_value_string =
             * option_value.<String>as(); }
             * 
             * } } } catch (java.lang.Exception e2) { continue; }
             * 
             * if (option_value_string!="") {
             * System.out.println(option+" = "+option_value_string); //ofs
             * << option.compareTo() < 0 < < " = " <<
             * option_value_string.compareTo() < 0 < < std.endl; } }
             * //ofs.close();
             */
        } else {
            System.out.println("Failed to create config: " + Config.sConfigFilePath);
            throw new RuntimeException("Failed to create config: " + Config.sConfigFilePath);
        }
    } else if (Config.bResetConfig) {
        String ofs = null;
        // std.ofstream ofs = new
        // std.ofstream(config.sConfigFilePath.c_str());
        if (ofs != null) {
            /*
             * if (config.sToken!="" && config.sSecret!="") { ofs
             * +="token = " +config.sToken+"\n"; ofs +="secret = "
             * +config.sSecret+"\n"; }
             */
            // ofs.close();
        } else {
            System.out.println("Failed to create config: " + Config.sConfigFilePath);
            throw new RuntimeException("Failed to create config: " + Config.sConfigFilePath);
        }
    } else if (Config.bUpdateCheck) {
        // Update check has priority over download and list
        downloader.updateCheck();
    } else if (Config.bRepair) {
        // Repair file
        downloader.repair();
    } else if ((Config.sSearch != null) && (!Config.sSearch.isEmpty())) {
        // search games
        downloader.searchGames(Config.sSearch);
    } else if (Config.bDownload) {
        // Download games
        downloader.download();
    } else if (Config.bListDetails || Config.bList) {
        // Detailed list of games/extras
        downloader.listGames();
    } else if (Config.sOrphanRegex != null) {
        // Check for orphaned files if regex for orphans is set
        downloader.checkOrphans();
    } else if (Config.bCheckStatus) {
        downloader.checkStatus();
    } else {
        // Show help message
        System.out.println(Config.sVersionString + "" + options_cli_all);
    }

    // Orphan check was called at the same time as download. Perform it
    // after download has finished
    if (Config.sOrphanRegex != null && Config.bDownload) {
        downloader.checkOrphans();
    }
    return;
}

From source file:org.deegree.tools.coverage.TransformRaster.java

/**
 * @param args/*from w w  w .ja va  2 s . co m*/
 */
public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    Option t_srs = new Option("t_srs", "the srs of the target raster");
    t_srs.setRequired(true);
    t_srs.setArgs(1);
    t_srs.setArgName("epsg code");
    options.addOption(t_srs);

    Option s_srs = new Option("s_srs", "the srs of the source raster");
    s_srs.setRequired(true);
    s_srs.setArgs(1);
    s_srs.setArgName("epsg code");
    options.addOption(s_srs);

    Option interpolation = new Option("interpolation",
            "the raster interpolation (nn: nearest neighbour, bl: bilinear");
    interpolation.setArgs(1);
    interpolation.setArgName("nn|bl");
    options.addOption(interpolation);

    Option originLocation = new Option("origin", "originlocation", true,
            "the location of the origin on the upper left pixel (default = center)");
    interpolation.setArgs(1);
    interpolation.setArgName("center|outer");
    options.addOption(originLocation);

    CommandUtils.addDefaultOptions(options);

    // for the moment, using the CLI API there is no way to respond to a help argument; see
    // https://issues.apache.org/jira/browse/CLI-179
    if (args.length == 0 || (args.length > 0 && (args[0].contains("help") || args[0].contains("?")))) {
        printHelp(options);
    }

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

        InterpolationType interpolationType = getInterpolationType(line.getOptionValue(interpolation.getOpt()));
        OriginLocation location = getLocation(line.getOptionValue(originLocation.getOpt()));

        transformRaster(line.getArgs(), line.getOptionValue("s_srs"), line.getOptionValue("t_srs"),
                interpolationType, location);

    } catch (ParseException exp) {
        System.out.println("ERROR: Invalid command line:" + exp.getMessage());
    }
    System.exit(0);
}

From source file:org.eclim.annotation.CommandListingProcessor.java

public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    Options options = new Options();
    Pattern pattern = null;//  www . j  a v  a 2s .  c  o  m
    String filter = this.processingEnv.getOptions().get("filter");
    if (filter != null) {
        pattern = Pattern.compile(filter);
    }
    for (TypeElement element : annotations) {
        for (Element e : env.getElementsAnnotatedWith(element)) {
            Command command = e.getAnnotation(Command.class);
            if (pattern == null || pattern.matcher(command.name()).matches()) {
                Collection<Option> opts = options.parseOptions(command.options());
                System.out.print(command.name());
                for (Option opt : opts) {
                    String display = "-" + opt.getOpt();
                    if (opt.hasArg()) {
                        display += " " + opt.getLongOpt();
                    }
                    if (opt.isRequired()) {
                        System.out.print(" " + display);
                    } else {
                        System.out.print(" [" + display + "]");
                    }
                }
                System.out.println("\n\tclass: " + e);
            }
        }
    }
    return true;
}

From source file:org.eclim.command.CommandLine.java

/**
 * Constructs a new instance from the supplied command line.
 *
 * @param command The command.//  w w  w. j  a v a  2s . c o  m
 * @param commandLine The command line.
 * @param args The orginal command line args.
 */
public CommandLine(Command command, org.apache.commons.cli.CommandLine commandLine, String[] args) {
    this.command = command;
    this.args = args;
    Option[] options = commandLine.getOptions();
    for (Option option : options) {
        if (option.hasArgs()) {
            this.options.put(option.getOpt(), commandLine.getOptionValues(option.getOpt()));
        } else { //if(option.hasArg() || option.hasOptionalArg()){
            this.options.put(option.getOpt(), commandLine.getOptionValue(option.getOpt()));
        }
    }
    unrecognized = commandLine.getArgs();
}

From source file:org.eclim.command.Main.java

public static void usage(String cmd, PrintStream out) {
    ArrayList<org.eclim.annotation.Command> commands = new ArrayList<org.eclim.annotation.Command>();
    for (Class<? extends Command> command : Services.getCommandClasses()) {
        commands.add(command.getAnnotation(org.eclim.annotation.Command.class));
    }//w  w  w . ja va 2  s.co m
    Collections.sort(commands, new Comparator<org.eclim.annotation.Command>() {
        public int compare(org.eclim.annotation.Command o1, org.eclim.annotation.Command o2) {
            return o1.name().compareTo(o2.name());
        }
    });

    boolean cmdFound = cmd == null;
    if (cmd == null) {
        String osOpts = StringUtils.EMPTY;
        if (SystemUtils.IS_OS_UNIX) {
            osOpts = " [-f eclimrc] [--nailgun-port port]";
        }
        out.println("Usage: eclim" + osOpts + " -command command [args]");
        out.println("  To view a full list of available commands:");
        out.println("    eclim -? commands");
        out.println("  To view info for a specific command:");
        out.println("    eclim -? <command_name>");
        out.println("  Ex.");
        out.println("    eclim -? project_create");
    } else if (cmd.equals("commands")) {
        out.println("Available Commands:");
    } else {
        out.println("Requested Command:");
    }

    for (org.eclim.annotation.Command command : commands) {
        if (cmd == null || (!cmd.equals(command.name()) && !cmd.equals("commands"))) {
            continue;
        }
        cmdFound = true;

        Collection<Option> options = new Options().parseOptions(command.options());
        StringBuffer opts = new StringBuffer();
        Iterator<Option> iterator = options.iterator();
        for (int ii = 0; iterator.hasNext(); ii++) {
            Option option = iterator.next();
            opts.append(option.isRequired() ? " " : " [");
            opts.append('-').append(option.getOpt());
            if (option.hasArg()) {
                opts.append(' ').append(option.getLongOpt());
            }
            if (!option.isRequired()) {
                opts.append(']');
            }
            // wrap every 4 options
            if ((ii + 1) % 4 == 0 && ii != options.size() - 1) {
                opts.append(StringUtils.rightPad("\n", command.name().length() + 5));
            }
        }
        StringBuffer info = new StringBuffer().append("    ").append(command.name()).append(opts);
        out.println(info);
        if (!command.description().equals(StringUtils.EMPTY)) {
            out.println("      " + command.description());
        }
    }

    if (!cmdFound) {
        out.println("    No Such Command: " + cmd);
    }
}

From source file:org.eclipse.rdf4j.console.Console.java

public static void main(final String[] args) throws IOException {
    final Console console = new Console();
    final Option helpOption = new Option("h", "help", false, "print this help");
    final Option versionOption = new Option("v", "version", false, "print version information");
    final Option serverURLOption = new Option("s", "serverURL", true,
            "URL of RDF4J Server to connect to, e.g. http://localhost:8080/rdf4j-server/");
    final Option dirOption = new Option("d", "dataDir", true, "data dir to 'connect' to");
    Option echoOption = new Option("e", "echo", false,
            "echoes input back to stdout, useful for logging script sessions");
    Option quietOption = new Option("q", "quiet", false, "suppresses prompts, useful for scripting");
    Option forceOption = new Option("f", "force", false,
            "always answer yes to (suppressed) confirmation prompts");
    Option cautiousOption = new Option("c", "cautious", false,
            "always answer no to (suppressed) confirmation prompts");
    Option exitOnErrorMode = new Option("x", "exitOnError", false,
            "immediately exit the console on the first error");
    final Options options = new Options();
    OptionGroup cautionGroup = new OptionGroup().addOption(cautiousOption).addOption(forceOption)
            .addOption(exitOnErrorMode);
    OptionGroup locationGroup = new OptionGroup().addOption(serverURLOption).addOption(dirOption);
    options.addOptionGroup(locationGroup).addOptionGroup(cautionGroup);
    options.addOption(helpOption).addOption(versionOption).addOption(echoOption).addOption(quietOption);
    CommandLine commandLine = parseCommandLine(args, console, options);
    handleInfoOptions(console, helpOption, versionOption, options, commandLine);
    console.consoleIO.setEcho(commandLine.hasOption(echoOption.getOpt()));
    console.consoleIO.setQuiet(commandLine.hasOption(quietOption.getOpt()));
    exitOnError = commandLine.hasOption(exitOnErrorMode.getOpt());
    String location = handleOptionGroups(console, serverURLOption, dirOption, forceOption, cautiousOption,
            options, cautionGroup, locationGroup, commandLine);
    final String[] otherArgs = commandLine.getArgs();
    if (otherArgs.length > 1) {
        printUsage(console.consoleIO, options);
        System.exit(1);//from w w w  . jav  a 2 s  .  c o  m
    }
    connectAndOpen(console, locationGroup.getSelected(), location, otherArgs);
    console.start();
}

From source file:org.eclipse.rdf4j.console.Console.java

private static String handleOptionGroups(final Console console, final Option serverURLOption,
        final Option dirOption, Option forceOption, Option cautiousOption, final Options options,
        OptionGroup cautionGroup, OptionGroup locationGroup, CommandLine commandLine) {
    String location = null;//w w w  .jav a 2s  .  c  om
    try {
        if (commandLine.hasOption(forceOption.getOpt())) {
            cautionGroup.setSelected(forceOption);
            console.consoleIO.setForce();
        }
        if (commandLine.hasOption(cautiousOption.getOpt())) {
            cautionGroup.setSelected(cautiousOption);
            console.consoleIO.setCautious();
        }
        if (commandLine.hasOption(dirOption.getOpt())) {
            locationGroup.setSelected(dirOption);
            location = commandLine.getOptionValue(dirOption.getOpt());
        }
        if (commandLine.hasOption(serverURLOption.getOpt())) {
            locationGroup.setSelected(serverURLOption);
            location = commandLine.getOptionValue(serverURLOption.getOpt());
        }
    } catch (AlreadySelectedException e) {
        printUsage(console.consoleIO, options);
        System.exit(3);
    }
    return location;
}

From source file:org.eclipse.rdf4j.console.Console.java

private static void handleInfoOptions(final Console console, final Option helpOption,
        final Option versionOption, final Options options, final CommandLine commandLine) {
    if (commandLine.hasOption(helpOption.getOpt())) {
        printUsage(console.consoleIO, options);
        System.exit(0);//  w w  w . jav a2  s  . c o  m
    }
    if (commandLine.hasOption(versionOption.getOpt())) {
        console.consoleIO.writeln(console.appConfig.getFullName());
        System.exit(0);
    }
}

From source file:org.efaps.cli.StartUp.java

/**
 * The main method./*from w w w  . j  av a2  s .  c o m*/
 *
 * @param _args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(final String[] _args) throws IOException {
    LOG.info("Startup at {}", new Date());

    final Options options = new Options()
            .addOption(
                    Option.builder("l").numberOfArgs(2).desc("set login information").longOpt("login").build())
            .addOption(Option.builder("u").numberOfArgs(1).desc("set url").longOpt("url").build())
            .addOption(Option.builder("ll").numberOfArgs(1)
                    .desc("set Log Level, One of 'ALL','TRACE','DEBUG','INFO','WARN','ERROR', 'OFF'")
                    .longOpt("logLevel").build())
            .addOption(Option.builder("h").desc("print this help information").longOpt("help").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine cmd = parser.parse(options, _args);

        if (cmd.hasOption("h")) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("eFaps-CLI", options);
        } else {
            final Shell shell = ShellBuilder.shell("eFaps").behavior()
                    .setHistoryFile(new File(System.getProperty("user.home") + "/.eFapsCLI", "history"))
                    .addHandler(ContextHandler.get()).addHandler(new CommandHandler())
                    .addHandler(new MessageResolver()).addHandler(new EQLHandler())
                    .addHandler(EQLObserver.get()).addHandler(new EQLCandidatesChooser())
                    .addHandler(new EQLFilter()).build();
            shell.setAppName("\"eFaps Command Line Interface\"");

            for (final Option opt : cmd.getOptions()) {
                switch (opt.getOpt()) {
                case "l":
                    shell.getEnvironment().setVariable(CLISettings.USER, opt.getValue(0));
                    shell.getEnvironment().setVariable(CLISettings.PWD, opt.getValue(1));
                    break;
                case "u":
                    shell.getEnvironment().setVariable(CLISettings.URL, opt.getValue());
                    break;
                case "ll":
                    LOG.info("Setting Log level to {}", opt.getValue());
                    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
                            .getLogger(Logger.ROOT_LOGGER_NAME);
                    root.setLevel(Level.toLevel(opt.getValue()));
                    LOG.info("ROOT Log level set to {}", root.getLevel());
                    break;
                default:
                    break;
                }
            }
            shell.processLine("company " + ContextHandler.FAKECOMPANY);
            shell.commandLoop();
        }
    } catch (final ParseException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("eFaps-CLI", options);
        LOG.error("ParseException", e);
    } catch (final CLIException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("eFaps-CLI", options);
        LOG.error("ParseException", e);
    }
}