Java Code Examples for org.apache.commons.cli.ParseException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-common/src/main/java/org/dcm4che/tool/common/.

Source file: CLIUtils.java

  21 
vote

public static void configureConnect(Connection conn,AAssociateRQ rq,CommandLine cl) throws ParseException {
  if (!cl.hasOption("c"))   throw new MissingOptionException(rb.getString("missing-connect-opt"));
  String aeAtHostPort=cl.getOptionValue("c");
  String[] aeHostPort=split(aeAtHostPort,'@',0);
  if (aeHostPort[1] == null)   throw new ParseException(rb.getString("invalid-connect-opt"));
  String[] hostPort=split(aeHostPort[1],':',0);
  if (hostPort[1] == null)   throw new ParseException(rb.getString("invalid-connect-opt"));
  rq.setCalledAET(aeHostPort[0]);
  conn.setHostname(hostPort[0]);
  conn.setPort(Integer.parseInt(hostPort[1]));
  conn.setHttpProxy(cl.getOptionValue("proxy"));
  if (cl.hasOption("user"))   rq.setUserIdentityRQ(cl.hasOption("user-pass") ? new UserIdentityRQ(cl.getOptionValue("user"),cl.getOptionValue("user-pass").toCharArray()) : new UserIdentityRQ(cl.getOptionValue("user"),cl.hasOption("user-rsp")));
}
 

Example 2

From project magrit, under directory /server/main/src/main/java/org/kercoin/magrit/.

Source file: ArgumentsParser.java

  21 
vote

private int getNumber(String opt,int min,String label) throws ParseException {
  try {
    int httpPort=Integer.parseInt(get(opt));
    if (httpPort <= min) {
      throw new ParseException(label + " must be >" + min);
    }
    return httpPort;
  }
 catch (  NumberFormatException e) {
    throw new ParseException(label + " should be numeric");
  }
}
 

Example 3

From project sqoop, under directory /src/java/org/apache/sqoop/tool/.

Source file: SqoopTool.java

  21 
vote

/** 
 * Configures a SqoopOptions according to the specified arguments. Reads a set of arguments and uses them to configure a SqoopOptions and its embedded configuration (i.e., through GenericOptionsParser.) Stores any unparsed arguments in the extraArguments field.
 * @param args the arguments to parse.
 * @param conf if non-null, set as the configuration for the returnedSqoopOptions.
 * @param in a (perhaps partially-configured) SqoopOptions. If null,then a new SqoopOptions will be used. If this has a null configuration and conf is null, then a new Configuration will be inserted in this.
 * @param useGenericOptions if true, will also parse generic Hadoopoptions into the Configuration.
 * @return a SqoopOptions that is fully configured by a given tool.
 */
public SqoopOptions parseArguments(String[] args,Configuration conf,SqoopOptions in,boolean useGenericOptions) throws ParseException, SqoopOptions.InvalidOptionsException {
  SqoopOptions out=in;
  if (null == out) {
    out=new SqoopOptions();
  }
  if (null != conf) {
    out.setConf(conf);
  }
 else   if (null == out.getConf()) {
    out.setConf(new Configuration());
  }
  out.setActiveSqoopTool((com.cloudera.sqoop.tool.SqoopTool)this);
  String[] toolArgs=args;
  if (useGenericOptions) {
    try {
      toolArgs=ConfigurationHelper.parseGenericOptions(out.getConf(),args);
    }
 catch (    IOException ioe) {
      ParseException pe=new ParseException("Could not parse generic arguments");
      pe.initCause(ioe);
      throw pe;
    }
  }
  ToolOptions toolOptions=new ToolOptions();
  configureOptions(toolOptions);
  CommandLineParser parser=new SqoopParser();
  CommandLine cmdLine=parser.parse(toolOptions.merge(),toolArgs,true);
  applyOptions(cmdLine,out);
  this.extraArguments=cmdLine.getArgs();
  return out;
}
 

Example 4

From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/client/avro/.

Source file: AvroCLIClient.java

  20 
vote

private boolean parseCommandLine(String[] args) throws ParseException {
  Options options=new Options();
  options.addOption("p","port",true,"port of the avro source").addOption("H","host",true,"hostname of the avro source").addOption("F","filename",true,"file to stream to avro source").addOption("R","headerFile",true,("file containing headers as " + "key/value pairs on each new line")).addOption("h","help",false,"display help text");
  CommandLineParser parser=new GnuParser();
  CommandLine commandLine=parser.parse(options,args);
  if (commandLine.hasOption('h')) {
    new HelpFormatter().printHelp("flume-ng avro-client",options,true);
    return false;
  }
  if (!commandLine.hasOption("port")) {
    throw new ParseException("You must specify a port to connect to with --port");
  }
  port=Integer.parseInt(commandLine.getOptionValue("port"));
  if (!commandLine.hasOption("host")) {
    throw new ParseException("You must specify a hostname to connect to with --host");
  }
  hostname=commandLine.getOptionValue("host");
  fileName=commandLine.getOptionValue("filename");
  if (commandLine.hasOption("headerFile")) {
    parseHeaders(commandLine);
  }
  return true;
}
 

Example 5

From project genobyte, under directory /genobyte/src/main/java/org/obiba/bitwise/client/.

Source file: PrintRecordCommand.java

  20 
vote

public boolean execute(Option opt,ClientContext context) throws ParseException {
  String str=opt.getValue();
  try {
    int index=Integer.valueOf(str);
    BitwiseStore store=context.getStore();
    ResultDisplay rd=new ResultDisplay();
    rd.setDisplayType(ResultDisplay.DisplayType.PLAIN);
    for (    String field : store.getFieldList()) {
      rd.addField(field);
    }
    rd.putRecord(store,index);
    System.out.println(rd.getOutput());
  }
 catch (  NumberFormatException e) {
    throw new ParseException(e.getMessage());
  }
  return false;
}
 

