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

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

Introduction

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

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:com.zuehlke.sbdfx.utils.CampApplBase.java

protected File getOptionValueAsFile(final Option option, final String defaultValue, final boolean forceExists) {
    final String optionValueString = getOptionValue(option,
            defaultValue != null ? String.valueOf(defaultValue) : ""); //$NON-NLS-1$
    File result = null;//w  w w  . ja va2 s .  co m
    if (StringUtils.isNotBlank(optionValueString)) {
        result = new File(optionValueString);
    } else if (StringUtils.isNotBlank(defaultValue)) {
        result = new File(defaultValue);
    } else {
        throw new IllegalArgumentException("Missing option or default value: " + option.getOpt());
    }
    if (forceExists && !result.exists()) {
        throw new IllegalArgumentException(
                "File does not exist for option : " + option.getOpt() + " - " + result.getAbsolutePath());
    }
    return result;
}

From source file:eu.stratosphere.pact.client.CliFrontend.java

/**
 * Displays exceptions./*from  w w  w. j  av a  2  s  .c  om*/
 * 
 * @param e the exception to display.
 */
@SuppressWarnings({ "unchecked" })
private void handleError(Throwable t) {
    if (t instanceof UnrecognizedOptionException) {

        Options generalOptions = this.options.get(GENERAL_OPTS);
        boolean generalOption = false;
        for (Option o : (Collection<Option>) generalOptions.getOptions()) {
            if (t.getMessage().startsWith("Unrecognized option: -" + o.getOpt())
                    || t.getMessage().contains("Unrecognized option: -" + o.getLongOpt())) {
                generalOption = true;
            }
        }
        if (generalOption) {
            System.err.println("ERROR: General args must be placed directly after action.");
        } else {
            System.err.println("ERROR: " + t.getMessage());
        }
        printHelp();
    } else {
        System.err.println("ERROR: " + t.getMessage());
        if (this.verbose) {
            t.printStackTrace();
        } else {
            System.out.println("For a more detailed error message use the '-v' option");
        }
    }
    System.exit(1);
}

From source file:craterdog.marketplace.DigitalMarketplaceCli.java

private CommandLine parse(Options options, String[] arguments) throws ParseException {
    CommandLineParser parser = new DefaultParser();

    Option helpOption = new Option("help", false, "print this message");
    options.addOption(helpOption);/*w w  w . j a v  a 2  s .  c  o  m*/

    // NOTE: this parse method may throw a different ParseException and miss the code below...
    CommandLine commandLine = parser.parse(options, arguments);
    if (commandLine == null || commandLine.hasOption(helpOption.getOpt())) {
        throw new ParseException(helpOption.getOpt());
    }
    return commandLine;
}

From source file:it.crs4.seal.read_sort.MergeAlignments.java

/**
 * Scan command line and set configuration values appropriately.
 * Calls System.exit in case of a command line error.
 *///from  w  w w  . j a  va  2  s.  co m
