Example usage for org.apache.commons.cli OptionBuilder withArgName

List of usage examples for org.apache.commons.cli OptionBuilder withArgName

Introduction

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

Prototype

public static OptionBuilder withArgName(String name) 

Source Link

Document

The next Option created will have the specified argument value name.

Usage

From source file:de.l3s.content.mapred.WikipediaPagesBz2InputStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("gzipped XML dump file")
            .create(INPUT_OPTION));//from  w  ww  . ja v a2 s . c o m
    options.addOption(OptionBuilder.withArgName("lang").hasArg().withDescription("output location")
            .create(LANGUAGE_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(WikipediaPagesBz2InputStream.class.getCanonicalName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String path = cmdline.getOptionValue(INPUT_OPTION);
    String lang = cmdline.hasOption(LANGUAGE_OPTION) ? cmdline.getOptionValue(LANGUAGE_OPTION) : "en";
    WikipediaPage p = WikipediaPageFactory.createWikipediaPage(lang);

    WikipediaPagesBz2InputStream stream = new WikipediaPagesBz2InputStream(path);
    while (stream.readNext(p)) {
        System.out.println(p.getTitle() + "\t" + p.getDocid());
    }
}

From source file:io.anserini.index.IndexGov2.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//from w  w w. j  av  a  2s  .  c om
            OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path")
            .create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads")
            .create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of documents to index (-1 to index everything)")
            .create(DOCLIMIT_OPTION));

    options.addOption(POSITIONS_OPTION, false, "index positions");
    options.addOption(OPTIMIZE_OPTION, false, "merge all index segments");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(THREADS_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp(IndexGov2.class.getCanonicalName(), options);
        System.exit(-1);
    }

    final String dirPath = cmdline.getOptionValue(INDEX_OPTION);
    final String dataDir = cmdline.getOptionValue(INPUT_OPTION);
    final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION))
            : -1;
    final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION));

    final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION);
    final boolean positions = cmdline.hasOption(POSITIONS_OPTION);
    final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION);

    final Analyzer a = new EnglishAnalyzer();
    final TrecContentSource trecSource = createGov2Source(dataDir);
    final Directory dir = FSDirectory.open(Paths.get(dirPath));

    LOG.info("Index path: " + dirPath);
    LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit));
    LOG.info("Threads: " + numThreads);
    LOG.info("Positions: " + positions);
    LOG.info("Optimize (merge segments): " + optimize);

    final IndexWriterConfig config = new IndexWriterConfig(a);

    if (doUpdate) {
        config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    } else {
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }

    final IndexWriter writer = new IndexWriter(dir, config);
    Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit);
    LOG.info("Indexer: start");

    final long t0 = System.currentTimeMillis();

    threads.start();

    while (!threads.done()) {
        Thread.sleep(100);
    }
    threads.stop();

    final long t1 = System.currentTimeMillis();
    LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs");
    if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) {
        throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit);
    }
    if (threads.failed.get()) {
        throw new RuntimeException("exceptions during indexing");
    }

    final long t2;
    t2 = System.currentTimeMillis();

    final Map<String, String> commitData = new HashMap<String, String>();
    commitData.put("userData", "multi");
    writer.setCommitData(commitData);
    writer.commit();
    final long t3 = System.currentTimeMillis();
    LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)");

    if (optimize) {
        LOG.info("Indexer: merging all segments");
        writer.forceMerge(1);
        final long t4 = System.currentTimeMillis();
        LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)");
    }

    LOG.info("Indexer: at close: " + writer.segString());
    final long tCloseStart = System.currentTimeMillis();
    writer.close();
    LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec");
    dir.close();
    final long tFinal = System.currentTimeMillis();
    LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)");
    LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed());
    LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.))
            + " GB/hour plain text");
}

From source file:joshua.subsample.AlignedSubsampler.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    new SubsamplerCLI() { /* Local class definition */

        //TODO hasArg is a static method. It should be accessed as OptionBuilder.hasArg()
        protected final Option oa = OptionBuilder.withArgName("lang").hasArg()
                .withDescription("Word alignment extension").isRequired().create("a");

        //TODO hasArg is a static method. It should be accessed as OptionBuilder.hasArg()
        protected final Option oapath = OptionBuilder.withArgName("path").hasArg()
                .withDescription("Directory containing word alignment files").create("apath");

        public Options getCliOptions() {
            return super.getCliOptions().addOption(oa).addOption(oapath);
        }//from w  w  w  .  j  ava  2  s  .  c om

        public String getClassName() {
            return AlignedSubsampler.class.getName();
        }

        public void runSubsampler(String[] testFiles, int maxN, int targetCount, float ratio)
                throws IOException {
            new AlignedSubsampler(testFiles, maxN, targetCount).subsample(ot.getValue(), ratio, of.getValue(),
                    oe.getValue(), oa.getValue(), ofpath.getValue(), oepath.getValue(), oapath.getValue(),
                    ooutput.getValue());
        }

    }.runMain(args);
}