Example 6

From project Ivory, under directory /client/src/main/java/org/apache/ivory/cli/.

Source file: CLIParser.java

  20 
vote

/** 
 * Parse a array of arguments into a command.
 * @param args array of arguments.
 * @return the parsed Command.
 * @throws ParseException thrown if the arguments could not be parsed.
 */
public Command parse(String[] args) throws ParseException {
  if (args.length == 0) {
    throw new ParseException("missing sub-command");
  }
 else {
    if (commands.containsKey(args[0])) {
      GnuParser parser=new GnuParser();
      String[] minusCommand=new String[args.length - 1];
      System.arraycopy(args,1,minusCommand,0,minusCommand.length);
      return new Command(args[0],parser.parse(commands.get(args[0]),minusCommand,commandWithArgs.get(args[0])));
    }
 else {
      throw new ParseException(MessageFormat.format("invalid sub-command [{0}]",args[0]));
    }
  }
}
 

Example 7

From project mwe, under directory /plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/runtime/.

Source file: Mwe2Launcher.java

  20 
vote

public void run(String[] args){
  Options options=getOptions();
  final CommandLineParser parser=new PosixParser();
  CommandLine line=null;
  try {
    line=parser.parse(options,args);
    if (line.getArgs().length == 0)     throw new ParseException("No module name specified.");
    if (line.getArgs().length > 1)     throw new ParseException("Only one module name expected. But " + line.getArgs().length + " were passed ("+ line.getArgList()+ ")");
    String moduleName=line.getArgs()[0];
    Map<String,String> params=new HashMap<String,String>();
    String[] optionValues=line.getOptionValues(PARAM);
    if (optionValues != null) {
      for (      String string : optionValues) {
        int index=string.indexOf('=');
        if (index == -1) {
          throw new ParseException("Incorrect parameter syntax '" + string + "'. It should be 'name=value'");
        }
        String name=string.substring(0,index);
        String value=string.substring(index + 1);
        if (params.put(name,value) != null) {
          throw new ParseException("Duplicate parameter '" + name + "'.");
        }
      }
    }
    Injector injector=new Mwe2StandaloneSetup().createInjectorAndDoEMFRegistration();
    Mwe2Runner mweRunner=injector.getInstance(Mwe2Runner.class);
    if (moduleName.contains("/")) {
      mweRunner.run(URI.createURI(moduleName),params);
    }
 else {
      mweRunner.run(moduleName,params);
    }
  }
 catch (  final ParseException exp) {
    final HelpFormatter formatter=new HelpFormatter();
    System.err.println("Parsing arguments failed.  Reason: " + exp.getMessage());
    formatter.printHelp("java " + Mwe2Launcher.class.getName() + " some.mwe2.Module [options]\n",options);
    return;
  }
}
 

Example 8

From project nuxeo-distribution, under directory /nuxeo-launcher/src/main/java/org/nuxeo/launcher/.

Source file: NuxeoLauncher.java

  20 
vote

/** 
 * @since 5.6
 */
protected static CommandLine parseOptions(String[] args) throws ParseException {
  initParserOptions();
  CommandLineParser parser=new PosixParser();
  CommandLine cmdLine=null;
  Boolean stopAfterParsing=true;
  try {
    cmdLine=parser.parse(launcherOptions,args);
    if (cmdLine.hasOption(OPTION_HELP) || cmdLine.getArgList().contains(OPTION_HELP)) {
      printLongHelp();
    }
 else     if (cmdLine.getArgList().isEmpty()) {
      printShortHelp();
    }
 else {
      stopAfterParsing=false;
    }
  }
 catch (  UnrecognizedOptionException e) {
    log.error(e.getMessage());
    printShortHelp();
  }
catch (  MissingArgumentException e) {
    log.error(e.getMessage());
    printShortHelp();
  }
catch (  ParseException e) {
    log.error("Error while parsing command line: " + e.getMessage());
    printShortHelp();
  }
 finally {
    if (stopAfterParsing) {
      throw new ParseException("Invalid command line");
    }
  }
  return cmdLine;
}
 

Example 9

From project anarchyape, under directory /src/main/java/ape/.

Source file: CorruptCommand.java

  19 
vote

/** 
 * This method overrides the abstract function declared in the ApeCommand class  which actual implements the event
 */
@Override protected boolean runImpl(String[] args) throws ParseException, IOException {
  datatype=args[0];
  try {
    size=Integer.parseInt(args[1]);
    offset=Integer.parseInt(args[2]);
  }
 catch (  NumberFormatException t) {
    System.out.println("Unable to parse the size or offset given as an integer.");
    Main.logger.info("Unable to parse the size or offset given as an integer.");
    t.printStackTrace();
    Main.logger.info(t);
    return false;
  }
  if (Main.VERBOSE) {
    System.out.println("VERBOSE: Data type is " + args[0]);
    System.out.println("VERBOSE: Size of corruption is " + size);
    System.out.println("VERBOSE: Offset is " + offset);
  }
  if (!corrupt(null)) {
    System.out.println("Corrupting block file unsuccessful");
    return false;
  }
  return true;
}
 

Example 10

From project android-rindirect, under directory /rindirect/src/main/java/de/akquinet/android/rindirect/.

Source file: Main.java

  19 
vote

/** 
 * Main method. This methods defines the arguments, parse them and launch the R indirection generation.
 * @param args the arguments.
 * @throws ParseException
 * @throws IOException
 */
