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

The following examples show how to use org.apache.commons.cli.CommandLine. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: rocketmq   Source File: UpdateKvConfigCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
    try {
        // namespace
        String namespace = commandLine.getOptionValue('s').trim();
        // key name
        String key = commandLine.getOptionValue('k').trim();
        // key name
        String value = commandLine.getOptionValue('v').trim();

        defaultMQAdminExt.start();
        defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
        System.out.printf("create or update kv config to namespace success.%n");
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 2
Source Project: james-project   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
private static void runCommand(CommandLine cmd) throws Exception {
    boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION, Boolean.toString(false)));
    File file = new File(cmd.getOptionValue(FILE_OPTION));
    if (file.exists()) {
        try {
            Port port = new Port(Integer.parseInt(cmd.getOptionValue(PORT_OPTION)));    
            String host = cmd.getOptionValue(HOST_OPTION, "localhost");
            String shabang = cmd.getOptionValue(SHABANG_OPTION, null);
            RunScript runner = new RunScript(file, port, host, shabang, verbose);
            runner.run();
            
        } catch (NumberFormatException e) {
            System.out.println("Port must be numeric");
            System.exit(PORT_NOT_A_NUMBER);
        }
    } else {
        System.out.println("Script not found");
        System.exit(FILE_NOT_FOUND);
    }
}
 
Example 3
public static void main(String[] args) throws IOException {
  CommandLine parsedArgs = BaseOption.parseOptions(args);
  File configPath = null;
  if (!NO_CONFIG.isSet(parsedArgs)) {
    configPath = BaseOption.checkedConfigPath(parsedArgs);
  }
  ContentConfig config = ContentConfig.load(configPath);

  ShoppingContent.Builder builder = createStandardBuilder(parsedArgs, config);
  ShoppingContent content = createService(builder);
  ShoppingContent sandbox = createSandboxContentService(builder);
  retrieveConfiguration(content, config);

  try {
    new DatafeedsWorkflow(content, sandbox, config).execute();
  } catch (GoogleJsonResponseException e) {
    checkGoogleJsonResponseException(e);
  }
}
 
Example 4
Source Project: rocketmq-4.3.0   Source File: QueryMsgByKeySubCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);

    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));

    try {
        final String topic = commandLine.getOptionValue('t').trim();
        final String key = commandLine.getOptionValue('k').trim();

        this.queryByKey(defaultMQAdminExt, topic, key);
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 5
Source Project: ipst   Source File: ListOfflineWorkflowsTool.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    try (OfflineApplication app = new RemoteOfflineApplicationImpl()) {
        Map<String, OfflineWorkflowStatus> statuses = app.listWorkflows();
        Table table = new Table(4, BorderStyle.CLASSIC_WIDE);
        table.addCell("ID");
        table.addCell("Running");
        table.addCell("Step");
        table.addCell("Time");
        for (Map.Entry<String, OfflineWorkflowStatus> entry : statuses.entrySet()) {
            String workflowId = entry.getKey();
            OfflineWorkflowStatus status = entry.getValue();
            Duration remaining = null;
            if (status.getStartTime() != null) {
                remaining = Duration.millis(status.getStartParameters().getDuration() * 60 * 1000)
                        .minus(new Duration(status.getStartTime(), DateTime.now()));
            }
            table.addCell(workflowId);
            table.addCell(Boolean.toString(status.isRunning()));
            table.addCell(status.getStep() != null ? status.getStep().toString() : "");
            table.addCell(remaining != null ? PeriodFormat.getDefault().print(remaining.toPeriod()) : "");
        }
        context.getOutputStream().println(table.render());
    }
}
 
