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

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

Introduction

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

Prototype

public String getOptionValue(char opt) 

Source Link

Document

Retrieve the argument, if any, of this option.

Usage

From source file:com.osrdata.etltoolbox.fileloader.Main.java

/**
 * Main entry point into the application.
 * @param args command line argunemtns/* w w w .  j av a2s  .  c  o  m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("s", "spec", true, "Source-to-target specification file"));
    options.addOption(new Option("d", "directory", true, "Source directory to load"));
    options.addOption(new Option("f", "file", true, "File to perform operation on"));
    options.addOption(new Option("r", "replace", false, "Replace previously loaded data"));
    options.addOption(new Option("t", "trace", true, "Trace records processed at specified interval"));

    CommandLineParser parser = new BasicParser();

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

        if (line.hasOption("spec") && (line.hasOption("directory") || line.hasOption("file"))) {
            FileLoader loader = new FileLoader(line);

            loader.init();

            if (line.hasOption("file")) {
                loader.load(new File(line.getOptionValue("file")));
            } else if (line.hasOption("directory")) {
                File directory = new File(line.getOptionValue("directory"));

                if (directory.isDirectory()) {
                    File[] files = directory.listFiles();

                    for (File file : files) {
                        loader.load(file);
                    }
                } else {
                    log.fatal(directory.getAbsolutePath() + " does not appear to be a directory.");
                }
            }
        } else {
            usage();
        }
    } catch (ParseException e) {
        usage();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.rover12421.shaka.cli.Main.java

public static void main(String[] args) throws Exception {
    boolean smali = false;
    boolean baksmali = false;

    String[] realyArgs = args;//from  w  ww .  ja  v a 2  s  .  c  o m

    if (args.length > 0) {
        String cmd = args[0];
        if (cmd.equalsIgnoreCase("s") || cmd.equalsIgnoreCase("smali")) {
            smali = true;
        } else if (cmd.equalsIgnoreCase("bs") || cmd.equalsIgnoreCase("baksmali")) {
            baksmali = true;
        }

        if (smali || baksmali) {
            realyArgs = new String[args.length - 1];
            System.arraycopy(args, 1, realyArgs, 0, realyArgs.length);
        }
    }

    // cli parser
    CommandLineParser parser = new IgnoreUnkownArgsPosixParser();
    CommandLine commandLine;

    Option language = CommandLineArgEnum.LANGUAGE.getOption();

    Options options = new Options();
    options.addOption(language);

    try {
        commandLine = parser.parse(options, args, false);
        if (CommandLineArgEnum.LANGUAGE.hasMatch(commandLine)) {
            String lngStr = commandLine.getOptionValue(CommandLineArgEnum.LANGUAGE.getOpt());
            Locale locale = Locale.forLanguageTag(lngStr);
            if (locale.toString().isEmpty()) {
                lngStr = lngStr.replaceAll("_", "-");
                locale = Locale.forLanguageTag(lngStr);
            }
            MultiLanguageSupport.getInstance().setLang(locale);
        }
    } catch (Exception ex) {
    }

    if (smali) {
        smaliMainAj.setHookMain(ApktoolMainAj.getHookMain());
        org.jf.smali.main.main(realyArgs);
    } else if (baksmali) {
        baksmaliMainAj.setHookMain(ApktoolMainAj.getHookMain());
        org.jf.baksmali.main.main(realyArgs);
    } else {
        brut.apktool.Main.main(realyArgs);
    }
}

From source file:de.uni_koblenz.jgralab.utilities.converter.TGraphToTGraph2Converter.java

/**
 * Uses the apache cli interface for command line handling.
 * //from ww  w  .j  a  v  a  2 s . co  m
 * @param args
 *            the command line parameters
 */