public static void main(String[] args) throws ParseException, Exception {
  LOGGER.setLevel(Level.WARNING);
  Options options=new Options();
  options.addOption("P","package",true,"destination package (mandatory)").addOption("R","classname",true,"generated java file [R]").addOption("D","destination",true,"the root of the destination [src]").addOption("I","input",true,"R file [searched in the 'gen' folder]").addOption("V","verbose",false,"Enable verbose mode");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  RIndirect rindirect=configure(cmd);
  rindirect.generate();
}
 

Example 11

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/consumer/.

Source file: KafkaHBaseConsumer.java

  19 
vote

public static void main(String[] args){
  OptionFactory optFactory=OptionFactory.getInstance();
  Options options=KafkaConsumer.getOptions();
  options.addOption(optFactory.create("tbl","table",true,"HBase table name.").required());
  options.addOption(optFactory.create("f","family",true,"Column family."));
  options.addOption(optFactory.create("q","qualifier",true,"Column qualifier."));
  options.addOption(optFactory.create("pd","prefixdate",false,"Prefix key with salted date."));
  CommandLineParser parser=new GnuParser();
  ShutdownHook sh=ShutdownHook.getInstance();
  try {
    CommandLine cmd=parser.parse(options,args);
    final KafkaConsumer consumer=KafkaConsumer.fromOptions(cmd);
    sh.addFirst(consumer);
    final KeyValueSink sink=new HBaseSink(cmd.getOptionValue("table"),cmd.getOptionValue("family","data"),cmd.getOptionValue("qualifier","json"),Boolean.parseBoolean(cmd.getOptionValue("prefixdate","true")));
    sh.addLast(sink);
    consumer.setSink(sink);
    MetricsManager.getInstance();
    consumer.poll();
  }
 catch (  ParseException e) {
    LOG.error("Error parsing command line options",e);
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp(KafkaHBaseConsumer.class.getName(),options);
  }
}
 

Example 12

From project BDSup2Sub, under directory /src/main/java/bdsup2sub/.

Source file: BDSup2Sub.java

  19 
vote

private void parseOptions(String[] args){
  options=new CommandLineParser();
  try {
    options.parse(args);
  }
 catch (  ParseException e) {
    fatalError(e.getMessage());
    options.printHelp();
    System.exit(1);
  }
}
 

Example 13

From project behemoth, under directory /core/src/main/java/com/digitalpebble/behemoth/util/.

Source file: ContentExtractor.java

  19 
vote

public int run(String[] args) throws Exception {
  Options options=new Options();
  HelpFormatter formatter=new HelpFormatter();
  CommandLineParser parser=new GnuParser();
  options.addOption("h","help",false,"print this message");
  options.addOption("i","input",true,"Behemoth corpus");
  options.addOption("o","output",true,"local corpus dir");
  options.addOption("b","binary",false,"dumps binary content, text otherwise");
  options.addOption("n","filenaming",true,"whether to name files based on URL, UUID (default) or NUM");
  try {
    CommandLine line=parser.parse(options,args);
    String input=line.getOptionValue("i");
    String output=line.getOptionValue("o");
    if (line.hasOption("help")) {
      formatter.printHelp("ContentExtractor",options);
      return 0;
    }
    if (input == null || output == null) {
      formatter.printHelp("ContentExtractor",options);
      return -1;
    }
    dumpBinary=line.hasOption("binary");
    if (line.hasOption("filenaming")) {
      String naming=line.getOptionValue("n");
      mode=FileNamingMode.toMode(naming);
    }
    return generateDocs(input,output);
  }
 catch (  ParseException e) {
    formatter.printHelp("ContentExtractor",options);
    return -1;
  }
}
 

Example 14

From project bonecp, under directory /bonecp-benchmark/src/main/java/com/jolbox/benchmark/.

Source file: BenchmarkMain.java

  19 
vote