@SuppressWarnings("static") // for OptionBuilder
private void scanOptions(String[] args) {
    Options options = new Options();

    Option ref = OptionBuilder.withDescription("root path to the reference used to create the SAM data")
            .hasArg().withArgName("REF_PATH").withLongOpt("reference").create("ref");
    options.addOption(ref);

    Option ann = OptionBuilder.withDescription(
            "annotation file (.ann) of the BWA reference used to create the SAM data (not required if you specify "
                    + ref.getOpt() + ")")
            .hasArg().withArgName("ref.ann").withLongOpt("annotations").create("ann");
    options.addOption(ann);

    Option md5 = OptionBuilder.withDescription("generated MD5 checksums for reference contigs")
            .withLongOpt("md5").create("md5");
    options.addOption(md5);

    Option optSortOrder = OptionBuilder.withDescription(
            "Sort order.  Can be one of: unknown, unsorted, queryname, coordinate.  Default:  coordinate")
            .hasArg().withArgName("sort order").withLongOpt("sort-order").create("so");
    options.addOption(optSortOrder);

    Option as = OptionBuilder.withDescription("Genome assembly identifier (@SQ AS:xxxx tag)").hasArg()
            .withArgName("ASSEMBLY_ID").withLongOpt("sq-assembly").create("sqas");
    options.addOption(as);

    Option optHeaderOnly = OptionBuilder.withDescription("Only output the SAM header, then exit.")
            .withLongOpt("header-only").create("ho");
    options.addOption(optHeaderOnly);

    // read group options
    Map<String, Option> readGroupOptions = defineRGOptions();
    for (Option opt : readGroupOptions.values())
        options.addOption(opt);

    CommandLineParser parser = new GnuParser();

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

        if (line.hasOption(ref.getOpt()))
            userReferenceRoot = line.getOptionValue(ref.getOpt());

        if (line.hasOption(md5.getOpt()))
            generatedMd5 = true;

        if (line.hasOption(ann.getOpt()))
            userAnnotation = line.getOptionValue(ann.getOpt());

        if (line.hasOption(as.getOpt())) // TODO: validate this input
            genomeAssemblyId = line.getOptionValue(as.getOpt());

        if (line.hasOption(optSortOrder.getOpt())) {
            String value = line.getOptionValue(optSortOrder.getOpt());
            if ("unknown".equals(value) || "unsorted".equals(value) || "queryname".equals(value)
                    || "coordinate".equals(value))
                sortOrder = value;
            else
                throw new ParseException(
                        "Invalid sort order.  Sort order must be one of: unknown, unsorted, queryname, coordinate.");
        }

        if (line.hasOption(optHeaderOnly.getOpt()))
            headerOnly = true;

        // remaining args
        String[] otherArgs = line.getArgs();

        if (headerOnly) {
            // We're only generating the header, so we don't expect any input reads.
            if (otherArgs.length > 1)
                throw new ParseException(
                        "You can't provide an input path with --header-only. Provide an output path or let the output go to stdout.");

            if (otherArgs.length == 0)
                userOutput = null;
            else
                userOutput = otherArgs[0];
        } else // not headerOnly
        {
            if (otherArgs.length <= 0 || otherArgs.length > 2)
                throw new ParseException(
                        "You must provide an HDFS input path and, optionally, an output path.");

            userOutput = null;
            userInput = otherArgs[0];

            if (otherArgs.length >= 2)
                userOutput = otherArgs[1];
        }

        readGroupFields = parseReadGroupOptions(readGroupOptions, line);

        // option validation
        if (generatedMd5 && userReferenceRoot == null)
            throw new ParseException(
                    "You must specify the path the reference if you want to generate MD5 checksums");
        if (userReferenceRoot == null && userAnnotation == null)
            throw new ParseException(
                    "You must provide the path to the reference or at least its annotation file (<ref>.ann)");
    } catch (ParseException e) {
        System.err.println("Usage error: " + e.getMessage());
        // XXX: redirect System.out to System.err since the simple version of
        // HelpFormatter.printHelp prints to System.out, and we're on a way to
        // a fatal exit.
        System.setOut(System.err);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("MergeAlignments [options] -ann <ref>.ann [<in>] [<out>]", options);
        System.exit(1);
    }
}

From source file:com.aliyun.odps.mapred.bridge.streaming.StreamJob.java