Example 6
@Override
public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
    String topic = commandLine.getOptionValue('t').trim();
    try {
        defaultMQAdminExt.start();
        Set<String> clusters = defaultMQAdminExt.getTopicClusterList(topic);
        for (String value : clusters) {
            System.out.printf("%s%n", value);
        }
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 7
Source Project: flink   Source File: FlinkYarnSessionCliTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCorrectSettingOfMaxSlots() throws Exception {
	String[] params =
		new String[] {"-ys", "3"};

	FlinkYarnSessionCli yarnCLI = createFlinkYarnSessionCliWithJmAndTmTotalMemory(2048);

	final CommandLine commandLine = yarnCLI.parseCommandLineOptions(params, true);

	final Configuration executorConfig = yarnCLI.applyCommandLineOptionsToConfiguration(commandLine);
	final ClusterClientFactory<ApplicationId> clientFactory = getClusterClientFactory(executorConfig);
	final ClusterSpecification clusterSpecification = clientFactory.getClusterSpecification(executorConfig);

	// each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased.
	assertEquals(3, clusterSpecification.getSlotsPerTaskManager());
}
 
Example 8
@Test
public void testInvalidConfig() {
	try {
		String[] arguments = {};
		CommandLine line = new PosixParser().parse(CliFrontend.getJobManagerAddressOption(new Options()), arguments, false);
			
		TestingCliFrontend frontend = new TestingCliFrontend(CliFrontendTestUtils.getInvalidConfigDir());
		
		assertTrue(frontend.getJobManagerAddress(line) == null);
	}
	catch (Exception e) {
		System.err.println(e.getMessage());
		e.printStackTrace();
		fail("Program caused an exception: " + e.getMessage());
	}
}
 
Example 9
Source Project: flink   Source File: AbstractCustomCommandLine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Configuration applyCommandLineOptionsToConfiguration(CommandLine commandLine) throws FlinkException {
	final Configuration resultingConfiguration = new Configuration(configuration);
	resultingConfiguration.setString(DeploymentOptions.TARGET, RemoteExecutor.NAME);

	if (commandLine.hasOption(addressOption.getOpt())) {
		String addressWithPort = commandLine.getOptionValue(addressOption.getOpt());
		InetSocketAddress jobManagerAddress = NetUtils.parseHostPortAddress(addressWithPort);
		setJobManagerAddressInConfig(resultingConfiguration, jobManagerAddress);
	}

	if (commandLine.hasOption(zookeeperNamespaceOption.getOpt())) {
		String zkNamespace = commandLine.getOptionValue(zookeeperNamespaceOption.getOpt());
		resultingConfiguration.setString(HighAvailabilityOptions.HA_CLUSTER_ID, zkNamespace);
	}

	return resultingConfiguration;
}
 
Example 10
Source Project: hmftools   Source File: CopyNumberAnalyser.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void main(@NotNull final String[] args) throws ParseException, SQLException
{
    final Options options = new Options();
    CopyNumberAnalyser.addCmdLineArgs(options);

    final CommandLineParser parser = new DefaultParser();
    final CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption(LOG_DEBUG))
    {
        Configurator.setRootLevel(Level.DEBUG);
    }

    String outputDir = formOutputPath(cmd.getOptionValue(DATA_OUTPUT_DIR));

    final DatabaseAccess dbAccess = cmd.hasOption(DB_URL) ? databaseAccess(cmd) : null;

    CopyNumberAnalyser cnAnalyser = new CopyNumberAnalyser(outputDir, dbAccess);
    cnAnalyser.loadConfig(cmd);

    cnAnalyser.runAnalysis();
    cnAnalyser.close();

    LNX_LOGGER.info("CN analysis complete");
}
 
Example 11
Source Project: incubator-retired-blur   Source File: TermsDataCommand.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-access")
private static CommandLine parse(String[] otherArgs, Writer out) {
  Options options = new Options();
  options.addOption(OptionBuilder.withArgName("startwith").hasArg().withDescription("The value to start with.")
      .create("s"));
  options.addOption(OptionBuilder.withArgName("size").hasArg().withDescription("The number of terms to return.")
      .create("n"));
  options.addOption(OptionBuilder.withDescription("Get the frequency of each term.").create("F"));

  CommandLineParser parser = new PosixParser();
  CommandLine cmd = null;
  try {
    cmd = parser.parse(options, otherArgs);
  } catch (ParseException e) {
    HelpFormatter formatter = new HelpFormatter();
    PrintWriter pw = new PrintWriter(out, true);
    formatter.printHelp(pw, HelpFormatter.DEFAULT_WIDTH, "terms", null, options, HelpFormatter.DEFAULT_LEFT_PAD,
        HelpFormatter.DEFAULT_DESC_PAD, null, false);
    return null;
  }
  return cmd;
}
 