From source file:es.csic.iiia.planes.cli.Cli.java

/**
 * Cli's entry point.//from  www  .  ja va  2 s .  c  om
 * 
 * @param args
 *            the command line arguments
 */
public static void main(String[] args) {
    initializeLogging();

    options.addOption("d", "dump-settings", false,
            "dump the default settings to standard output. This can be used to prepare a settings file.");
    ;
    options.addOption("g", "gui", false, "graphically display the simulation.");
    options.addOption("h", "help", false, "show this help message.");
    options.addOption(OptionBuilder.withArgName("setting=value").hasArgs(2).withValueSeparator()
            .withDescription("override \"setting\" with \"value\".")
            // .withLongOpt("override")
            .create('o'));
    options.addOption("q", "quiet", false, "disable all output except for results and errors.");
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Load settings from <file>.")
            .withLongOpt("settings").create('s'));
    options.addOption(OptionBuilder.withLongOpt("dry-run")
            .withDescription("Output only the resolved settings, but do not run the simulation.").create('t'));

    Configuration config = parseOptions(args);
    CliApp app = new CliApp(config);
    app.run();
}

From source file:io.anserini.index.IndexTweets.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));
    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(/*w  w w  . jav a 2 s .  c  om*/
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids")
            .create(DELETES_OPTION));
    options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)
            || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndexTweets.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);
    String indexPath = cmdline.getOptionValue(INDEX_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) {
        textOptions.setStoreTermVectors(true);
    }

    LOG.info("collection: " + collectionPath);
    LOG.info("index: " + indexPath);

    LongOpenHashSet deletes = null;
    if (cmdline.hasOption(DELETES_OPTION)) {
        deletes = new LongOpenHashSet();
        File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION));
        if (!deletesFile.exists()) {
            System.err.println("Error: " + deletesFile + " does not exist!");
            System.exit(-1);
        }
        LOG.info("Reading deletes from " + deletesFile);

        FileInputStream fin = new FileInputStream(deletesFile);
        byte[] ignoreBytes = new byte[2];
        fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools
        BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin)));

        String s;
        while ((s = br.readLine()) != null) {
            if (s.contains("\t")) {
                deletes.add(Long.parseLong(s.split("\t")[0]));
            } else {
                deletes.add(Long.parseLong(s));
            }
        }
        br.close();
        fin.close();
        LOG.info("Read " + deletes.size() + " tweetids from deletes file.");
    }

    long maxId = Long.MAX_VALUE;
    if (cmdline.hasOption(MAX_ID_OPTION)) {
        maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION));
        LOG.info("index: " + maxId);
    }

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    StatusStream stream = new JsonStatusCorpusReader(file);

    Directory dir = FSDirectory.open(Paths.get(indexPath));
    final IndexWriterConfig config = new IndexWriterConfig(ANALYZER);

    config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

    IndexWriter writer = new IndexWriter(dir, config);
    int cnt = 0;
    Status status;
    try {
        while ((status = stream.next()) != null) {
            if (status.getText() == null) {
                continue;
            }

            // Skip deletes tweetids.
            if (deletes != null && deletes.contains(status.getId())) {
                continue;
            }

            if (status.getId() > maxId) {
                continue;
            }

            cnt++;
            Document doc = new Document();
            doc.add(new LongPoint(StatusField.ID.name, status.getId()));
            doc.add(new StoredField(StatusField.ID.name, status.getId()));
            doc.add(new LongPoint(StatusField.EPOCH.name, status.getEpoch()));
            doc.add(new StoredField(StatusField.EPOCH.name, status.getEpoch()));
            doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES));

            doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions));

            doc.add(new IntPoint(StatusField.FRIENDS_COUNT.name, status.getFollowersCount()));
            doc.add(new StoredField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount()));
            doc.add(new IntPoint(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount()));
            doc.add(new StoredField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount()));
            doc.add(new IntPoint(StatusField.STATUSES_COUNT.name, status.getStatusesCount()));
            doc.add(new StoredField(StatusField.STATUSES_COUNT.name, status.getStatusesCount()));

            long inReplyToStatusId = status.getInReplyToStatusId();
            if (inReplyToStatusId > 0) {
                doc.add(new LongPoint(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId));
                doc.add(new StoredField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId));
                doc.add(new LongPoint(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId()));
                doc.add(new StoredField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId()));
            }

            String lang = status.getLang();
            if (!lang.equals("unknown")) {
                doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES));
            }

            long retweetStatusId = status.getRetweetedStatusId();
            if (retweetStatusId > 0) {
                doc.add(new LongPoint(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId));
                doc.add(new StoredField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId));
                doc.add(new LongPoint(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId()));
                doc.add(new StoredField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId()));
                doc.add(new IntPoint(StatusField.RETWEET_COUNT.name, status.getRetweetCount()));
                doc.add(new StoredField(StatusField.RETWEET_COUNT.name, status.getRetweetCount()));
                if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) {
                    LOG.warn("Error parsing retweet fields of " + status.getId());
                }
            }

            writer.addDocument(doc);
            if (cnt % 100000 == 0) {
                LOG.info(cnt + " statuses indexed");
            }
        }

        LOG.info(String.format("Total of %s statuses added", cnt));

        if (cmdline.hasOption(OPTIMIZE_OPTION)) {
            LOG.info("Merging segments...");
            writer.forceMerge(1);
            LOG.info("Done!");
        }

        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
        dir.close();
        stream.close();
    }
}