void parseArgv() {
    CommandLine cmdLine = null;/*from   www  .  jav  a 2 s  .  c om*/
    try {
        cmdLine = parser.parse(allOptions, argv_);
    } catch (Exception oe) {
        LOG.error(oe.getMessage());
        exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
    }

    if (cmdLine == null) {
        exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
        return;
    }

    @SuppressWarnings("unchecked")
    List<String> args = cmdLine.getArgList();
    if (args != null && args.size() > 0) {
        fail("Found " + args.size() + " unexpected arguments on the " + "command line " + args);
    }

    detailedUsage_ = cmdLine.hasOption("info");
    if (cmdLine.hasOption("help") || detailedUsage_) {
        printUsage = true;
        return;
    }
    verbose_ = cmdLine.hasOption("verbose");
    background_ = cmdLine.hasOption("background");
    debug_ = cmdLine.hasOption("debug") ? debug_ + 1 : debug_;

    output_ = cmdLine.getOptionValue("output");

    comCmd_ = cmdLine.getOptionValue("combiner");
    redCmd_ = cmdLine.getOptionValue("reducer");

    lazyOutput_ = cmdLine.hasOption("lazyOutput");

    String[] values = cmdLine.getOptionValues("file");
    SessionState ss = SessionState.get();
    MetaExplorer metaExplorer = new MetaExplorerImpl(ss.getOdps());
    Map<String, String> aliasToTempResource = new HashMap<String, String>();
    String padding = "_" + UUID.randomUUID().toString();
    if (values != null && values.length > 0) {
        for (int i = 0; i < values.length; i++) {
            String file = values[i];
            packageFiles_.add(file);
            try {
                aliasToTempResource.put(FilenameUtils.getName(file),
                        metaExplorer.addFileResourceWithRetry(file, Resource.Type.FILE, padding, true));
            } catch (OdpsException e) {
                throw new RuntimeException(e);
            }
        }

        config_.set("stream.temp.resource.alias", JSON.toJSONString(aliasToTempResource));

        String[] res = config_.getResources();
        Set<String> resources = aliasToTempResource.keySet();
        if (res != null) {
            config_.setResources(StringUtils.join(res, ",") + "," + StringUtils.join(resources, ","));
        } else {
            config_.setResources(StringUtils.join(resources, ","));
        }
    }

    additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec");
    numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks");
    partitionerSpec_ = cmdLine.getOptionValue("partitioner");
    mapDebugSpec_ = cmdLine.getOptionValue("mapdebug");
    reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug");
    ioSpec_ = cmdLine.getOptionValue("io");

    String[] car = cmdLine.getOptionValues("cacheArchive");
    if (null != car) {
        fail("no -cacheArchive option any more, please use -resources instead.");
    }

    String[] caf = cmdLine.getOptionValues("cacheFile");
    if (null != caf) {
        fail("no -cacheFile option any more, please use -resources instead.");
    }

    mapCmd_ = cmdLine.getOptionValue("mapper");

    String[] cmd = cmdLine.getOptionValues("cmdenv");
    if (null != cmd && cmd.length > 0) {
        for (String s : cmd) {
            if (addTaskEnvironment_.length() > 0) {
                addTaskEnvironment_ += " ";
            }
            addTaskEnvironment_ += s;
        }
    }

    // per table input config
    Map<String, Map<String, String>> inputConfigs = new HashMap<String, Map<String, String>>();
    String[] columns = null;

    for (Option opt : cmdLine.getOptions()) {
        if ("jobconf".equals(opt.getOpt())) {
            String[] jobconf = opt.getValues();
            if (null != jobconf && jobconf.length > 0) {
                for (String s : jobconf) {
                    String[] parts = s.split("=", 2);
                    config_.set(parts[0], parts[1]);
                }
            }
        } else if ("columns".equals(opt.getOpt())) {
            String columnsValue = opt.getValue();
            if (columnsValue.equals("ALL")) {
                columns = null;
            } else {
                columns = columnsValue.split(",");
            }
        } else if ("input".equals(opt.getOpt())) {
            values = opt.getValues();
            if (values != null && values.length > 0) {
                for (String input : values) {
                    TableInfo ti = parseTableInfo(input);
                    if (columns != null) {
                        ti.setCols(columns);
                    }
                    inputSpecs_.add(ti);

                    String inputKey = (ti.getProjectName() + "." + ti.getTableName()).toLowerCase();
                    // XXX only apply once per table
                    if (inputConfigs.get(inputKey) != null) {
                        continue;
                    }

                    Map<String, String> inputConfig = new HashMap<String, String>();
                    inputConfig.put("stream.map.input.field.separator",
                            config_.get("stream.map.input.field.separator", "\t"));
                    // TODO other per table input config: cols, etc.
                    inputConfigs.put(inputKey, inputConfig);
                }
            }
        }
    }
    try {
        config_.set("stream.map.input.configs", JSON.toJSONString(inputConfigs));
    } catch (Exception e) {
        throw new RuntimeException("fail to set input configs");
    }
}

From source file:epgtools.dumpservicefromnit.Main.java