public static void main(String[] args) {
    CommandLine cmdl = processCommandLineOptions(args);
    try {

        String inputFilename = cmdl.hasOption('i') ? cmdl.getOptionValue('i') : null;
        String outputFilename = cmdl.hasOption('o') ? cmdl.getOptionValue('o') : null;
        boolean loadSchema = outputFilename != null && cmdl.hasOption('l');

        String tempFilename = outputFilename != null
                ? outputFilename + "~" + Long.toString(System.currentTimeMillis())
                : null;

        File inputFile = inputFilename != null ? new File(inputFilename) : null;
        File tempFile = tempFilename != null ? new File(tempFilename) : null;
        File outputFile = outputFilename != null ? new File(outputFilename) : null;

        InputStream in = inputFile != null ? new FileInputStream(inputFile) : System.in;

        OutputStream out = tempFilename != null ? new FileOutputStream(tempFile) : System.out;

        TGraphToTGraph2Converter converter = new TGraphToTGraph2Converter();
        converter.convertTGStream(out, in);

        if (!tempFile.renameTo(outputFile)) {
            System.err.println("Warning: temporary file could not be moved to\n" + outputFile.getAbsolutePath()
                    + "\nit can be found at\n" + tempFile.getAbsolutePath());
        }

        System.out.println("Fini.");
        if (loadSchema) {
            loadConvertedSchema(outputFilename);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.genentech.chemistry.openEye.apps.SDFCatsIndexer.java

/**
 * @param args//from  www. j ava  2 s.  c o  m
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_NORMALIZATION, true,
            "Normalization method: Counts|CountsPerAtom|CountsPerFeature(def) multiple allowed");
    opt.setArgName("meth");
    options.addOption(opt);

    opt = new Option(OPT_PRINTDESC, false,
            "Causes the descriptor for describing each linear path in a molceule to be created");
    options.addOption(opt);

    opt = new Option(OPT_RGROUPTYPES, false, "treat RGroup attachement point ([U]) as atom type.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    AtomTyperInterface[] myTypes = CATSIndexer.typers;
    String tagPrefix = "";
    if (cmd.hasOption(OPT_RGROUPTYPES)) {
        myTypes = CATSIndexer.rgroupTypers;
        tagPrefix = "RG";
    }

    if (cmd.hasOption(OPT_PRINTDESC)) {
        SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
        sdfIndexer.printDescriptors(inFile, outFile);
        sdfIndexer.close();
        return;
    }

    EnumSet<Normalization> normMeth = EnumSet.noneOf(Normalization.class);
    if (cmd.hasOption(OPT_NORMALIZATION))
        for (String n : cmd.getOptionValues(OPT_NORMALIZATION))
            normMeth.add(Normalization.valueOf(n));
    else
        normMeth.add(Normalization.CountsPerFeature);

    SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
    sdfIndexer.run(inFile, outFile, normMeth);
    sdfIndexer.close();
}

From source file:com.ibm.crail.storage.StorageServer.java

public static void main(String[] args) throws Exception {
    Logger LOG = CrailUtils.getLogger();
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);
    CrailConstants.printConf();/*www . j  a va  2 s . co  m*/
    CrailConstants.verify();

    int splitIndex = 0;
    for (String param : args) {
        if (param.equalsIgnoreCase("--")) {
            break;
        }
        splitIndex++;
    }

    //default values
    StringTokenizer tokenizer = new StringTokenizer(CrailConstants.STORAGE_TYPES, ",");
    if (!tokenizer.hasMoreTokens()) {
        throw new Exception("No storage types defined!");
    }
    String storageName = tokenizer.nextToken();
    int storageType = 0;
    HashMap<String, Integer> storageTypes = new HashMap<String, Integer>();
    storageTypes.put(storageName, storageType);
    for (int type = 1; tokenizer.hasMoreElements(); type++) {
        String name = tokenizer.nextToken();
        storageTypes.put(name, type);
    }
    int storageClass = -1;

    //custom values
    if (args != null) {
        Option typeOption = Option.builder("t").desc("storage type to start").hasArg().build();
        Option classOption = Option.builder("c").desc("storage class the server will attach to").hasArg()
                .build();
        Options options = new Options();
        options.addOption(typeOption);
        options.addOption(classOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, splitIndex));
            if (line.hasOption(typeOption.getOpt())) {
                storageName = line.getOptionValue(typeOption.getOpt());
                storageType = storageTypes.get(storageName).intValue();
            }
            if (line.hasOption(classOption.getOpt())) {
                storageClass = Integer.parseInt(line.getOptionValue(classOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Storage tier", options);
            System.exit(-1);
        }
    }
    if (storageClass < 0) {
        storageClass = storageType;
    }

    StorageTier storageTier = StorageTier.createInstance(storageName);
    if (storageTier == null) {
        throw new Exception("Cannot instantiate datanode of type " + storageName);
    }

    String extraParams[] = null;
    splitIndex++;
    if (args.length > splitIndex) {
        extraParams = new String[args.length - splitIndex];
        for (int i = splitIndex; i < args.length; i++) {
            extraParams[i - splitIndex] = args[i];
        }
    }
    storageTier.init(conf, extraParams);
    storageTier.printConf(LOG);

    RpcClient rpcClient = RpcClient.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcClient.init(conf, args);
    rpcClient.printConf(LOG);

    ConcurrentLinkedQueue<InetSocketAddress> namenodeList = CrailUtils.getNameNodeList();
    ConcurrentLinkedQueue<RpcConnection> connectionList = new ConcurrentLinkedQueue<RpcConnection>();
    while (!namenodeList.isEmpty()) {
        InetSocketAddress address = namenodeList.poll();
        RpcConnection connection = rpcClient.connect(address);
        connectionList.add(connection);
    }
    RpcConnection rpcConnection = connectionList.peek();
    if (connectionList.size() > 1) {
        rpcConnection = new RpcDispatcher(connectionList);
    }
    LOG.info("connected to namenode(s) " + rpcConnection.toString());

    StorageServer server = storageTier.launchServer();
    StorageRpcClient storageRpc = new StorageRpcClient(storageType, CrailStorageClass.get(storageClass),
            server.getAddress(), rpcConnection);

    HashMap<Long, Long> blockCount = new HashMap<Long, Long>();
    long sumCount = 0;
    while (server.isAlive()) {
        StorageResource resource = server.allocateResource();
        if (resource == null) {
            break;
        } else {
            storageRpc.setBlock(resource.getAddress(), resource.getLength(), resource.getKey());
            DataNodeStatistics stats = storageRpc.getDataNode();
            long newCount = stats.getFreeBlockCount();
            long serviceId = stats.getServiceId();

            long oldCount = 0;
            if (blockCount.containsKey(serviceId)) {
                oldCount = blockCount.get(serviceId);
            }
            long diffCount = newCount - oldCount;
            blockCount.put(serviceId, newCount);
            sumCount += diffCount;
            LOG.info("datanode statistics, freeBlocks " + sumCount);
        }
    }

    while (server.isAlive()) {
        DataNodeStatistics stats = storageRpc.getDataNode();
        long newCount = stats.getFreeBlockCount();
        long serviceId = stats.getServiceId();

        long oldCount = 0;
        if (blockCount.containsKey(serviceId)) {
            oldCount = blockCount.get(serviceId);
        }
        long diffCount = newCount - oldCount;
        blockCount.put(serviceId, newCount);
        sumCount += diffCount;

        LOG.info("datanode statistics, freeBlocks " + sumCount);
        Thread.sleep(2000);
    }
}

From source file:com.zimbra.cs.mailbox.calendar.FixCalendarTZUtil.java

public static void main(String[] args) {
    CliUtil.toolSetup();/*from  w  w w  .jav  a2s .  c  o m*/
    FixCalendarTZUtil util = null;
    try {
        util = new FixCalendarTZUtil();
    } catch (ServiceException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    try {
        CommandLine cl = util.getCommandLine(args);
        if (cl == null)
            return;
        if (!cl.hasOption(O_RULEFILE))
            throw new ParseException("Missing required option --" + O_RULEFILE);
        String after = null;
        if (cl.hasOption(O_AFTER))
            after = cl.getOptionValue(O_AFTER);

        util.doit(getZAuthToken(cl), cl.getOptionValue(O_RULEFILE), cl.getOptionValues(O_ACCOUNT), after,
                cl.hasOption(O_SYNC));
        System.exit(0);
    } catch (ParseException e) {
        util.usage(e);
    } catch (Exception e) {
        System.err.println("Error occurred: " + e.getMessage());
        util.usage(null);
    }
    System.exit(1);
}

From source file:edu.msu.cme.rdp.classifier.train.validation.distance.PairwiseSeqDistance.java

/**
* This program does the pairwise alignment between each pair of sequences, 
* reports a summary of the average distances and the stdev at each rank.
* @param args/*from  w w w  .j a v a2  s  .c om*/
* @throws Exception 
*/
public static void main(String[] args) throws Exception {

    String trainseqFile = null;
    String taxFile = null;
    PrintStream outStream = null;
    AlignmentMode mode = AlignmentMode.overlap;
    boolean show_alignment = false;

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

        if (line.hasOption("show_alignment")) {
            show_alignment = true;
        }
        if (line.hasOption("alignment-mode")) {
            String m = line.getOptionValue("alignment-mode").toLowerCase();
            mode = AlignmentMode.valueOf(m);

        }

        if (args.length != 3) {
            throw new Exception("wrong arguments");
        }
        args = line.getArgs();
        trainseqFile = args[0];
        taxFile = args[1];
        outStream = new PrintStream(new File(args[2]));
    } catch (Exception e) {
        System.err.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] trainseqFile taxonFile outFile", "", options, "");
        return;
    }

    PairwiseSeqDistance theObj = new PairwiseSeqDistance(trainseqFile, taxFile, mode, show_alignment);

    theObj.printSummary(outStream);
}

From source file:Dcm2Txt.java

public static void main(String[] args) {
    CommandLine cl = parse(args);
    Dcm2Txt dcm2txt = new Dcm2Txt();
    dcm2txt.setWithNames(!cl.hasOption("c"));
    if (cl.hasOption("w"))
        dcm2txt.setMaxWidth(parseInt(cl.getOptionValue("w"), "w", MIN_MAX_WIDTH, MAX_MAX_WIDTH));
    if (cl.hasOption("l"))
        dcm2txt.setMaxValLen(parseInt(cl.getOptionValue("l"), "l", MIN_MAX_VAL_LEN, MAX_MAX_VAL_LEN));
    File ifile = new File((String) cl.getArgList().get(0));
    try {//from  www. ja  v  a2 s. c o  m
        dcm2txt.dump(ifile);
    } catch (IOException e) {
        System.err.println("dcm2txt: Failed to dump " + ifile + ": " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:edu.usc.pgroup.floe.client.commands.Signal.java

/**
 * Entry point for Scale command.//from   w w  w. j  av a 2s.  c om
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option signalOption = OptionBuilder.withArgName("data").hasArg().withType(new String())
            .withDescription("signal data to send to the pellet").create("data");

    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(signalOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

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

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String data = line.getOptionValue("data");

    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("data: {}", data);

    byte[] datab = Utils.serialize(data);
    try {
        TSignal signal = new TSignal();
        signal.set_destApp(app);
        signal.set_destPellet(pellet);
        signal.set_data(datab);
        FloeClient.getInstance().getClient().signal(signal);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:com.aestel.chemistry.openEye.fp.DistMatrix.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.tsv from FingerPrinter]");
    opt.setRequired(true);//  ww  w.ja va  2  s  . c om
    options.addOption(opt);

    opt = new Option("o", true, "outpur file [.tsv ");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0)
        exitWithHelp(options);

    String file = cmd.getOptionValue("i");
    BufferedReader in = new BufferedReader(new FileReader(file));

    file = cmd.getOptionValue("o");
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    ArrayList<Fingerprint> fps = new ArrayList<Fingerprint>();
    ArrayList<String> ids = new ArrayList<String>();
    String line;
    while ((line = in.readLine()) != null) {
        String[] parts = line.split("\t");
        if (parts.length == 3) {
            ids.add(parts[0]);
            fps.add(new ByteFingerprint(parts[2]));
        }
    }
    in.close();

    out.print("ID");
    for (int i = 0; i < ids.size(); i++) {
        out.print('\t');
        out.print(ids.get(i));
    }
    out.println();

    for (int i = 0; i < ids.size(); i++) {
        out.print(ids.get(i));
        Fingerprint fp1 = fps.get(i);

        for (int j = 0; j <= i; j++) {
            out.printf("\t%.4g", fp1.tanimoto(fps.get(j)));
        }
        out.println();
    }
    out.close();

    System.err.printf("Done %d fingerprints in %.2gsec\n", fps.size(),
            (System.currentTimeMillis() - start) / 1000D);
}