From source file:eu.annocultor.converter.Analyser.java

static public void main(String... args) throws Exception {
    // Handling command line parameters with Apache Commons CLI
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired()
            .withDescription("XML file name to be analysed").withValueSeparator(',').create(OPT_FN));

    options.addOption(OptionBuilder.withArgName(OPT_MAX_VALUE_SIZE).hasArg().withDescription(
            "Maximal size when values are counted separately. Longer values are counted altogether. Reasonable values are 100, 300, etc.")
            .create(OPT_MAX_VALUE_SIZE));

    options.addOption(OptionBuilder.withArgName(OPT_VALUES).hasArg().withDescription(
            "Maximal number of most frequent values displayed in the report. Reasonable values are 10, 25, 50")
            .create(OPT_VALUES));/*from  w  ww  .  j ava2 s  .c o  m*/

    // now lets parse the input
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args));
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("analyse", options);
        return;
    }

    MAX_VALUE_SIZE = Integer.parseInt(cmd.getOptionValue(OPT_MAX_VALUE_SIZE, Integer.toString(MAX_VALUE_SIZE)));
    MAX_VALUES = Integer.parseInt(cmd.getOptionValue(OPT_VALUES, Integer.toString(MAX_VALUES)));

    Analyser analyser = new Analyser(new EnvironmentImpl());

    // undo:
    /*
    analyser.task.setSrcFiles(new File("."), cmd.getOptionValue(OPT_FN));
            
    if (analyser.task.getSrcFiles().size() > 1)
    {
       analyser.task.mergeSourceFiles();
    }
            
    if (analyser.task.getSrcFiles().size() == 0)
    {
       throw new Exception("No files to analyze, pattern " + cmd.getOptionValue(OPT_FN));
    }
            
    File trg = new File(analyser.task.getSrcFiles().get(0).getParentFile(), "rdf");
    if (!trg.exists())
       trg.mkdir();
            
    System.out.println("[Analysis] Analysing files "
    + cmd.getOptionValue(OPT_FN)
    + ", writing analysis to "
    + trg.getCanonicalPath()
    + ", max value length (long values are aggregated into one 'long value' value) "
    + MAX_VALUE_SIZE
    + ", number most fequently used values per field shown in report "
    + MAX_VALUES);
     */
    if (true)
        throw new Exception("unimplemented");
    System.exit(analyser.run());
}

From source file:de.prozesskraft.pkraft.Perlcode.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*w w w. ja va2 s .co  m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("perlcode", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:com.runwaysdk.system.metadata.MetadataPatcher.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("vendor").hasArg()
            .withDescription("Database vendor [" + POSTGRESQL + "]").isRequired().create("d"));
    options.addOption(OptionBuilder.withArgName("username").hasArg().withDescription("Database username")
            .isRequired().create("u"));
    options.addOption(OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .isRequired().create("p"));
    options.addOption(/*  w ww .  ja  v a2 s.  c  o  m*/
            OptionBuilder.withArgName("url").hasArg().withDescription("Database URL").isRequired().create("l"));

    CommandLineParser parser = new BasicParser();

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

        MetadataPatcher patcher = new MetadataPatcher();
        patcher.setDbms(cmd.getOptionValue("d"));
        patcher.setUserid(cmd.getOptionValue("u"));
        patcher.setPassword(cmd.getOptionValue("p"));
        patcher.setUrl(cmd.getOptionValue("l"));
        patcher.run();
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    } catch (RuntimeException exp) {
        System.err.println("Patching failed. Reason: " + exp.getMessage());
    }
}