Example 12
Source Project: flink   Source File: FlinkYarnSessionCli.java    License: Apache License 2.0 6 votes vote down vote up
private String encodeDynamicProperties(final CommandLine cmd) {
	final Properties properties = cmd.getOptionProperties(dynamicproperties.getOpt());
	final String[] dynamicProperties = properties.stringPropertyNames().stream()
			.flatMap(
					(String key) -> {
						final String value = properties.getProperty(key);

						LOG.info("Dynamic Property set: {}={}", key, GlobalConfiguration.isSensitive(key) ? GlobalConfiguration.HIDDEN_CONTENT : value);

						if (value != null) {
							return Stream.of(key + dynamicproperties.getValueSeparator() + value);
						} else {
							return Stream.empty();
						}
					})
			.toArray(String[]::new);

	return StringUtils.join(dynamicProperties, YARN_DYNAMIC_PROPERTIES_SEPARATOR);
}
 
Example 13
Source Project: rocketmq   Source File: UpdateKvConfigCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
    try {
        // namespace
        String namespace = commandLine.getOptionValue('s').trim();
        // key name
        String key = commandLine.getOptionValue('k').trim();
        // key name
        String value = commandLine.getOptionValue('v').trim();

        defaultMQAdminExt.start();
        defaultMQAdminExt.createAndUpdateKvConfig(namespace, key, value);
        System.out.printf("create or update kv config to namespace success.%n");
        return;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 14
Source Project: powsybl-core   Source File: ConversionTool.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    String inputFile = line.getOptionValue(INPUT_FILE);
    String outputFormat = line.getOptionValue(OUTPUT_FORMAT);
    String outputFile = line.getOptionValue(OUTPUT_FILE);

    Exporter exporter = Exporters.getExporter(outputFormat);
    if (exporter == null) {
        throw new PowsyblException("Target format " + outputFormat + " not supported");
    }

    Properties inputParams = readProperties(line, ConversionToolUtils.OptionType.IMPORT, context);
    Network network = Importers.loadNetwork(context.getFileSystem().getPath(inputFile), context.getShortTimeExecutionComputationManager(), createImportConfig(), inputParams);

    Properties outputParams = readProperties(line, ConversionToolUtils.OptionType.EXPORT, context);
    DataSource ds2 = Exporters.createDataSource(context.getFileSystem().getPath(outputFile), new DefaultDataSourceObserver() {
        @Override
        public void opened(String streamName) {
            context.getOutputStream().println("Generating file " + streamName + "...");
        }
    });
    exporter.export(network, outputParams, ds2);
}
 
Example 15
Source Project: distributedlog   Source File: CommandLineUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Optional<Integer> getOptionalIntegerArg(CommandLine cmdline, String arg) throws IllegalArgumentException {
    try {
        if (cmdline.hasOption(arg)) {
            return Optional.of(Integer.parseInt(cmdline.getOptionValue(arg)));
        } else {
            return Optional.absent();
        }
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException(arg + " is not a number");
    }
}
 
Example 16
Source Project: flink   Source File: CliFrontendParser.java    License: Apache License 2.0 5 votes vote down vote up
public static CommandLine parse(Options options, String[] args, boolean stopAtNonOptions) throws CliArgsException {
	final DefaultParser parser = new DefaultParser();

	try {
		return parser.parse(options, args, stopAtNonOptions);
	} catch (ParseException e) {
		throw new CliArgsException(e.getMessage());
	}
}
 