public void start(String[] args)
        throws org.apache.commons.cli.ParseException, FileNotFoundException, IOException {
    final byte[] sectionByte;
    final SERVICE_TYPE serviceType;
    final Option sectionDumpOption = Option.builder("s").required().longOpt("section")
            .desc("?hex").hasArg().type(String.class).build();

    final Option serviceTypeOption = Option.builder("t").required(false).longOpt("servicetype")
            .desc("?").hasArg().type(Integer.class).build();

    Options opts = new Options();
    opts.addOption(sectionDumpOption);/*from   www . ja  va  2  s  .  c  o m*/
    opts.addOption(serviceTypeOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        try {
            sectionByte = Hex.decodeHex(cl.getOptionValue(sectionDumpOption.getOpt()).toCharArray());
        } catch (DecoderException ex) {
            LOG.error(ex);
            throw new ParseException("hex??????");
        }

        serviceType = SERVICE_TYPE
                .reverseLookUp(Integer.parseInt(cl.getOptionValue(serviceTypeOption.getOpt()), 16));

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    }

    LOG.info("Starting application...");
    LOG.info("section           : " + Hex.encodeHexString(sectionByte));
    LOG.info("service type      : " + serviceType);

    Section section = new Section(sectionByte);

    if (section.checkCRC() != CRC_STATUS.NO_CRC_ERROR) {
        LOG.error("CRC??");
    }

    if (section.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK
            && section.getTable_id_const() != TABLE_ID.NIT_OTHER_NETWORK) {
        LOG.error("NIT?????");
    }

    NetworkInformationTableBody nitbody = (NetworkInformationTableBody) section.getSectionBody();

    final int networkId = nitbody.getNetwork_id();
    LOG.info("networkId = " + Integer.toHexString(networkId));

    for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
        final String networkName;
        if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
            final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
            networkName = nnd.getChar_String();
            LOG.info("networkName = " + networkName);
        }
    }

    final List<TransportStreamLoop> tsLoopList = nitbody.getTransport_streams_loop();

    for (TransportStreamLoop tsLoop : tsLoopList) {
        final int transportStreamId = tsLoop.getTransport_stream_id();
        LOG.info("transportStreamId = " + Integer.toHexString(transportStreamId));
        final int originalNetworkId = tsLoop.getOriginal_network_id();
        LOG.info("originalNetworkId = " + Integer.toHexString(originalNetworkId));
        final DescriptorsLoop dloop = tsLoop.getDescriptors_loop();
        final List<Descriptor> dList = dloop.getDescriptors_loopList();
        for (Descriptor desc : dList) {

            if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                List<Service> svList = sd.getServiceList();
                for (Service service : svList) {
                    if (service.getService_type_Enum() == serviceType) {
                        final int serviceId = service.getService_id();
                        LOG.info("serviceId = " + Integer.toHexString(serviceId));
                    }
                }
            }
        }
    }

}