/** 
 * @param args
 * @throws ClassNotFoundException 
 * @throws PropertyVetoException 
 * @throws SQLException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws InterruptedException 
 * @throws SecurityException 
 * @throws IllegalArgumentException 
 * @throws NamingException 
 * @throws ParseException 
 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException, IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NamingException, ParseException {
  Options options=new Options();
  options.addOption("t","threads",true,"Max number of threads");
  options.addOption("s","stepping",true,"Stepping of threads");
  options.addOption("p","poolsize",true,"Pool size");
  options.addOption("h","help",false,"Help");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,args);
  if (cmd.hasOption("h")) {
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp("benchmark.jar",options);
    System.exit(1);
  }
  Class.forName("com.jolbox.bonecp.MockJDBCDriver");
  new MockJDBCDriver();
  BenchmarkTests tests=new BenchmarkTests();
  BenchmarkTests.threads=200;
  BenchmarkTests.stepping=20;
  BenchmarkTests.pool_size=200;
  System.out.println("JIT warm up");
  tests.testMultiThreadedConstantDelay(0);
  BenchmarkTests.threads=200;
  BenchmarkTests.stepping=5;
  BenchmarkTests.pool_size=100;
  if (cmd.hasOption("t")) {
    BenchmarkTests.threads=Integer.parseInt(cmd.getOptionValue("t","400"));
  }
  if (cmd.hasOption("s")) {
    BenchmarkTests.stepping=Integer.parseInt(cmd.getOptionValue("s","20"));
  }
  if (cmd.hasOption("p")) {
    BenchmarkTests.pool_size=Integer.parseInt(cmd.getOptionValue("p","200"));
  }
  System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping "+ BenchmarkTests.stepping+ ") using pool size of "+ BenchmarkTests.pool_size+ " connections");
  System.out.println("Starting tests");
  plotLineGraph(tests.testMultiThreadedConstantDelay(0),0,false);
  plotBarGraph("Single Thread","bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-"+ BenchmarkTests.threads+ ".png",tests.testSingleThread());
  plotBarGraph("Prepared Statement\nSingle Threaded","bonecp-preparedstatement-single-poolsize-" + BenchmarkTests.pool_size + "-threads-"+ BenchmarkTests.threads+ ".png",tests.testPreparedStatementSingleThread());
}
 

Example 15

From project bpelunit, under directory /net.bpelunit.framework.client.command/src/main/java/net/bpelunit/framework/ui/command/.

Source file: BPELUnitCommandLineRunner.java

  19 
vote

@SuppressWarnings("unchecked") private final void parseOptionsFromCommandLine(String[] args){
  saveCoverageDetails=false;
  CommandLineParser parser=new PosixParser();
  try {
    CommandLine cmd=parser.parse(options,args);
    verifyCommandLineArguments(cmd);
    verbose=cmd.hasOption(PARAMETER_VERBOSE);
    xmlFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_XMLFILE));
    logFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_LOGFILE));
    if (cmd.hasOption(PARAMETER_COVERAGEFILE)) {
      covFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_COVERAGEFILE));
    }
    if (cmd.hasOption(PARAMETER_DETAILEDCOVERAGEFILE)) {
      covFileName=trimEqualsSignFromStart(cmd.getOptionValue(PARAMETER_DETAILEDCOVERAGEFILE));
      saveCoverageDetails=true;
    }
    ArrayList<String> remainingOptions=new ArrayList<String>(cmd.getArgList());
    setAndValidateTestSuiteFileName(remainingOptions.remove(0));
    testCaseNames=remainingOptions;
  }
 catch (  ParseException e) {
    showHelpAndExit();
  }
}
 

Example 16

From project Chess_1, under directory /src/main/java/com/es/.

Source file: CmdConfiguration.java

  19 
vote

public boolean parse(String[] args){
  final CommandLineParser parser=new PosixParser();
  try {
    commandLine=parser.parse(options,args);
  }
 catch (  final ParseException e) {
    LOG.error("Error parsing the command line",e);
    return false;
  }
  return true;
}
 

Example 17

From project Cloud9, under directory /src/dist/edu/umd/cloud9/collection/.

Source file: DocnoMapping.java

  19 
vote

public static DefaultBuilderOptions parseDefaultOptions(String[] args){
  Options options=new Options();
  options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("(required) collection path").create(COLLECTION_OPTION));
  options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("(required) output DocnoMapping path").create(MAPPING_OPTION));
  options.addOption(OptionBuilder.withArgName("class").hasArg().withDescription("(optional) fully-qualified Hadoop InputFormat").create(FORMAT_OPTION));
  CommandLine cmdline;
  CommandLineParser parser=new GnuParser();
  try {
    cmdline=parser.parse(options,args);
  }
 catch (  ParseException exp) {
    System.err.println("Error parsing command line: " + exp.getMessage());
    return null;
  }
  if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(MAPPING_OPTION)) {
    HelpFormatter formatter=new HelpFormatter();
    formatter.printHelp(DefaultBuilderOptions.class.getName(),options);
    ToolRunner.printGenericCommandUsage(System.out);
    return null;
  }
  DefaultBuilderOptions parsedOptions=new DefaultBuilderOptions();
  parsedOptions.inputFormat=SequenceFileInputFormat.class;
  if (cmdline.hasOption(FORMAT_OPTION)) {
    try {
      parsedOptions.inputFormat=(Class<? extends InputFormat>)Class.forName(cmdline.getOptionValue(FORMAT_OPTION));
    }
 catch (    ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  parsedOptions.collection=cmdline.getOptionValue(COLLECTION_OPTION);
  parsedOptions.docnoMapping=cmdline.getOptionValue(MAPPING_OPTION);
  return parsedOptions;
}
 

Example 18

From project Flume-Hive, under directory /src/java/com/cloudera/flume/core/.

Source file: EventUtil.java

  19 
vote

public static CommandLine defaultSinkParser(String[] argv) throws ParseException {
  Options options=new Options();
  options.addOption("d",false,"Directly send to collector");
  options.addOption("c",false,"Directly output to console");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,argv);
  return cmd;
}
 

Example 19

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/core/.

Source file: EventUtil.java

  19 
vote

public static CommandLine defaultSinkParser(String[] argv) throws ParseException {
  Options options=new Options();
  options.addOption("d",false,"Directly send to collector");
  options.addOption("c",false,"Directly output to console");
  CommandLineParser parser=new PosixParser();
  CommandLine cmd=parser.parse(options,argv);
  return cmd;
}
 

Example 20

From project hank, under directory /src/java/com/rapleaf/hank/util/.

Source file: CliUtils.java

  19 
vote

public static CommandLine parseAndHelp(String appName,Options options,String[] args){
  options.addOption(HELP_OPTION);
  Parser parser=new GnuParser();
  CommandLine line=null;
  try {
    line=parser.parse(options,args);
  }
 catch (  MissingOptionException e) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
catch (  MissingArgumentException e) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
catch (  ParseException e) {
    System.err.println("Unexpected Exception: " + e);
    throw new IllegalArgumentException();
  }
  if (line.hasOption("help")) {
    new HelpFormatter().printHelp(appName,options,true);
    throw new IllegalArgumentException();
  }
  return line;
}
 

Example 21

From project heritrix3, under directory /commons/src/main/java/org/archive/io/arc/.

Source file: ARCReader.java

  19 
vote

protected boolean output(final String format) throws IOException, java.text.ParseException {
  boolean result=super.output(format);
  if (!result && (format.equals(NOHEAD) || format.equals(HEADER))) {
    throw new IOException(format + " format only supported for single Records");
  }
  return result;
}
 

Example 22

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/storage/.

Source file: IndexesLogServer.java

  19 
vote

public static void main(String[] args) throws IOException, InterruptedException {
  CommandLineParser parser=new PosixParser();
  int readerPort, managerPort;
  try {
    CommandLine line=parser.parse(getOptions(),args);
    if (line.hasOption("help")) {
      printHelp(getOptions(),null);
      System.exit(1);
      return;
    }
    String val=null;
    val=line.getOptionValue("reader_port",null);
    if (null != val) {
      readerPort=Integer.valueOf(val);
    }
 else {
      printHelp(getOptions(),"Must specify a server port");
      System.exit(1);
      return;
    }
    val=null;
    val=line.getOptionValue("manager_port",null);
    if (null != val) {
      managerPort=Integer.valueOf(val);
    }
 else {
      printHelp(getOptions(),"Must specify a server port");
      System.exit(1);
      return;
    }
  }
 catch (  ParseException exp) {
    printHelp(getOptions(),exp.getMessage());
    System.exit(1);
    return;
  }
  new IndexesLogServer(readerPort,managerPort).start();
}
 

Example 23

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/test/java/org/isatools/isatab/commandline/permission_manager/.

Source file: PermissionManagerTest.java

  19 
vote

@Test public void testCreateNewUserFromOptions() throws ParseException {
  PermissionManager permMgr=new PermissionManager(entityManager);
  String[] args=new String[]{"--name","Marco","--surename","Brandizi","-p","secret","--date","10/09/1973","-r","submitter"};
  CommandLineParser clparser=new GnuParser();
  CommandLine cmdl=clparser.parse(permMgr.createUserDefOptions(),args);
  Person user=permMgr.createNewUserFromOptions("zakmck",cmdl);
  out.println(user);
  assertEquals("Wrong created user!","zakmck",user.getUserName());
  assertEquals("Wrong created user!","Marco",user.getFirstName());
  assertEquals("Wrong created user!",StringEncryption.getInstance().encrypt("secret"),user.getPassword());
  assertEquals("Wrong created user!",UserRole.SUBMITTER,user.getRole());
  assertEquals("Wrong created user!",new GregorianCalendar(1973,Calendar.SEPTEMBER,10).getTime(),user.getJoinDate());
}
 

Example 24

From project jmxsh, under directory /src/jmxsh/.

Source file: CloseCmd.java

  19 
vote

private CommandLine parseCommandLine(TclObject argv[]) throws ParseException {
  String[] args=new String[argv.length - 1];
  for (int i=0; i < argv.length - 1; i++)   args[i]=argv[i + 1].toString();
  CommandLine cl=(new PosixParser()).parse(this.opts,args);
  return cl;
}
 

Example 25

From project jnrpe-lib, under directory /jnrpe-lib/src/main/java/it/jnrpe/plugins/.

Source file: PluginProxy.java

  19 
vote

/** 
 * Executes the proxied plugin passing the received arguments as parameters.
 * @param args The parameters to be passed to the plugin
 * @return The return value of the plugin.
 */
