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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:fr.inria.atlanmod.kyanos.benchmarks.ReferencesCounter.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from   w w  w  .j  a  v a2 s .c  om*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option labelOpt = OptionBuilder.create(LABEL);
    labelOpt.setArgName("LABEL");
    labelOpt.setDescription("Label for the data set");
    labelOpt.setArgs(1);
    labelOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(labelOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        Class<?> inClazz = ReferencesCounter.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);

        FileWriter writer = new FileWriter(new File(commandLine.getOptionValue(OUT)));
        try {
            writer.write(commandLine.getOptionValue(LABEL));
            writer.write("\n");

            for (Iterator<EObject> iterator = sourceResource.getAllContents(); iterator.hasNext();) {
                EObject eObject = iterator.next();
                for (EStructuralFeature feature : eObject.eClass().getEAllStructuralFeatures()) {
                    if (feature.isMany() && eObject.eIsSet(feature)) {
                        EList<?> value = (EList<?>) eObject.eGet(feature);
                        //                     if (value.size() > 10) 
                        writer.write(String.format("%d\n", value.size()));
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(writer);
        }

    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

From source file:com.cloudera.impala.testutil.SentryServiceWrapper.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    // Parse command line options to get config file path.
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config_file")
            .withDescription("Absolute path to a sentry-site.xml config file").hasArg()
            .withArgName("CONFIG_FILE").isRequired().create('c'));
    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    SentryServiceWrapper server = new SentryServiceWrapper(
            new SentryConfig(cmdArgs.getOptionValue("config_file")));
    server.start();//from   w w w.  ja  v a  2s  .  co m
}

From source file:fr.liglab.consgap.Main.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    CommandLineParser parser = new PosixParser();

    options.addOption("s", false, "Sparse: use int lists instead of bitsets to represent positions");
    options.addOption("b", false, "Benchmark mode : sequences are not outputted at all");
    options.addOption("h", false, "Show help");
    options.addOption("w", false,
            "Use breadth first exploration instead of depth first. Usually less efficient.");
    options.addOption("t", true,
            "How many threads will be launched (defaults to your machine's processors count)");
    options.addOption("l", false, "Use lcm style, read dataset to generate candidates");
    options.addOption("f", true,
            "Sequences filtering frequency, expressed in number of outputs. Recommended value is 100, avoids some redundant explorations.");
    options.addOption("sep", true, "separator in the dataset files (defaults to tabulation)");
    try {//from   w  ww.j  a  v  a2s . c  o  m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.getArgs().length != 5 || cmd.hasOption('h')) {
            printMan(options);
        } else {
            standalone(cmd);
        }
    } catch (ParseException e) {
        printMan(options);
    }
}

From source file:ca.uqac.info.trace.conversion.TraceConverter.java