From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java

public static void main(String[] args) {
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file")
              .withDescription("Path to a single file").create('f');

      Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir")
              .withDescription("A directory with image files in it").create('d');

      Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h');

      Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile")
              .withDescription(//from w  w  w .  j  ava 2s  .  c  o m
                      "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt")
              .create('p');

      Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg()
              .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o');

      Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json")
              .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j');

      Option similarityFromFeatureVectorsOpt = OptionBuilder
              .withArgName("similarity from FeatureVectors directory")
              .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg()
              .withDescription("calculate similarity matrix from given directory of feature vectors").create('s');

      Options options = new Options();
      options.addOption(dirOpt);
      options.addOption(pathFileOpt);
      options.addOption(fileOpt);
      options.addOption(helpOpt);
      options.addOption(outputFileOpt);
      options.addOption(jsonOutputFlag);
      options.addOption(similarityFromFeatureVectorsOpt);

      // create the parser
      CommandLineParser parser = new GnuParser();

      try {
          // parse the command line arguments
          CommandLine line = parser.parse(options, args);
          String directoryPath = null;
          String pathFile = null;
          String singleFilePath = null;
          String similarityFromFeatureVectorsDirectory = null;
          ArrayList<Path> videoFiles = null;

          if (line.hasOption("dir")) {
              directoryPath = line.getOptionValue("dir");
          }

          if (line.hasOption("pathfile")) {
              pathFile = line.getOptionValue("pathfile");
          }

          if (line.hasOption("file")) {
              singleFilePath = line.getOptionValue("file");
          }

          if (line.hasOption("outputfile")) {
              outputFile = line.getOptionValue("outputfile");
          }

          if (line.hasOption("json")) {
              outputFormat = OUTPUT_FORMATS.JSON;
          }

          if (line.hasOption("similarityFromFeatureVectorsDirectory")) {
              similarityFromFeatureVectorsDirectory = line
                      .getOptionValue("similarityFromFeatureVectorsDirectory");
          }

          if (line.hasOption("help")
                  || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0))
                  || (directoryPath != null && pathFile != null && !directoryPath.equals("")
                          && !pathFile.equals(""))) {
              HelpFormatter formatter = new HelpFormatter();
              formatter.printHelp("pooled_time_series", options);
              System.exit(1);
          }

          if (directoryPath != null) {
              File dir = new File(directoryPath);
              List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                      TrueFileFilter.INSTANCE);
              videoFiles = new ArrayList<Path>(files.size());

              for (File file : files) {
                  String filePath = file.toString();

                  // When given a directory to load videos from we need to ensure that we
                  // don't try to load the of.txt and hog.txt intermediate result files
                  // that results from previous processing runs.
                  if (!filePath.contains(".txt")) {
                      videoFiles.add(file.toPath());
                  }
              }

              LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath);

          }

          if (pathFile != null) {
              Path list_file = Paths.get(pathFile);
              videoFiles = loadFiles(list_file);
              LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile);
          }

          if (singleFilePath != null) {
              Path singleFile = Paths.get(singleFilePath);
              LOG.info("Loaded file: " + singleFile);
              videoFiles = new ArrayList<Path>(1);
              videoFiles.add(singleFile);
          }

          if (similarityFromFeatureVectorsDirectory != null) {
              File dir = new File(similarityFromFeatureVectorsDirectory);
              List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                      TrueFileFilter.INSTANCE);
              videoFiles = new ArrayList<Path>(files.size());

              for (File file : files) {
                  String filePath = file.toString();

                  // We need to load only the *.of.txt and *.hog.txt values
                  if (filePath.endsWith(".of.txt")) {
                      videoFiles.add(file.toPath());
                  }

                  if (filePath.endsWith(".hog.txt")) {
                      videoFiles.add(file.toPath());
                  }
              }

              LOG.info("Added " + videoFiles.size() + " feature vectors from "
                      + similarityFromFeatureVectorsDirectory);
              evaluateSimilarity(videoFiles, 1);
          } else {
              evaluateSimilarity(videoFiles, 1);
          }
          LOG.info("done.");

      } catch (ParseException exp) {
          // oops, something went wrong
          System.err.println("Parsing failed.  Reason: " + exp.getMessage());
      }

  }