public ReturnValue execute(final String[] args){
  CommandLineParser clp=new PosixParser();
  try {
    CommandLine cl=clp.parse(m_Options,args);
    if (getListeners() != null && m_plugin instanceof IPluginInterfaceEx) {
      ((IPluginInterfaceEx)m_plugin).addListeners(getListeners());
    }
    return m_plugin.execute(new PluginCommandLine(cl));
  }
 catch (  ParseException e) {
    return new ReturnValue(Status.UNKNOWN,e.getMessage());
  }
}
 

Example 26

From project jnrpe-server, under directory /jnrpe-server/src/main/java/it/jnrpe/server/.

Source file: JNRPEServer.java

  19 
vote

private static CommandLine parseCommandLine(String[] vsArgs){
  Digester d=DigesterLoader.createDigester(new InputSource(JNRPEServer.class.getResourceAsStream("command-line-digester.xml")));
  try {
    XMLOptions opts=(XMLOptions)d.parse(JNRPEServer.class.getResourceAsStream("jnrpe-command-line.xml"));
    m_Options=opts.toOptions();
    CommandLineParser clp=new PosixParser();
    return clp.parse(m_Options,vsArgs);
  }
 catch (  IOException e) {
  }
catch (  SAXException e) {
    e.printStackTrace();
  }
catch (  ParseException e) {
    printUsage(e);
  }
  return null;
}
 

Example 27

From project joshua, under directory /src/joshua/subsample/.

Source file: SubsamplerCLI.java

  19 
vote

/** 
 * Non-static version of main so that we can define anonymous local classes to override or extend the above.
 */
public void runMain(String[] args){
  Options o=this.getCliOptions();
  try {
    new GnuParser().parse(o,args);
  }
 catch (  ParseException pe) {
    System.err.println("Error parsing command line");
    new HelpFormatter().printHelp(this.getClassName(),o);
    System.exit(1);
  }
  try {
    float ratio=0.8f;
    if (this.oratio.getValue() != null) {
      ratio=Float.parseFloat(this.oratio.getValue());
    }
    this.runSubsampler(this.otest.getValues(),12,20,ratio);
  }
 catch (  Exception e) {
    e.printStackTrace();
    System.exit(1);
  }
}
 

Example 28

From project jreversepro, under directory /src/main/java/org/jreversepro/cmd/.

Source file: CommandLineInterface.java

  19 
vote