/**
 * Main program loop// www.j  a  v  a2  s  . c o  m
 * @param args Command-line arguments
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // Default values
    String input_format = "xml", output_format = "smv";
    String input_filename = "trace.xml", output_filename = "";
    //String event_tag_name = "Event";

    // Define and process command line arguments
    Options options = new Options();
    HelpFormatter help_formatter = new HelpFormatter();
    Option opt;
    options.addOption("h", "help", false, "Show help");
    opt = OptionBuilder.withArgName("format").hasArg()
            .withDescription("Input format for trace. Accepted values are csv, xml.").create("i");
    opt.setRequired(false);
    options.addOption(opt);
    opt = OptionBuilder.withArgName("format").hasArg().withDescription(
            "Output format for trace. Accepted values are javamop, json, monpoly, smv, sql, xml. Default: smv")
            .create("t");
    opt.setRequired(false);
    options.addOption(opt);
    opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename. Default: trace.xml")
            .create("f");
    opt.setRequired(false);
    options.addOption(opt);
    opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Output filename").create("o");
    opt.setRequired(false);
    options.addOption(opt);
    opt = OptionBuilder.withArgName("name").hasArg().withDescription("Event tag name. Default: Event")
            .create("e");
    opt.setRequired(false);
    options.addOption(opt);
    opt = OptionBuilder.withArgName("formula").hasArg().withDescription("Formula to translate").create("s");
    opt.setRequired(false);
    options.addOption(opt);
    CommandLine c_line = parseCommandLine(options, args);
    if (c_line.hasOption("h")) {
        help_formatter.printHelp(app_name, options);
        System.exit(0);
    }
    input_filename = c_line.getOptionValue("f");
    if (c_line.hasOption("o"))
        output_filename = c_line.getOptionValue("o");
    /*if (c_line.hasOption("e"))
      event_tag_name = c_line.getOptionValue("e");*/

    // Determine the input format
    if (!c_line.hasOption("i")) {
        // Guess output format by filename extension
        input_format = getExtension(input_filename);
    }
    if (c_line.hasOption("i")) {
        // The "t" parameter overrides the filename extension
        input_format = c_line.getOptionValue("i");
    }

    // Determine which trace reader to initialize
    TraceReader reader = initializeReader(input_format);
    if (reader == null) {
        System.err.println("ERROR: Unrecognized input format");
        System.exit(1);
    }

    // Instantiate the proper trace reader and checks that the trace exists
    //reader.setEventTagName(event_tag_name);
    File in_f = new File(input_filename);
    if (!in_f.exists()) {
        System.err.println("ERROR: Input file not found");
        System.exit(1);
    }
    if (!in_f.canRead()) {
        System.err.println("ERROR: Input file is not readable");
        System.exit(1);
    }

    // Determine the output format
    if (!c_line.hasOption("o") && !c_line.hasOption("t")) {
        System.err.println("ERROR: At least one of output filename and output format must be given");
        System.exit(1);
    }
    if (c_line.hasOption("o")) {
        // Guess output format by filename extension
        output_filename = c_line.getOptionValue("o");
        output_format = getExtension(output_filename);
    }
    if (c_line.hasOption("t")) {
        // The "t" parameter overrides the filename extension
        output_format = c_line.getOptionValue("t");
    }

    // Determine which translator to initialize
    Translator trans = initializeTranslator(output_format);
    if (trans == null) {
        System.err.println("ERROR: Unrecognized output format");
        System.exit(1);
    }

    // Translate the trace into the output format
    EventTrace trace = null;
    try {
        trace = reader.parseEventTrace(new FileInputStream(in_f));
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        System.exit(1);
    }
    assert trace != null;
    trans.setTrace(trace);
    String out_trace = trans.translateTrace();
    if (output_filename.isEmpty())
        System.out.println(out_trace);
    else
        writeToFile(output_filename, out_trace);

    // Check if there is a formula to translate
    if (c_line.hasOption("s")) {
        String formula = c_line.getOptionValue("s");
        try {
            Operator o = Operator.parseFromString(formula);
            trans.setFormula(o);
            System.out.println(trans.translateFormula());
        } catch (Operator.ParseException e) {
            System.err.println("ERROR: parsing input formula");
            System.exit(1);
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.LuceneIndexer.java

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

    options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC);
    options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC);
    options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {// w  w w. j  ava 2s  .c om
        CommandLine cmd = parser.parse(options, args);

        String rootDir = null;

        rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM);

        if (null == rootDir)
            Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options);

        String outputDirName = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outputDirName)
            Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options);

        String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM);

        if (null == subDirTypeList || subDirTypeList.isEmpty())
            Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options);

        String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM);
        if (null == solrFileName)
            Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options);

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null) {
            try {
                maxNumRec = Integer.parseInt(tmp);
                if (maxNumRec <= 0) {
                    Usage("The maximum number of records should be a positive integer", options);
                }
            } catch (NumberFormatException e) {
                Usage("The maximum number of records should be a positive integer", options);
            }
        }

        File outputDir = new File(outputDirName);
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                System.out.println("couldn't create " + outputDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!outputDir.isDirectory()) {
            System.out.println(outputDir.getAbsolutePath() + " is not a directory!");
            System.exit(1);
        }
        if (!outputDir.canWrite()) {
            System.out.println("Can't write to " + outputDir.getAbsolutePath());
            System.exit(1);
        }

        String subDirs[] = subDirTypeList.split(",");

        int docNum = 0;

        // No English analyzer here, all language-related processing is done already,
        // here we simply white-space tokenize and index tokens verbatim.
        Analyzer analyzer = new WhitespaceAnalyzer();
        FSDirectory indexDir = FSDirectory.open(outputDir);
        IndexWriterConfig indexConf = new IndexWriterConfig(analyzer.getVersion(), analyzer);

        System.out.println("Creating a new Lucene index, maximum # of docs to process: " + maxNumRec);
        indexConf.setOpenMode(OpenMode.CREATE);
        IndexWriter indexWriter = new IndexWriter(indexDir, indexConf);

        for (int subDirId = 0; subDirId < subDirs.length && docNum < maxNumRec; ++subDirId) {
            String inputFileName = rootDir + "/" + subDirs[subDirId] + "/" + solrFileName;

            System.out.println("Input file name: " + inputFileName);

            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inputFileName)));
            String docText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (; docText != null && docNum < maxNumRec; docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
                ++docNum;
                Map<String, String> docFields = null;

                Document luceneDoc = new Document();

                try {
                    docFields = XmlHelper.parseXMLIndexEntry(docText);
                } catch (Exception e) {
                    System.err.println(String.format("Parsing error, offending DOC #%d:\n%s", docNum, docText));
                    System.exit(1);
                }

                String id = docFields.get(UtilConst.TAG_DOCNO);

                if (id == null) {
                    System.err.println(String.format("No ID tag '%s', offending DOC #%d:\n%s",
                            UtilConst.TAG_DOCNO, docNum, docText));
                }

                luceneDoc.add(new StringField(UtilConst.TAG_DOCNO, id, Field.Store.YES));

                for (Map.Entry<String, String> e : docFields.entrySet())
                    if (!e.getKey().equals(UtilConst.TAG_DOCNO)) {
                        luceneDoc.add(new TextField(e.getKey(), e.getValue(), Field.Store.YES));
                    }
                indexWriter.addDocument(luceneDoc);
                if (docNum % 1000 == 0)
                    System.out.println("Indexed " + docNum + " docs");
            }
            System.out.println("Indexed " + docNum + " docs");
        }

        indexWriter.commit();
        indexWriter.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.incapture.rapgen.GenApi.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("l", true, "Language to generate");
    options.addOption("o", true, "Output root folder for kernel files");
    options.addOption("a", true, "Output root folder for api files");
    options.addOption("w", true, "Output root folder for web files");
    options.addOption("d", true, "Template dir to use (use either this or 't')");
    options.addOption("t", true, "Template file to use (use either this or 'd')");
    options.addOption("g", true, "The type of grammar to generate, current options are 'SDK' or 'API'");
    options.addOption("mainApiFile", true, "FileName specifying the api");
    options.addOption("codeSamplesJava", true, "A path to search for files that have Java code samples");
    options.addOption("codeSamplesPython", true, "A path to search for files that have Python code samples");

    CommandLineParser cparser = new PosixParser();
    try {//  w  w w  . jav a  2 s. c  o  m
        CommandLine cmd = cparser.parse(options, args);
        String mainApiFile = cmd.getOptionValue("mainApiFile");
        String outputKernelFolder = cmd.getOptionValue('o');
        String outputApiFolder = cmd.getOptionValue('a');
        String outputWebFolder = cmd.getOptionValue('w');
        String codeSamplesJava = cmd.getOptionValue("codeSamplesJava");
        String codeSamplesPython = cmd.getOptionValue("codeSamplesPython");

        GenType genType = GenType.valueOf(cmd.getOptionValue('g'));

        // The language will ultimately choose the walker class
        String language = cmd.getOptionValue('l');
        if (cmd.hasOption('d') && cmd.hasOption('t')) {
            throw new IllegalArgumentException(
                    "Cannot define both a template folder ('d') and file ('t'). Please use one OR the other.");
        }

        // And off we go

        TLexer lexer = new TLexer();
        ResourceBasedApiReader apiReader = new ResourceBasedApiReader();
        lexer.setApiReader(apiReader);
        lexer.setCharStream(apiReader.read(mainApiFile));

        // Using the lexer as the token source, we create a token
        // stream to be consumed by the parser
        //
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // Now we need an instance of our parser
        //
        TParser parser = new TParser(tokens);

        hmxdef_return psrReturn = parser.hmxdef();

        // load in T.stg template group, put in templates variable
        StringTemplateGroup templates = null;

        if (!isSlateMd(language)) {
            templates = TemplateRepo.getTemplates(language, genType);
        }
        Tree t = psrReturn.getTree();

        CommonTreeNodeStream ns = new CommonTreeNodeStream(t);
        ns.setTokenStream(tokens);
        if (templates != null) {
            templates.registerRenderer(String.class, new UpCaseRenderer());
        }
        AbstractTTree walker = TreeFactory.createTreeWalker(ns, templates, language);
        System.out.println("Generating files with a " + walker.getClass().getName());
        if (walker instanceof TTree) {
            if (genType.equals(GenType.API)) {
                ((TTree) walker).apiGen();
            } else {
                ((TTree) walker).sdkGen();
            }
        } else if (walker instanceof TTreeRuby) {
            System.out.println("Running for Ruby");
            /* TTreeRuby.hmxdef_return out = */
            ((TTreeRuby) walker).hmxdef();
        } else if (walker instanceof TTreeJS) {
            System.out.println("Running for JavaScript");
            /* TTreeJS.hmxdef_return out = */
            ((TTreeJS) walker).hmxdef();
        } else if (walker instanceof TTreeDoc) {
            System.out.println("Running for Documentation");
            /* TTreeDoc.hmxdef_return out = */
            ((TTreeDoc) walker).hmxdef();
        } else if (walker instanceof TTreeVB) {
            System.out.println("Running for VB");
            /* TTreeVB.hmxdef_return out = */
            ((TTreeVB) walker).hmxdef();
        } else if (walker instanceof TTreeGo) {
            System.out.println("Running for Go");
            /* TTreeGo.hmxdef_return out = */
            ((TTreeGo) walker).hmxdef();
        } else if (walker instanceof TTreeCpp) {
            System.out.println("Running for Cpp");
            /* TTreeGo.hmxdef_return out = */
            ((TTreeCpp) walker).hmxdef();
        } else if (walker instanceof TTreePython) {
            System.out.println("Running for Python");
            /* TTreePython.hmxdef_return out = */
            ((TTreePython) walker).hmxdef();
        } else if (walker instanceof TTreeSlateMd) {
            System.out.println("Running for Slate Markdown");
            TTreeSlateMd slateMdWalker = (TTreeSlateMd) walker;
            slateMdWalker.setupCodeParser(codeSamplesJava, codeSamplesPython);
            slateMdWalker.hmxdef();
        } else if (walker instanceof TTreeDotNet) {
            System.out.println("Running for DotNet");
            ((TTreeDotNet) walker).apiGen();
        } else if (walker instanceof TTreeCurtisDoc) {
            System.out.println("Running for CurtisDoc");
            ((TTreeCurtisDoc) walker).apiGen();
        }
        // Now dump the files out
        System.out.println("Genereated source output locations:");
        System.out.println(String.format("kernel: [%s]", outputKernelFolder));
        System.out.println(String.format("api: [%s]", outputApiFolder));
        System.out.println(String.format("web: [%s]", outputWebFolder));
        walker.dumpFiles(outputKernelFolder, outputApiFolder, outputWebFolder);

    } catch (ParseException e) {
        System.err.println("Error parsing command line - " + e.getMessage());
        System.out.println("Usage: " + options.toString());
    } catch (IOException | RecognitionException e) {
        System.err.println("Error running GenApi: " + ExceptionToString.format(e));
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryGrabats09.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//  w  ww . j  a  v a2 s . c  o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryGrabats09.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                Runtime.getRuntime().gc();
                long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                        MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<ClassDeclaration> list = ASE2015JavaQueries.grabats09(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
                Runtime.getRuntime().gc();
                long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
                LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.github.jjYBdx4IL.utils.lang.ConstantClassCreator.java

public static void main(String[] args) {
    try {// w  w w  . j a  va 2 s . c o m
        CommandLineParser parser = new GnuParser();
        Options options = new Options();
        options.addOption(OPTNAME_H, OPTNAME_HELP, false, "show help (this page)");
        options.addOption(null, OPTNAME_SYSPROP, true, "system property name(s)");
        options.addOption(null, OPTNAME_OUTPUT_CLASSNAME, true, "output classname");
        options.addOption(null, OPTNAME_OUTPUT_DIRECTORY, true, "output directory");
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(OPTNAME_H)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(ConstantClassCreator.class.getName(), options);
        } else if (line.hasOption(OPTNAME_SYSPROP)) {
            new ConstantClassCreator().run(line);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.adobe.aem.demomachine.Json2Csv.java

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

    String inputFile1 = null;//w w  w.j a v  a2s .  c  o  m
    String inputFile2 = null;
    String outputFile = null;

    HashMap<String, String> hmReportSuites = new HashMap<String, String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("c", true, "Filename 1");
    options.addOption("r", true, "Filename 2");
    options.addOption("o", true, "Filename 3");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("c")) {
            inputFile1 = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("r")) {
            inputFile2 = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("o")) {
            outputFile = cmd.getOptionValue("o");
        }

        if (inputFile1 == null || inputFile1 == null || outputFile == null) {
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // List of customers and report suites for these customers
    String sInputFile1 = readFile(inputFile1, Charset.defaultCharset());
    sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

    // Processing the list of report suites for each customer
    try {

        JSONArray jCustomers = new JSONArray(sInputFile1.trim());
        for (int i = 0, size = jCustomers.length(); i < size; i++) {
            JSONObject jCustomer = jCustomers.getJSONObject(i);
            Iterator<?> keys = jCustomer.keys();
            String companyName = null;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("company")) {
                    companyName = jCustomer.getString(key);
                }
            }
            keys = jCustomer.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();

                if (key.equals("report_suites")) {
                    JSONArray jReportSuites = jCustomer.getJSONArray(key);
                    for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) {
                        hmReportSuites.put(jReportSuites.getString(j), companyName);
                        System.out.println(jReportSuites.get(j) + " for company " + companyName);
                    }

                }
            }
        }

        // Creating the out put file
        PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
        writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents"
                + "\",\"" + "Last Updated" + "\"");

        // Processing the list of SOLR collections
        String sInputFile2 = readFile(inputFile2, Charset.defaultCharset());
        sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

        JSONObject jResults = new JSONObject(sInputFile2.trim());
        JSONArray jCollections = jResults.getJSONArray("result");
        for (int i = 0, size = jCollections.length(); i < size; i++) {
            JSONObject jCollection = jCollections.getJSONObject(i);
            String id = null;
            String number = null;
            String lastupdate = null;

            Iterator<?> keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("_id")) {
                    id = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("noOfDocs")) {
                    number = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("latestUpdateDate")) {
                    lastupdate = jCollection.getString(key);
                }
            }

            Date d = new Date(Long.parseLong(lastupdate));
            System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + ","
                    + new SimpleDateFormat("MM-dd-yyyy").format(d));
            writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\""
                    + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\"");

        }

        writer.close();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("p").required(true).hasArg().longOpt("pylint_file")
            .desc("Executable pylint file to invoke").build());

    try {/*from www.jav  a2s .  c  o m*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String pylintFile = line.getOptionValue("p");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.info("No python files found by checkstyle");
            return;
        }

        LOG.info(sourceFiles.size() + " python files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(pylintFile);
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}