From source file:de.prozesskraft.ptest.Compare.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from ww  w  .  j a v a  2s.  co m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oref = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against")
            //            .isRequired()
            .create("ref");

    Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription(
            "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref")
            //            .isRequired()
            .create("exam");

    Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file")
            //            .isRequired()
            .create("result");

    Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription(
            "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements")
            //            .isRequired()
            .create("summary");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no")
            //            .isRequired()
            .create("md5");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oref);
    options.addOption(oexam);
    options.addOption(oresult);
    options.addOption(osummary);
    options.addOption(omd5);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("compare", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.err.println("web:     " + web);
        System.err.println("author: " + author);
        System.err.println("version:" + version);
        System.err.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String result = "";
    boolean md5 = false;
    String ref = null;
    String exam = null;

    if (!(commandline.hasOption("ref"))) {
        System.err.println("option -ref is mandatory");
        error = true;
    } else {
        ref = commandline.getOptionValue("ref");
    }

    if (!(commandline.hasOption("exam"))) {
        java.io.File refFile = new java.io.File(ref).getCanonicalFile();
        java.io.File examFile = refFile.getParentFile();
        exam = examFile.getCanonicalPath();

        System.err.println("setting default: -exam=" + exam);
    } else {
        exam = commandline.getOptionValue("exam");
    }

    if (error) {
        exiter();
    }

    if (!(commandline.hasOption("result"))) {
        System.err.println("setting default: -result=result.txt");
        result = "result.txt";
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default: -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // einlesen der referenzdaten
    java.io.File refPath = new java.io.File(ref);

    Dir refDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (refPath.exists() && refPath.isDirectory()) {
        refDir.setBasepath(refPath.getCanonicalPath());
        refDir.genFingerprint(0f, true, new ArrayList<String>());
        refDir.setRespectMd5Recursive(md5);
        System.err.println("-ref is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (refPath.exists()) {
        refDir.setInfilexml(refPath.getCanonicalPath());
        System.err.println("-ref is a fingerprint");
        try {
            refDir.readXml();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refDir.setRespectMd5Recursive(md5);
    } else if (!refPath.exists()) {
        System.err.println("-ref does not exist! " + refPath.getAbsolutePath());
        exiter();
    }

    // einlesen der prueflingsdaten
    java.io.File examPath = new java.io.File(exam);

    Dir examDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (examPath.exists() && examPath.isDirectory()) {
        examDir.setBasepath(examPath.getCanonicalPath());
        examDir.genFingerprint(0f, true, new ArrayList<String>());
        examDir.setRespectMd5Recursive(md5);
        System.err.println("-exam is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (examPath.exists()) {
        examDir.setInfilexml(examPath.getCanonicalPath());
        System.err.println("-exam is a fingerprint");
        try {
            examDir.readXml();
        } catch (JAXBException e) {
            System.err.println("error while reading xml");
            e.printStackTrace();
        }
        examDir.setRespectMd5Recursive(md5);
    } else if (!examPath.exists()) {
        System.err.println("-exam does not exist! " + examPath.getAbsolutePath());
        exiter();
    }

    // durchfuehren des vergleichs
    refDir.runCheck(examDir);

    //      if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive())
    if (refDir.isMatchSuccessfullRecursive()) {
        System.out.println("SUCCESS");
    } else {
        System.out.println("FAILED");
    }

    // printen der csv-ergebnis-tabelle
    if (commandline.hasOption("summary")) {
        if (commandline.getOptionValue("summary").equals("error")) {
            System.err.println("the results of the reference are crucial for result FAILED|SUCCESS");
            System.err.println(refDir.sprintSummaryAsCsv("error"));
            System.err.println(examDir.sprintSummaryAsCsv("error"));
        } else if (commandline.getOptionValue("summary").equals("all")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
        } else if (commandline.getOptionValue("summary").equals("debug")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
            // printen des loggings
            System.err.println("------ logging of reference --------");
            System.err.println(refDir.getLogAsStringRecursive());
            System.err.println("------ logging of examinee --------");
            System.err.println(examDir.getLogAsStringRecursive());
        } else {
            System.err.println("for option -summary you only may use all|error");
            exiter();
        }
    }

}