public void parse(String[] args){
  try {
    cmd=parser.parse(options,args);
    if (cmd.hasOption(OPTION_GUI)) {
      if (cmd.hasOption(OPTION_INPUT) || cmd.hasOption(OPTION_DECOMPILE) || cmd.hasOption(OPTION_DISASSEMBLE)) {
        LOGGER.severe(OPTION_GUI + " needs to be specified alone and should not accompany other arguments");
        throw new IllegalArgumentException("Invalid argument specified");
      }
      guiEnabled=true;
      return;
    }
    if (!cmd.hasOption(OPTION_INPUT)) {
      LOGGER.severe("Option -" + OPTION_INPUT + " mandatory");
    }
    outputType=OutputType.NONE;
    if (cmd.hasOption(OPTION_DISASSEMBLE)) {
      outputType=OutputType.DISASSEMBLER;
    }
    if (cmd.hasOption(OPTION_DECOMPILE)) {
      outputType=OutputType.DECOMPILER;
    }
    if (cmd.hasOption(OPTION_GUI)) {
      if (cmd.hasOption(OPTION_INPUT) || cmd.hasOption(OPTION_DECOMPILE)) {
        LOGGER.severe(OPTION_GUI + " needs to be specified alone and should not accompany other arguments");
        throw new UnsupportedOperationException("Invalid argument specified");
      }
      guiEnabled=true;
    }
    if (outputType == OutputType.NONE) {
      LOGGER.severe("Need to specify either " + OPTION_DISASSEMBLE + " or "+ OPTION_DECOMPILE);
    }
    if (cmd.hasOption(DECOMPILE_VERSION)) {
      javaVersionToDecompile=cmd.getOptionValue(DECOMPILE_VERSION);
    }
  }
 catch (  ParseException ex) {
    LOGGER.severe(ex.toString());
  }
}
 

Example 29

From project legacy-maven-support, under directory /maven3-interceptor/src/main/java/org/apache/maven/cli/.

Source file: DefaultMavenExecutionRequestBuilder.java

  19 
vote

private void cli(CliRequest cliRequest) throws Exception {
  CLIManager cliManager=new CLIManager();
  try {
    cliRequest.commandLine=cliManager.parse(cliRequest.args);
  }
 catch (  ParseException e) {
    cliRequest.stderr.println("Unable to parse command line options: " + e.getMessage());
    cliManager.displayHelp(cliRequest.stdout);
    throw e;
  }
  if (cliRequest.commandLine.hasOption(CLIManager.HELP)) {
    cliManager.displayHelp(cliRequest.stdout);
    throw new MavenCli.ExitException(0);
  }
  if (cliRequest.commandLine.hasOption(CLIManager.VERSION)) {
    CLIReportingUtils.showVersion(cliRequest.stdout);
    throw new MavenCli.ExitException(0);
  }
}
 

Example 30

From project maven-doxia-tools, under directory /doxia-converter/src/main/java/org/apache/maven/doxia/cli/.

Source file: CLIManager.java

  19 
vote

/** 
 * @param args not null.
 * @return a not null command line.
 * @throws ParseException if any
 * @throws IllegalArgumentException is args is null
 */
CommandLine parse(String[] args) throws ParseException {
  if (args == null) {
    throw new IllegalArgumentException("args is required.");
  }
  String[] cleanArgs=cleanArgs(args);
  CommandLineParser parser=new GnuParser();
  return parser.parse(OPTIONS,cleanArgs);
}
 

Example 31

From project Metamorphosis, under directory /metamorphosis-server/src/main/java/com/taobao/metamorphosis/server/.

Source file: MetamorphosisStartup.java

  19 
vote

static String getConfigFilePath(final String[] args) throws MetamorphosisServerStartupException {
  final Options options=new Options();
  final Option file=new Option("f",true,"Configuration file path");
  options.addOption(file);
  final CommandLineParser parser=new PosixParser();
  CommandLine line=null;
  try {
    line=parser.parse(options,args);
  }
 catch (  final ParseException e) {
    throw new MetamorphosisServerStartupException("Parse command line failed",e);
  }
  String configFilePath=null;
  if (line.hasOption("f")) {
    configFilePath=line.getOptionValue("f");
  }
 else {
    System.err.println("Please tell me the configuration file path by -f option");
    System.exit(1);
  }
  if (StringUtils.isBlank(configFilePath)) {
    throw new MetamorphosisServerStartupException("Blank file path");
  }
  return configFilePath;
}
 

Example 32

From project movsim, under directory /core/src/main/java/org/movsim/input/.

Source file: SimCommandLine.java

  19 
vote

/** 
 * Parse the command line.
 * @param args the args
 */
public void parse(String[] args){
  try {
    final CommandLine cmdline=parser.parse(options,args);
    parse(cmdline);
  }
 catch (  final ParseException exp) {
    System.out.printf("Parsing failed.  Reason: %s %n",exp.getMessage());
    optHelp();
  }
  final String projectName=projectMetaData.getProjectName();
  if (projectMetaData.isWriteInternalXml() && projectName.isEmpty()) {
    System.err.println("no xml file for simulation configuration found!");
    System.exit(-1);
  }
}
 

Example 33

From project onebusaway-gtfs-modules, under directory /onebusaway-gtfs-merge-cli/src/main/java/org/onebusaway/gtfs_merge/.

Source file: GtfsMergerMain.java

  19 
vote

/** 
 * {@link Runnable} Interface
 */