Example 17
@Override
public void execute(final CommandLine commandLine, final Options options, RPCHook rpcHook) throws SubCommandException {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);

    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));

    long printInterval = 1;
    boolean enableInterval = commandLine.hasOption('i');

    if (enableInterval) {
        printInterval = Long.parseLong(commandLine.getOptionValue('i')) * 1000;
    }

    try {
        defaultMQAdminExt.start();
        long i = 0;

        do {
            if (i++ > 0) {
                Thread.sleep(printInterval);
            }
            if (commandLine.hasOption('m')) {
                this.printClusterMoreStats(defaultMQAdminExt);
            } else {
                this.printClusterBaseInfo(defaultMQAdminExt);
            }
        }
        while (enableInterval);
    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
    }
}
 
Example 18
Source Project: Flink-CEPplus   Source File: CliFrontend.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the custom command-line for the arguments.
 * @param commandLine The input to the command-line.
 * @return custom command-line which is active (may only be one at a time)
 */
public CustomCommandLine<?> getActiveCustomCommandLine(CommandLine commandLine) {
	for (CustomCommandLine<?> cli : customCommandLines) {
		if (cli.isActive(commandLine)) {
			return cli;
		}
	}
	throw new IllegalStateException("No command-line ran.");
}
 
Example 19
/**
 * Apply Apache Commons CLI PosixParser to command-line arguments.
 * 
 * @param commandLineArguments
 *            Command-line arguments to be processed with Posix-style parser.
 */