From source file:dumpsection.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);/*from ww  w . j a v a2  s  . co  m*/
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        final PROGRAM_ID pids = PROGRAM_ID.SDT_OR_BAT;

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids.getPids());
        } else {
            reader = new TsReader(new File(fileName), pids.getPids(), limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();

        for (Integer pid : ret.keySet()) {
            try (FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + "_SDT.txt")) {
                SectionReconstructor sr = new SectionReconstructor(ret.get(pid), pid);
                for (Section s : sr.getSections()) {
                    String text = Hex.encodeHexString(s.getData());
                    writer.write(text + "\n");
                }
                writer.flush();
            } catch (IOException ex) {
                LOG.fatal("", ex);
            }
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:descriptordump.Main.java

public void start(String args[]) throws DecoderException, ParseException {
    File inputFile = null;//  ww w  .  java  2  s . co m
    Charset cs = null;

    final Option charSetOption = Option.builder("c").required(false).longOpt("charset").desc(
            "?????????????")
            .hasArg().type(String.class).build();

    final Option fileNameOption = Option.builder("f").required().longOpt("filename")
            .desc("??").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();
    try {
        cl = parser.parse(opts, args);

        try {
            cs = Charset.forName(cl.getOptionValue(charSetOption.getOpt()));
        } catch (Exception e) {
            LOG.error(
                    "?????????",
                    e);
            cs = Charset.defaultCharset();
        }
        inputFile = new File(cl.getOptionValue(fileNameOption.getOpt()));
        if (!inputFile.isFile()) {
            throw new ParseException("?????????");
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
    }

    final Set<TABLE_ID> tids = new HashSet<>();
    tids.add(TABLE_ID.SDT_THIS_STREAM);
    tids.add(TABLE_ID.SDT_OTHER_STREAM);
    tids.add(TABLE_ID.NIT_THIS_NETWORK);
    tids.add(TABLE_ID.NIT_OTHER_NETWORK);
    tids.add(TABLE_ID.EIT_THIS_STREAM_8_DAYS);
    tids.add(TABLE_ID.EIT_THIS_STREAM_NOW_AND_NEXT);
    tids.add(TABLE_ID.EIT_OTHER_STREAM_8_DAYS);
    tids.add(TABLE_ID.EIT_OTHER_STREAM_NOW_AND_NEXT);

    LOG.info("Starting application...");
    LOG.info("ts filename   : " + inputFile.getAbsolutePath());
    LOG.info("charset       : " + cs);

    Set<Section> sections = new HashSet<>();
    try {
        FileInputStream input = new FileInputStream(inputFile);
        InputStreamReader stream = new InputStreamReader(input, cs);
        BufferedReader buffer = new BufferedReader(stream);

        String line;
        long lines = 0;
        while ((line = buffer.readLine()) != null) {
            byte[] b = Hex.decodeHex(line.toCharArray());
            Section s = new Section(b);
            if (s.checkCRC() == CRC_STATUS.NO_CRC_ERROR && tids.contains(s.getTable_id_const())) {
                sections.add(s);
                LOG.trace("1????");
            } else {
                LOG.error("?????? = " + s);
            }
            lines++;
        }
        LOG.info(
                "?? = " + lines + " ? = " + sections.size());
        input.close();
        stream.close();
        buffer.close();
    } catch (FileNotFoundException ex) {
        LOG.fatal("???????", ex);
    } catch (IOException ex) {
        LOG.fatal("???????", ex);
    }

    SdtDescGetter sde = new SdtDescGetter();

    NitDescGetter nide = new NitDescGetter();

    EitDescGetter eide = new EitDescGetter();

    for (Section s : sections) {
        sde.process(s);
        nide.process(s);
        eide.process(s);
    }

    Set<Descriptor> descs = new HashSet<>();
    descs.addAll(sde.getUnmodifiableDest());
    descs.addAll(nide.getUnmodifiableDest());
    descs.addAll(eide.getUnmodifiableDest());

    Set<Integer> dtags = new TreeSet<>();
    for (Descriptor d : descs) {
        dtags.add(d.getDescriptor_tag());
    }

    for (Integer i : dtags) {
        LOG.info(Integer.toHexString(i));
    }
}

From source file:epgtools.dumpepgfromts.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("tsfile").desc("ts")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit").desc(
            "??(???????100000000)")
            .hasArg().type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);//from w  ww. j  a  v a2  s. c  om
    //        opts.addOption(PhysicalChannelNumberOption);
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = 10000000L;
        } finally {
            limit = xl;
        }

        LOG.info("Starting application...");
        LOG.info("filename   : " + fileName);
        LOG.info("limit : " + limit);

        FileLoader fl = new FileLoader(new File(fileName), limit);
        fl.load();

        //???
        Set<Channel> ch = fl.getChannels();
        LOG.info("?? = " + ch.size());
        for (Channel c : ch) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(c.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        //            ?
        Set<Programme> p = fl.getProgrammes();
        LOG.info(" = " + p.size());
        for (Programme pg : p) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(pg.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        System.gc();

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:eu.stratosphere.nephele.jobmanager.JobManager.java

@SuppressWarnings("static-access")
public static JobManager initialize(String[] args) throws Exception {
    // output the version and revision information to the log
    logVersionInformation();//ww w . j  a v  a 2s  .  com

    final Option configDirOpt = OptionBuilder.withArgName("config directory").hasArg()
            .withDescription("Specify configuration directory.").create("configDir");

    final Option executionModeOpt = OptionBuilder.withArgName("execution mode").hasArg()
            .withDescription("Specify execution mode.").create("executionMode");

    final Options options = new Options();
    options.addOption(configDirOpt);
    options.addOption(executionModeOpt);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error("CLI Parsing failed. Reason: " + e.getMessage());
        System.exit(FAILURE_RETURN_CODE);
    }

    final String configDir = line.getOptionValue(configDirOpt.getOpt(), null);
    final String executionModeName = line.getOptionValue(executionModeOpt.getOpt(), "local");

    ExecutionMode executionMode = null;
    if ("local".equals(executionModeName)) {
        executionMode = ExecutionMode.LOCAL;
    } else if ("cluster".equals(executionModeName)) {
        executionMode = ExecutionMode.CLUSTER;
    } else {
        System.err.println("Unrecognized execution mode: " + executionModeName);
        System.exit(FAILURE_RETURN_CODE);
    }

    // First, try to load global configuration
    GlobalConfiguration.loadConfiguration(configDir);

    // Create a new job manager object
    JobManager jobManager = new JobManager(executionMode);

    // Set base dir for info server
    Configuration infoserverConfig = GlobalConfiguration.getConfiguration();
    if (configDir != null && new File(configDir).isDirectory()) {
        infoserverConfig.setString(ConfigConstants.STRATOSPHERE_BASE_DIR_PATH_KEY, configDir + "/..");
    }
    GlobalConfiguration.includeConfiguration(infoserverConfig);
    return jobManager;
}