use of net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup in project kafka by apache.
the class CoordinatorClient method main.
public static void main(String[] args) throws Exception {
ArgumentParser rootParser = ArgumentParsers.newArgumentParser("trogdor-coordinator-client").description("The Trogdor coordinator client.");
Subparsers subParsers = rootParser.addSubparsers().dest("command");
Subparser uptimeParser = subParsers.addParser("uptime").help("Get the coordinator uptime.");
addTargetArgument(uptimeParser);
addJsonArgument(uptimeParser);
Subparser statusParser = subParsers.addParser("status").help("Get the coordinator status.");
addTargetArgument(statusParser);
addJsonArgument(statusParser);
Subparser showTaskParser = subParsers.addParser("showTask").help("Show a coordinator task.");
addTargetArgument(showTaskParser);
addJsonArgument(showTaskParser);
showTaskParser.addArgument("--id", "-i").action(store()).required(true).type(String.class).dest("taskId").metavar("TASK_ID").help("The task ID to show.");
showTaskParser.addArgument("--verbose", "-v").action(storeTrue()).dest("verbose").metavar("VERBOSE").help("Print out everything.");
showTaskParser.addArgument("--show-status", "-S").action(storeTrue()).dest("showStatus").metavar("SHOW_STATUS").help("Show the task status.");
Subparser showTasksParser = subParsers.addParser("showTasks").help("Show many coordinator tasks. By default, all tasks are shown, but " + "command-line options can be specified as filters.");
addTargetArgument(showTasksParser);
addJsonArgument(showTasksParser);
MutuallyExclusiveGroup idGroup = showTasksParser.addMutuallyExclusiveGroup();
idGroup.addArgument("--id", "-i").action(append()).type(String.class).dest("taskIds").metavar("TASK_IDS").help("Show only this task ID. This option may be specified multiple times.");
idGroup.addArgument("--id-pattern").action(store()).type(String.class).dest("taskIdPattern").metavar("TASK_ID_PATTERN").help("Only display tasks which match the given ID pattern.");
showTasksParser.addArgument("--state", "-s").type(TaskStateType.class).dest("taskStateType").metavar("TASK_STATE_TYPE").help("Show only tasks in this state.");
Subparser createTaskParser = subParsers.addParser("createTask").help("Create a new task.");
addTargetArgument(createTaskParser);
createTaskParser.addArgument("--id", "-i").action(store()).required(true).type(String.class).dest("taskId").metavar("TASK_ID").help("The task ID to create.");
createTaskParser.addArgument("--spec", "-s").action(store()).required(true).type(String.class).dest("taskSpec").metavar("TASK_SPEC").help("The task spec to create, or a path to a file containing the task spec.");
Subparser stopTaskParser = subParsers.addParser("stopTask").help("Stop a task.");
addTargetArgument(stopTaskParser);
stopTaskParser.addArgument("--id", "-i").action(store()).required(true).type(String.class).dest("taskId").metavar("TASK_ID").help("The task ID to create.");
Subparser destroyTaskParser = subParsers.addParser("destroyTask").help("Destroy a task.");
addTargetArgument(destroyTaskParser);
destroyTaskParser.addArgument("--id", "-i").action(store()).required(true).type(String.class).dest("taskId").metavar("TASK_ID").help("The task ID to destroy.");
Subparser shutdownParser = subParsers.addParser("shutdown").help("Shut down the coordinator.");
addTargetArgument(shutdownParser);
Namespace res = rootParser.parseArgsOrFail(args);
String target = res.getString("target");
CoordinatorClient client = new Builder().maxTries(3).target(target).build();
ZoneOffset localOffset = OffsetDateTime.now().getOffset();
switch(res.getString("command")) {
case "uptime":
{
UptimeResponse uptime = client.uptime();
if (res.getBoolean("json")) {
System.out.println(JsonUtil.toJsonString(uptime));
} else {
System.out.printf("Coordinator is running at %s.%n", target);
System.out.printf("\tStart time: %s%n", dateString(uptime.serverStartMs(), localOffset));
System.out.printf("\tCurrent server time: %s%n", dateString(uptime.nowMs(), localOffset));
System.out.printf("\tUptime: %s%n", durationString(uptime.nowMs() - uptime.serverStartMs()));
}
break;
}
case "status":
{
CoordinatorStatusResponse response = client.status();
if (res.getBoolean("json")) {
System.out.println(JsonUtil.toJsonString(response));
} else {
System.out.printf("Coordinator is running at %s.%n", target);
System.out.printf("\tStart time: %s%n", dateString(response.serverStartMs(), localOffset));
}
break;
}
case "showTask":
{
String taskId = res.getString("taskId");
TaskRequest req = new TaskRequest(taskId);
TaskState taskState = null;
try {
taskState = client.task(req);
} catch (NotFoundException e) {
System.out.printf("Task %s was not found.%n", taskId);
Exit.exit(1);
}
if (res.getBoolean("json")) {
System.out.println(JsonUtil.toJsonString(taskState));
} else {
System.out.printf("Task %s of type %s is %s. %s%n", taskId, taskState.spec().getClass().getCanonicalName(), taskState.stateType(), prettyPrintTaskInfo(taskState, localOffset));
if (taskState instanceof TaskDone) {
TaskDone taskDone = (TaskDone) taskState;
if ((taskDone.error() != null) && (!taskDone.error().isEmpty())) {
System.out.printf("Error: %s%n", taskDone.error());
}
}
if (res.getBoolean("verbose")) {
System.out.printf("Spec: %s%n%n", JsonUtil.toPrettyJsonString(taskState.spec()));
}
if (res.getBoolean("verbose") || res.getBoolean("showStatus")) {
System.out.printf("Status: %s%n%n", JsonUtil.toPrettyJsonString(taskState.status()));
}
}
break;
}
case "showTasks":
{
TaskStateType taskStateType = res.<TaskStateType>get("taskStateType");
List<String> taskIds = new ArrayList<>();
Pattern taskIdPattern = null;
if (res.getList("taskIds") != null) {
for (Object taskId : res.getList("taskIds")) {
taskIds.add((String) taskId);
}
} else if (res.getString("taskIdPattern") != null) {
try {
taskIdPattern = Pattern.compile(res.getString("taskIdPattern"));
} catch (PatternSyntaxException e) {
System.out.println("Invalid task ID regular expression " + res.getString("taskIdPattern"));
e.printStackTrace();
Exit.exit(1);
}
}
TasksRequest req = new TasksRequest(taskIds, 0, 0, 0, 0, Optional.ofNullable(taskStateType));
TasksResponse response = client.tasks(req);
if (taskIdPattern != null) {
TreeMap<String, TaskState> filteredTasks = new TreeMap<>();
for (Map.Entry<String, TaskState> entry : response.tasks().entrySet()) {
if (taskIdPattern.matcher(entry.getKey()).matches()) {
filteredTasks.put(entry.getKey(), entry.getValue());
}
}
response = new TasksResponse(filteredTasks);
}
if (res.getBoolean("json")) {
System.out.println(JsonUtil.toJsonString(response));
} else {
System.out.println(prettyPrintTasksResponse(response, localOffset));
}
if (response.tasks().isEmpty()) {
Exit.exit(1);
}
break;
}
case "createTask":
{
String taskId = res.getString("taskId");
TaskSpec taskSpec = JsonUtil.objectFromCommandLineArgument(res.getString("taskSpec"), TaskSpec.class);
CreateTaskRequest req = new CreateTaskRequest(taskId, taskSpec);
try {
client.createTask(req);
System.out.printf("Sent CreateTaskRequest for task %s.%n", req.id());
} catch (RequestConflictException rce) {
System.out.printf("CreateTaskRequest for task %s got a 409 status code - " + "a task with the same ID but a different specification already exists.%nException: %s%n", req.id(), rce.getMessage());
Exit.exit(1);
}
break;
}
case "stopTask":
{
String taskId = res.getString("taskId");
StopTaskRequest req = new StopTaskRequest(taskId);
client.stopTask(req);
System.out.printf("Sent StopTaskRequest for task %s.%n", taskId);
break;
}
case "destroyTask":
{
String taskId = res.getString("taskId");
DestroyTaskRequest req = new DestroyTaskRequest(taskId);
client.destroyTask(req);
System.out.printf("Sent DestroyTaskRequest for task %s.%n", taskId);
break;
}
case "shutdown":
{
client.shutdown();
System.out.println("Sent ShutdownRequest.");
break;
}
default:
{
System.out.println("You must choose an action. Type --help for help.");
Exit.exit(1);
}
}
}
use of net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup in project pcgen by PCGen.
the class Main method getParser.
/**
* @return an ArgumentParser used to peform argument parsing
*/
private static ArgumentParser getParser() {
ArgumentParser parser = ArgumentParsers.newArgumentParser(Constants.APPLICATION_NAME).defaultHelp(false).description("RPG Character Generator").version(PCGenPropBundle.getVersionNumber());
parser.addArgument("-v", "--verbose").help("verbose logging").type(Boolean.class).action(Arguments.count());
parser.addArgument("-V", "--version").action(Arguments.version());
parser.addArgument("-J").help("ignore java version checks").action(Arguments.storeTrue());
MutuallyExclusiveGroup startupMode = parser.addMutuallyExclusiveGroup().description("start up on a specific mode");
startupMode.addArgument("-G", "--gmgen").help("GMGen mode").type(Boolean.class).action(Arguments.storeTrue());
startupMode.addArgument("-N", "--npc").help("NPC generation mode").type(Boolean.class).action(Arguments.storeTrue());
startupMode.addArgument("--name-generator").help("run the name generator").type(Boolean.class).action(Arguments.storeTrue());
startupMode.addArgument("-D", "--tab").nargs(1);
parser.addArgument("-s", "--settingsdir").nargs(1).type(Arguments.fileType().verifyIsDirectory().verifyCanRead().verifyExists());
parser.addArgument("-m", "--campaignmode").nargs(1).type(String.class);
parser.addArgument("-E", "--exportsheet").nargs(1).type(Arguments.fileType().verifyCanRead().verifyExists().verifyIsFile());
parser.addArgument("-o", "--outputfile").nargs(1).type(Arguments.fileType().verifyCanCreate().verifyCanWrite().verifyNotExists());
parser.addArgument("-c", "--character").nargs(1).type(Arguments.fileType().verifyCanRead().verifyExists().verifyIsFile());
parser.addArgument("-p", "--party").nargs(1).type(Arguments.fileType().verifyCanRead().verifyExists().verifyIsFile());
return parser;
}
use of net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup in project java-docs-samples by GoogleCloudPlatform.
the class SynthesizeFile method main.
// [END tts_synthesize_ssml_file]
public static void main(String... args) throws Exception {
ArgumentParser parser = ArgumentParsers.newFor("SynthesizeFile").build().defaultHelp(true).description("Synthesize a text file or ssml file.");
MutuallyExclusiveGroup group = parser.addMutuallyExclusiveGroup().required(true);
group.addArgument("--text").help("The text file from which to synthesize speech.");
group.addArgument("--ssml").help("The ssml file from which to synthesize speech.");
try {
Namespace namespace = parser.parseArgs(args);
if (namespace.get("text") != null) {
synthesizeTextFile(namespace.getString("text"));
} else {
synthesizeSsmlFile(namespace.getString("ssml"));
}
} catch (ArgumentParserException e) {
parser.handleError(e);
}
}
use of net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup in project kafka by apache.
the class ProducerPerformance method argParser.
/**
* Get the command-line argument parser.
*/
static ArgumentParser argParser() {
ArgumentParser parser = ArgumentParsers.newArgumentParser("producer-performance").defaultHelp(true).description("This tool is used to verify the producer performance.");
MutuallyExclusiveGroup payloadOptions = parser.addMutuallyExclusiveGroup().required(true).description("either --record-size or --payload-file must be specified but not both.");
parser.addArgument("--topic").action(store()).required(true).type(String.class).metavar("TOPIC").help("produce messages to this topic");
parser.addArgument("--num-records").action(store()).required(true).type(Long.class).metavar("NUM-RECORDS").dest("numRecords").help("number of messages to produce");
payloadOptions.addArgument("--record-size").action(store()).required(false).type(Integer.class).metavar("RECORD-SIZE").dest("recordSize").help("message size in bytes. Note that you must provide exactly one of --record-size or --payload-file.");
payloadOptions.addArgument("--payload-file").action(store()).required(false).type(String.class).metavar("PAYLOAD-FILE").dest("payloadFile").help("file to read the message payloads from. This works only for UTF-8 encoded text files. " + "Payloads will be read from this file and a payload will be randomly selected when sending messages. " + "Note that you must provide exactly one of --record-size or --payload-file.");
parser.addArgument("--payload-delimiter").action(store()).required(false).type(String.class).metavar("PAYLOAD-DELIMITER").dest("payloadDelimiter").setDefault("\\n").help("provides delimiter to be used when --payload-file is provided. " + "Defaults to new line. " + "Note that this parameter will be ignored if --payload-file is not provided.");
parser.addArgument("--throughput").action(store()).required(true).type(Integer.class).metavar("THROUGHPUT").help("throttle maximum message throughput to *approximately* THROUGHPUT messages/sec. Set this to -1 to disable throttling.");
parser.addArgument("--producer-props").nargs("+").required(false).metavar("PROP-NAME=PROP-VALUE").type(String.class).dest("producerConfig").help("kafka producer related configuration properties like bootstrap.servers,client.id etc. " + "These configs take precedence over those passed via --producer.config.");
parser.addArgument("--producer.config").action(store()).required(false).type(String.class).metavar("CONFIG-FILE").dest("producerConfigFile").help("producer config properties file.");
parser.addArgument("--print-metrics").action(storeTrue()).type(Boolean.class).metavar("PRINT-METRICS").dest("printMetrics").help("print out metrics at the end of the test.");
parser.addArgument("--transactional-id").action(store()).required(false).type(String.class).metavar("TRANSACTIONAL-ID").dest("transactionalId").setDefault("performance-producer-default-transactional-id").help("The transactionalId to use if transaction-duration-ms is > 0. Useful when testing the performance of concurrent transactions.");
parser.addArgument("--transaction-duration-ms").action(store()).required(false).type(Long.class).metavar("TRANSACTION-DURATION").dest("transactionDurationMs").setDefault(0L).help("The max age of each transaction. The commitTransaction will be called after this time has elapsed. Transactions are only enabled if this value is positive.");
return parser;
}
use of net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup in project kafka by apache.
the class VerifiableConsumer method argParser.
private static ArgumentParser argParser() {
ArgumentParser parser = ArgumentParsers.newArgumentParser("verifiable-consumer").defaultHelp(true).description("This tool consumes messages from a specific topic and emits consumer events (e.g. group rebalances, received messages, and offsets committed) as JSON objects to STDOUT.");
MutuallyExclusiveGroup connectionGroup = parser.addMutuallyExclusiveGroup("Connection Group").description("Group of arguments for connection to brokers").required(true);
connectionGroup.addArgument("--bootstrap-server").action(store()).required(false).type(String.class).metavar("HOST1:PORT1[,HOST2:PORT2[...]]").dest("bootstrapServer").help("REQUIRED unless --broker-list(deprecated) is specified. The server(s) to connect to. Comma-separated list of Kafka brokers in the form HOST1:PORT1,HOST2:PORT2,...");
connectionGroup.addArgument("--broker-list").action(store()).required(false).type(String.class).metavar("HOST1:PORT1[,HOST2:PORT2[...]]").dest("brokerList").help("DEPRECATED, use --bootstrap-server instead; ignored if --bootstrap-server is specified. Comma-separated list of Kafka brokers in the form HOST1:PORT1,HOST2:PORT2,...");
parser.addArgument("--topic").action(store()).required(true).type(String.class).metavar("TOPIC").help("Consumes messages from this topic.");
parser.addArgument("--group-id").action(store()).required(true).type(String.class).metavar("GROUP_ID").dest("groupId").help("The groupId shared among members of the consumer group");
parser.addArgument("--group-instance-id").action(store()).required(false).type(String.class).metavar("GROUP_INSTANCE_ID").dest("groupInstanceId").help("A unique identifier of the consumer instance");
parser.addArgument("--max-messages").action(store()).required(false).type(Integer.class).setDefault(-1).metavar("MAX-MESSAGES").dest("maxMessages").help("Consume this many messages. If -1 (the default), the consumer will consume until the process is killed externally");
parser.addArgument("--session-timeout").action(store()).required(false).setDefault(30000).type(Integer.class).metavar("TIMEOUT_MS").dest("sessionTimeout").help("Set the consumer's session timeout");
parser.addArgument("--verbose").action(storeTrue()).type(Boolean.class).metavar("VERBOSE").help("Enable to log individual consumed records");
parser.addArgument("--enable-autocommit").action(storeTrue()).type(Boolean.class).metavar("ENABLE-AUTOCOMMIT").dest("useAutoCommit").help("Enable offset auto-commit on consumer");
parser.addArgument("--reset-policy").action(store()).required(false).setDefault("earliest").type(String.class).dest("resetPolicy").help("Set reset policy (must be either 'earliest', 'latest', or 'none'");
parser.addArgument("--assignment-strategy").action(store()).required(false).setDefault(RangeAssignor.class.getName()).type(String.class).dest("assignmentStrategy").help("Set assignment strategy (e.g. " + RoundRobinAssignor.class.getName() + ")");
parser.addArgument("--consumer.config").action(store()).required(false).type(String.class).metavar("CONFIG_FILE").help("Consumer config properties file (config options shared with command line parameters will be overridden).");
return parser;
}
Aggregations