private static CommandLine usePosixParser(final String[] commandLineArguments) {
	final CommandLineParser cmdLinePosixParser = new DefaultParser();
	final Options posixOptions = constructPosixOptions();
	try {
		return cmdLinePosixParser.parse(posixOptions, commandLineArguments);
	} catch (ParseException parseException) {
		System.err
				.println("Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
	}
	return null;
}
 
Example 20
/**
 * Parse extra arguments.
 *
 * @param args Extra arguments array
 * @throws ParseException
 */
void parseExtraArgs(String[] args) throws ParseException {
  // No-op when no extra arguments are present
  if (args == null || args.length == 0) {
    return;
  }

  // We do not need extended abilities of SqoopParser, so we're using
  // Gnu parser instead.
  CommandLineParser parser = new GnuParser();
  CommandLine cmdLine = parser.parse(getExtraOptions(), args, true);

  // Apply extra options
  if (cmdLine.hasOption(SCHEMA)) {
    String schemaName = cmdLine.getOptionValue(SCHEMA);
    LOG.info("We will use schema " + schemaName);

    this.schema = schemaName;
  }

  // Apply table hints
  if (cmdLine.hasOption(TABLE_HINTS)) {
    String hints = cmdLine.getOptionValue(TABLE_HINTS);
    LOG.info("Sqoop will use following table hints for data transfer: "
      + hints);

    this.tableHints = hints;
  }

  identityInserts = cmdLine.hasOption(IDENTITY_INSERT);
}
 
Example 21
Source Project: flink   Source File: DefaultCLI.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StandaloneClusterDescriptor createClusterDescriptor(
		CommandLine commandLine) throws FlinkException {
	final Configuration effectiveConfiguration = applyCommandLineOptionsToConfiguration(commandLine);

	return new StandaloneClusterDescriptor(effectiveConfiguration);
}
 
Example 22
Source Project: DDMQ   Source File: GetBrokerConfigCommandTest.java    License: Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testExecute() throws SubCommandException {
    GetBrokerConfigCommand cmd = new GetBrokerConfigCommand();
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    String[] subargs = new String[] {"-b 127.0.0.1:10911", "-c default-cluster"};
    final CommandLine commandLine =
        ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
    cmd.execute(commandLine, options, null);
}
 
Example 23
Source Project: distributedlog   Source File: CommandLineUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Optional<Boolean> getOptionalBooleanArg(CommandLine cmdline, String arg) {
    if (cmdline.hasOption(arg)) {
        return Optional.of(true);
    } else {
        return Optional.absent();
    }
}
 
Example 24
/**
 * Given a command line, check for the required options and return an IRI to be used as the
 * OntologyIRI for the output ontology.
 *
 * @param line the command line to use
 * @return the IRI for the output ontology, or null
 */
public static IRI getOutputIRI(CommandLine line) {
  String outputIRIString = getOptionalValue(line, "output-iri");
  IRI outputIRI = null;
  if (outputIRIString != null) {
    outputIRI = IRI.create(outputIRIString);
  }
  return outputIRI;
}
 
Example 25
Source Project: bboxdb   Source File: CLI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read and convert the bounding box from CLI args
 * @param line
 * @return
 */
private Hyperrectangle getBoundingBoxFromArgs(final CommandLine line) {
	final String bbox = line.getOptionValue(CLIParameter.BOUNDING_BOX);
	final Optional<Hyperrectangle> resultBox = HyperrectangleHelper.parseBBox(bbox);
	
	if(! resultBox.isPresent()) {
		System.err.println("Invalid bounding box: " + bbox);
		System.exit(-1);
	}
	
	return resultBox.get();
}
 
Example 26
@Ignore
@Test
public void testExecute() throws SubCommandException {
    ProducerConnectionSubCommand cmd = new ProducerConnectionSubCommand();
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    String[] subargs = new String[] {"-g default-producer-group", "-t unit-test"};
    final CommandLine commandLine =
        ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
    cmd.execute(commandLine, options, null);
}
 
Example 27
Source Project: vsphere-automation-sdk-java   Source File: ParametersHelper.java    License: MIT License 5 votes vote down vote up
private Object getOptionValueFromCmdLine(Option option, CommandLine cmd) {
    Object optionValue = null;
    if(!option.hasArg()) {
        if(cmd.hasOption(option.getLongOpt())) {
            optionValue = true;
        }
    }
    else {
        optionValue = cmd.getOptionValue(option.getLongOpt());
    }

    return optionValue;
}
 
Example 28
Source Project: sqoop-on-spark   Source File: SqoopSparkJob.java    License: Apache License 2.0 5 votes vote down vote up
public static CommandLine parseArgs(Options options, String[] args) {

    CommandLine commandLineArgs;
    try {
      // parse the command line arguments
      commandLineArgs = parser.parse(options, args, false);
    } catch (ParseException pe) {
      throw new RuntimeException("Parsing failed for command option:", pe);
    }
    return commandLineArgs;
  }
 
Example 29
Source Project: act   Source File: ReactionValidator.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Options opts = new Options();
  for (Option.Builder b : OPTION_BUILDERS) {
    opts.addOption(b.build());
  }

  CommandLine cl = null;
  try {
    CommandLineParser parser = new DefaultParser();
    cl = parser.parse(opts, args);
  } catch (ParseException e) {
    System.err.format("Argument parsing failed: %s\n", e.getMessage());
    HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
    System.exit(1);
  }

  if (cl.hasOption("help")) {
    HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
    return;
  }

  NoSQLAPI api = new NoSQLAPI(cl.getOptionValue(OPTION_READ_DB), cl.getOptionValue(OPTION_READ_DB));
  MechanisticValidator validator = new MechanisticValidator(api);
  validator.init();

  Map<Integer, List<Ero>> results = validator.validateOneReaction(Long.parseLong(cl.getOptionValue(OPTION_RXN_ID)));

  if (results == null) {
    System.out.format("ERROR: validation results are null.\n");
  } else if (results.size() == 0) {
    System.out.format("No matching EROs were found for the specified reaction.\n");
  } else {
    for (Map.Entry<Integer, List<Ero>> entry : results.entrySet()) {
      List<String> eroIds = entry.getValue().stream().map(x -> x.getId().toString()).collect(Collectors.toList());
      System.out.format("%d: %s\n", entry.getKey(), StringUtils.join(eroIds, ", "));
    }
  }
}
 
Example 30
Source Project: distributedlog   Source File: DistributedLogAdmin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void parseCommandLine(CommandLine cmdline) throws ParseException {
    super.parseCommandLine(cmdline);
    if (!cmdline.hasOption("s")) {
        throw new ParseException("No stream to set ACL");
    }
    stream = cmdline.getOptionValue("s");
}