public void run(String[] args) throws IOException {
  if (needsHelp(args)) {
    printHelp();
    System.exit(0);
  }
  try {
    CommandLine cli=_parser.parse(_options,args,true);
    runApplication(cli,args);
  }
 catch (  MissingOptionException ex) {
    System.err.println("Missing argument: " + ex.getMessage());
    printHelp();
  }
catch (  MissingArgumentException ex) {
    System.err.println("Missing argument: " + ex.getMessage());
    printHelp();
  }
catch (  UnrecognizedOptionException ex) {
    System.err.println("Unknown argument: " + ex.getMessage());
    printHelp();
  }
catch (  AlreadySelectedException ex) {
    System.err.println("Argument already selected: " + ex.getMessage());
    printHelp();
  }
catch (  ParseException ex) {
    System.err.println(ex.getMessage());
    printHelp();
  }
catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 34

From project onebusaway-uk, under directory /onebusaway-uk-atco-cif-to-gtfs-converter/src/main/java/org/onebusaway/uk/atco_cif_to_gtfs_converter/.

Source file: AtcoCifToGtfsConverterMain.java

  19 
vote

public void run(String[] args) throws ParseException, IOException {
  Options options=new Options();
  buildOptions(options);
  Parser parser=new PosixParser();
  CommandLine cli=parser.parse(options,args);
  args=cli.getArgs();
  if (args.length != 2) {
    usage();
    System.exit(-1);
  }
  AtcoCifToGtfsConverter converter=new AtcoCifToGtfsConverter();
  configureConverter(args,cli,converter);
  converter.run();
}
 

Example 35

From project pluto, under directory /pluto-util/src/main/java/org/apache/pluto/util/cli/.

Source file: AssemblerCLI.java

  19 
vote

public void run() throws ParseException, IOException, UtilityException {
  CommandLineParser parser=new PosixParser();
  CommandLine line=parser.parse(options,args);
  String[] args=line.getArgs();
  if (args.length != 1) {
    abort();
    return;
  }
  String dest=line.getOptionValue("file");
  if (dest == null) {
    dest=args[0];
  }
  File source=new File(args[0]);
  File result=new File(dest);
  result.getParentFile().mkdirs();
  if (!source.exists()) {
    System.out.println("File does not exist: " + source.getCanonicalPath());
  }
  System.out.println("-----------------------------------------------");
  System.out.println("Assembling: " + source.getCanonicalPath());
  System.out.println("        to: " + result.getCanonicalPath());
  File webXml=new File(args[0],Assembler.SERVLET_XML);
  File portletXml=new File(args[0],Assembler.PORTLET_XML);
  AssemblerConfig config=new AssemblerConfig();
  config.setWebappDescriptor(webXml);
  config.setPortletDescriptor(portletXml);
  config.setDestination(webXml);
  Assembler assembler=AssemblerFactory.getFactory().createAssembler(config);
  config.setPortletDescriptor(portletXml);
  config.setWebappDescriptor(webXml);
  assembler.assemble(config);
  System.out.println("Complete!");
}
 

Example 36

From project ptest-server, under directory /src/main/java/com/mnxfst/testing/client/.

Source file: TSClient.java

  19 
vote

public void executeClient(String[] args){
  Options commandLineOptions=getTSClientCommandLineOptions();
  try {
    CommandLine commandLine=parseCommandline(commandLineOptions,args);
    if (!commandLine.hasOption(CMD_OPT_MODE_EXECUTE) && !commandLine.hasOption(CMD_OPT_MODE_COLLECT) && !commandLine.hasOption(CMD_OPT_MODE_SATURATION_TEST)) {
      printHelp(commandLineOptions,"Please select one mode: test plan execution, saturation load test or result collection");
      return;
    }
    int modeCount=0;
    if (commandLine.hasOption(CMD_OPT_MODE_EXECUTE))     modeCount=modeCount + 1;
    if (commandLine.hasOption(CMD_OPT_MODE_COLLECT))     modeCount=modeCount + 1;
    if (commandLine.hasOption(CMD_OPT_MODE_SATURATION_TEST))     modeCount=modeCount + 1;
    if (modeCount > 1) {
      printHelp(commandLineOptions,"Please select only one mode: test plan execution, saturation load test or result collection");
      return;
    }
    if (commandLine.hasOption(CMD_OPT_MODE_EXECUTE) || commandLine.hasOption(CMD_OPT_MODE_SATURATION_TEST)) {
      Map<String,String> results=executeTestPlan(commandLineOptions,commandLine);
      if (results != null && !results.isEmpty()) {
        System.out.println("Requested test plan successfully started on referenced hosts. The results contain the host as well as the result identifier:");
        for (        String hostName : results.keySet())         System.out.println("Host: " + hostName + ", Result Identifier: "+ results.get(hostName));
      }
    }
 else     if (commandLine.hasOption(CMD_OPT_MODE_COLLECT)) {
      Set<TSClientPlanExecutionResult> results=executeResultCollection(commandLineOptions,commandLine);
      for (      TSClientPlanExecutionResult r : results)       System.out.println(r);
    }
  }
 catch (  ParseException e) {
    System.out.println("Failed to parse command-line. Error: " + e.getMessage());
  }
}
 

Example 37

From project rabbitmq-java-client, under directory /test/src/com/rabbitmq/client/test/performance/.

Source file: CLIHelper.java

  19 
vote

public CommandLine parseCommandLine(String[] args){
  CommandLineParser parser=new GnuParser();
  CommandLine commandLine=null;
  try {
    commandLine=parser.parse(options,args);
  }
 catch (  ParseException e) {
    printHelp(options);
    throw new RuntimeException("Parsing failed. Reason: " + e.getMessage());
  }
  if (commandLine.hasOption("help")) {
    printHelp(options);
    return null;
  }
  return commandLine;
}
 

Example 38

From project RecordBreaker, under directory /test/com/cloudera/recordbreaker/learnstructure/test/.

Source file: GenerateTestAvro.java

  19 
vote

/** 
 */
public static void main(String argv[]) throws IOException, InstantiationException {
  CommandLine cmd=null;
  Options options=new Options();
  options.addOption("?",false,"Help for command-line");
  options.addOption("n",true,"# tuples to emit per file");
  try {
    CommandLineParser parser=new PosixParser();
    cmd=parser.parse(options,argv);
  }
 catch (  ParseException pe) {
    HelpFormatter fmt=new HelpFormatter();
    fmt.printHelp("GenerateTestAvro",options,true);
    System.exit(-1);
  }
  if (cmd.hasOption("?")) {
    HelpFormatter fmt=new HelpFormatter();
    fmt.printHelp("GenerateTestAvro",options,true);
    System.exit(0);
  }
  int numToEmit=100;
  if (cmd.hasOption("n")) {
    try {
      numToEmit=Integer.parseInt(cmd.getOptionValue("n"));
    }
 catch (    NumberFormatException nfe) {
      nfe.printStackTrace();
    }
  }
  String[] argArray=cmd.getArgs();
  if (argArray.length == 0) {
    HelpFormatter fmt=new HelpFormatter();
    fmt.printHelp("GenerateTestAvro",options,true);
    System.exit(0);
  }
  File outputDir=new File(argArray[0]).getCanonicalFile();
  GenerateTestAvro gta=new GenerateTestAvro();
  gta.generateData(outputDir,numToEmit);
}
 

Example 39

From project scape, under directory /pc-as/old_stuff/toolwrapper/toolwrapper_core/src/main/java/eu/scape_project/core/toolwrapper/.

Source file: ToolWrapperGenerator.java

  19 
vote

/** 
 * Method that parses the program arguments and return an object that represents that same arguments ( {@link CommandLine})
 */
private static CommandLine parseArguments(String[] args){
  Options options=new Options();
  options.addOption("t","toolspec",true,"toolspec file");
  options.addOption("g","generate",true,"artifacts to generate");
  options.addOption("o","outDir",true,"directory where to put the generated artifacts");
  CommandLineParser parser=new PosixParser();
  CommandLine commandLine=null;
  try {
    commandLine=parser.parse(options,args);
  }
 catch (  ParseException e) {
    System.err.println(e);
  }
  return commandLine;
}
 

Example 40

From project SMSD, under directory /src/cmd/.

Source file: SMSDcmd.java

  19 
vote

/** 
 * @param args the command line arguments
 */
@SuppressWarnings("unchecked") public static void main(String[] args){
  ArgumentHandler argumentHandler=new ArgumentHandler();
  try {
    argumentHandler.parseCommandLineOptions(args);
    InputHandler inputHandler=new InputHandler(argumentHandler);
    if (argumentHandler.isHelp()) {
      argumentHandler.printHelp();
      inputHandler.printDataTypeHelp();
    }
 else     if (argumentHandler.isImageOptionHelp()) {
      OutputHandler outputHandler=new OutputHandler(argumentHandler);
      outputHandler.printImageOptionsHelp();
    }
 else {
      run(argumentHandler,inputHandler);
    }
  }
 catch (  ParseException pe) {
    System.err.println("Problem with the arguments : " + pe.getMessage());
  }
}
 

Example 41

From project spring-gemfire-examples, under directory /spring-gemfire-examples-common/src/main/java/org/springframework/data/gemfire/examples/.

Source file: LocatorCommandParser.java

  19 
vote

public static Map<String,Object> parseOptions(String[] args){
  initOptions();
  HashMap<String,Object> optionsMap=new HashMap<String,Object>();
  BasicParser parser=new BasicParser();
  try {
    CommandLine cl=parser.parse(options,args);
    if (cl.hasOption("help")) {
      usage("help");
      return null;
    }
    String command=getCommand(cl);
    if (command == null) {
      return null;
    }
    optionsMap.put("command",command);
    if (cl.hasOption("port")) {
      optionsMap.put("port",Integer.parseInt(cl.getOptionValue("port")));
    }
    if (cl.hasOption("dir")) {
      optionsMap.put("dir",cl.getOptionValue("dir"));
    }
    if (cl.hasOption("properties")) {
      optionsMap.put("properties",cl.getOptionValue("properties"));
    }
  }
 catch (  ParseException e) {
    usage(e.getMessage());
    return null;
  }
  return optionsMap;
}
 

Example 42

From project spring-migration-analyzer, under directory /command-line/src/main/java/org/springframework/migrationanalyzer/commandline/.

Source file: AbstractMigrationAnalysis.java

  19 
vote

final void run(String[] args){
  CommandLine commandLine=null;
  try {
    commandLine=new PosixParser().parse(OPTIONS,args);
    String inputPath=commandLine.getOptionValue(OptionsFactory.OPTION_KEY_INPUT_PATH);
    String outputType=commandLine.getOptionValue(OptionsFactory.OPTION_KEY_OUTPUT_TYPE);
    String outputPath=commandLine.getOptionValue(OptionsFactory.OPTION_KEY_OUTPUT_PATH);
    String[] excludes=commandLine.getOptionValues(OptionsFactory.OPTION_KEY_EXCLUDE);
    getExecutor(inputPath,outputType,outputPath,excludes).execute();
  }
 catch (  ParseException e) {
    new HelpFormatter().printHelp("migration-analysis.[sh | bat] [OPTION]...",OPTIONS);
    exit(-1);
  }
}
 

Example 43

From project stackoverflow-java-sdk, under directory /core/src/examples/java/com/google/code/stackexchange/client/examples/.

Source file: AnswersApiExample.java

  19 
vote

/** 
 * The main method.
 * @param args the arguments
 */
public static void main(String[] args){
  Options options=buildOptions();
  try {
    CommandLine line=new BasicParser().parse(options,args);
    processCommandLine(line,options);
  }
 catch (  ParseException exp) {
    System.err.println(exp.getMessage());
    printHelp(options);
  }
}