diff --git a/distribution/server/src/assemble/LICENSE.bin.txt b/distribution/server/src/assemble/LICENSE.bin.txt
index b96786f234bed..545292f2ba85a 100644
--- a/distribution/server/src/assemble/LICENSE.bin.txt
+++ b/distribution/server/src/assemble/LICENSE.bin.txt
@@ -244,6 +244,9 @@ This projects includes binary packages with the following licenses:
The Apache Software License, Version 2.0
* JCommander -- com.beust-jcommander-1.82.jar
+ * Picocli
+ - info.picocli-picocli-4.7.5.jar
+ - info.picocli-picocli-shell-jline3-4.7.5.jar
* High Performance Primitive Collections for Java -- com.carrotsearch-hppc-0.9.1.jar
* Jackson
- com.fasterxml.jackson.core-jackson-annotations-2.14.2.jar
diff --git a/distribution/shell/src/assemble/LICENSE.bin.txt b/distribution/shell/src/assemble/LICENSE.bin.txt
index 8ddcbcfb1600d..a9bbd541448fc 100644
--- a/distribution/shell/src/assemble/LICENSE.bin.txt
+++ b/distribution/shell/src/assemble/LICENSE.bin.txt
@@ -310,6 +310,9 @@ This projects includes binary packages with the following licenses:
The Apache Software License, Version 2.0
* JCommander -- jcommander-1.82.jar
+ * Picocli
+ - picocli-4.7.5.jar
+ - picocli-shell-jline3-4.7.5.jar
* Jackson
- jackson-annotations-2.14.2.jar
- jackson-core-2.14.2.jar
diff --git a/distribution/shell/src/assemble/NOTICE.bin.txt b/distribution/shell/src/assemble/NOTICE.bin.txt
index 7705416042a17..41c9bd7d217da 100644
--- a/distribution/shell/src/assemble/NOTICE.bin.txt
+++ b/distribution/shell/src/assemble/NOTICE.bin.txt
@@ -17,6 +17,9 @@ Copyright (c) 2005 Brian Goetz and Tim Peierls
JCommander
Copyright 2010 Cedric Beust cedric@beust.com
+picocli (http://picocli.info)
+Copyright 2017 Remko Popma
+
EA Agent Loader
Copyright (C) 2015 Electronic Arts Inc. All rights reserved.
diff --git a/pom.xml b/pom.xml
index f161165b7b924..359ac8963cc8e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -259,6 +259,7 @@ flexible messaging model and an intuitive client API.
1.34.1-alpha
1.32.1-alpha
1.23.1-alpha
+ 4.7.5
1.18.3
@@ -691,6 +692,18 @@ flexible messaging model and an intuitive client API.
${jcommander.version}
+
+ info.picocli
+ picocli
+ ${picocli.version}
+
+
+
+ info.picocli
+ picocli-shell-jline3
+ ${picocli.version}
+
+
com.google.guava
guava
diff --git a/pulsar-cli-utils/pom.xml b/pulsar-cli-utils/pom.xml
index 896f464ccd5d6..ac442b4004e8b 100644
--- a/pulsar-cli-utils/pom.xml
+++ b/pulsar-cli-utils/pom.xml
@@ -40,7 +40,11 @@
jcommander
compile
-
+
+ info.picocli
+ picocli
+ compile
+
org.apache.commons
commons-lang3
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/ValueValidationUtil.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/ValueValidationUtil.java
index c2000e1c7bc5a..751f69b20c4dd 100644
--- a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/ValueValidationUtil.java
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/ValueValidationUtil.java
@@ -18,7 +18,6 @@
*/
package org.apache.pulsar.cli;
-import com.beust.jcommander.ParameterException;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
@@ -27,31 +26,31 @@ public class ValueValidationUtil {
public static void maxValueCheck(String paramName, long value, long maxValue) {
if (value > maxValue) {
- throw new ParameterException(paramName + " cannot be bigger than <" + maxValue + ">!");
+ throw new IllegalArgumentException(paramName + " cannot be bigger than <" + maxValue + ">!");
}
}
public static void positiveCheck(String paramName, long value) {
if (value <= 0) {
- throw new ParameterException(paramName + " cannot be less than or equal to <0>!");
+ throw new IllegalArgumentException(paramName + " cannot be less than or equal to <0>!");
}
}
public static void positiveCheck(String paramName, int value) {
if (value <= 0) {
- throw new ParameterException(paramName + " cannot be less than or equal to <0>!");
+ throw new IllegalArgumentException(paramName + " cannot be less than or equal to <0>!");
}
}
public static void emptyCheck(String paramName, String value) {
if (StringUtils.isEmpty(value)) {
- throw new ParameterException("The value of " + paramName + " can't be empty");
+ throw new IllegalArgumentException("The value of " + paramName + " can't be empty");
}
}
public static void minValueCheck(String name, Long value, long min) {
if (value < min) {
- throw new ParameterException(name + " cannot be less than <" + min + ">!");
+ throw new IllegalArgumentException(name + " cannot be less than <" + min + ">!");
}
}
}
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitUtil.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitUtil.java
index cc6140dfced46..8b5a0aafcdb6a 100644
--- a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitUtil.java
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitUtil.java
@@ -18,7 +18,6 @@
*/
package org.apache.pulsar.cli.converters;
-import com.beust.jcommander.ParameterException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
@@ -26,12 +25,12 @@
import lombok.experimental.UtilityClass;
@UtilityClass
-class ByteUnitUtil {
+public class ByteUnitUtil {
private static Set sizeUnit = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList('k', 'K', 'm', 'M', 'g', 'G', 't', 'T')));
- static long validateSizeString(String byteStr) {
+ public static long validateSizeString(String byteStr) {
if (byteStr.isEmpty()) {
throw new IllegalArgumentException("byte string cannot be empty");
}
@@ -44,7 +43,7 @@ static long validateSizeString(String byteStr) {
? Long.parseLong(subStr)
: Long.parseLong(byteStr);
} catch (IllegalArgumentException e) {
- throw new ParameterException(String.format("Invalid size '%s'. Valid formats are: %s",
+ throw new IllegalArgumentException(String.format("Invalid size '%s'. Valid formats are: %s",
byteStr, "(4096, 100K, 10M, 16G, 2T)"));
}
switch (last) {
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitIntegerConverter.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToIntegerConverter.java
similarity index 60%
rename from pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitIntegerConverter.java
rename to pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToIntegerConverter.java
index b148d238b149d..2e5a15c9d9c41 100644
--- a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/ByteUnitIntegerConverter.java
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToIntegerConverter.java
@@ -16,26 +16,20 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pulsar.cli.converters;
+package org.apache.pulsar.cli.converters.picocli;
-import static org.apache.pulsar.cli.ValueValidationUtil.emptyCheck;
import static org.apache.pulsar.cli.converters.ByteUnitUtil.validateSizeString;
-import com.beust.jcommander.converters.BaseConverter;
-
-public class ByteUnitIntegerConverter extends BaseConverter {
-
- public ByteUnitIntegerConverter(String optionName) {
- super(optionName);
- }
+import picocli.CommandLine.ITypeConverter;
+import picocli.CommandLine.TypeConversionException;
+public class ByteUnitToIntegerConverter implements ITypeConverter {
@Override
- public Integer convert(String argStr) {
- return parseBytes(argStr).intValue();
- }
-
- Long parseBytes(String argStr) {
- emptyCheck(getOptionName(), argStr);
- long valueInBytes = validateSizeString(argStr);
- return valueInBytes;
+ public Integer convert(String value) throws Exception {
+ try {
+ long l = validateSizeString(value);
+ return (int) l;
+ } catch (Exception e) {
+ throw new TypeConversionException(e.getMessage());
+ }
}
}
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToLongConverter.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToLongConverter.java
new file mode 100644
index 0000000000000..519cf3dc4c32b
--- /dev/null
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/ByteUnitToLongConverter.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.cli.converters.picocli;
+
+import static org.apache.pulsar.cli.converters.ByteUnitUtil.validateSizeString;
+import picocli.CommandLine.ITypeConverter;
+import picocli.CommandLine.TypeConversionException;
+
+public class ByteUnitToLongConverter implements ITypeConverter {
+ @Override
+ public Long convert(String value) throws Exception {
+ try {
+ return validateSizeString(value);
+ } catch (Exception e) {
+ throw new TypeConversionException(e.getMessage());
+ }
+ }
+}
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/TimeUnitToMillisConverter.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToMillisConverter.java
similarity index 54%
rename from pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/TimeUnitToMillisConverter.java
rename to pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToMillisConverter.java
index 38ff4f501a67a..008467a23e6d8 100644
--- a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/TimeUnitToMillisConverter.java
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToMillisConverter.java
@@ -16,27 +16,20 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pulsar.cli.converters;
+package org.apache.pulsar.cli.converters.picocli;
-import static org.apache.pulsar.cli.ValueValidationUtil.emptyCheck;
-import com.beust.jcommander.ParameterException;
-import com.beust.jcommander.converters.BaseConverter;
import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.cli.converters.RelativeTimeUtil;
+import picocli.CommandLine.ITypeConverter;
+import picocli.CommandLine.TypeConversionException;
-public class TimeUnitToMillisConverter extends BaseConverter {
-
- public TimeUnitToMillisConverter(String optionName) {
- super(optionName);
- }
-
+public class TimeUnitToMillisConverter implements ITypeConverter {
@Override
- public Long convert(String str) {
- emptyCheck(getOptionName(), str);
+ public Long convert(String value) throws Exception {
try {
- return TimeUnit.SECONDS.toMillis(
- RelativeTimeUtil.parseRelativeTimeInSeconds(str.trim()));
- } catch (IllegalArgumentException exception) {
- throw new ParameterException("For input " + getOptionName() + ": " + exception.getMessage());
+ return TimeUnit.SECONDS.toMillis(RelativeTimeUtil.parseRelativeTimeInSeconds(value));
+ } catch (Exception e) {
+ throw new TypeConversionException(e.getMessage());
}
}
}
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToSecondsConverter.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToSecondsConverter.java
new file mode 100644
index 0000000000000..231fa19bdd56c
--- /dev/null
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/TimeUnitToSecondsConverter.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.cli.converters.picocli;
+
+import java.util.concurrent.TimeUnit;
+import org.apache.pulsar.cli.converters.RelativeTimeUtil;
+import picocli.CommandLine.ITypeConverter;
+import picocli.CommandLine.TypeConversionException;
+
+public class TimeUnitToSecondsConverter implements ITypeConverter {
+ @Override
+ public Long convert(String value) throws Exception {
+ try {
+ return TimeUnit.SECONDS.toSeconds(RelativeTimeUtil.parseRelativeTimeInSeconds(value));
+ } catch (Exception e) {
+ throw new TypeConversionException(e.getMessage());
+ }
+ }
+}
diff --git a/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/package-info.java b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/package-info.java
new file mode 100644
index 0000000000000..bdb3e1e85dd19
--- /dev/null
+++ b/pulsar-cli-utils/src/main/java/org/apache/pulsar/cli/converters/picocli/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.cli.converters.picocli;
diff --git a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/ValueValidationUtilTest.java b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/ValueValidationUtilTest.java
index 9d44ee41a2e25..06db820819970 100644
--- a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/ValueValidationUtilTest.java
+++ b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/ValueValidationUtilTest.java
@@ -19,14 +19,13 @@
package org.apache.pulsar.cli;
import static org.testng.Assert.assertThrows;
-import com.beust.jcommander.ParameterException;
import org.testng.annotations.Test;
public class ValueValidationUtilTest {
@Test
public void testMaxValueCheck() {
- assertThrows(ParameterException.class, () -> ValueValidationUtil.maxValueCheck("param1", 11L, 10L));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.maxValueCheck("param1", 11L, 10L));
ValueValidationUtil.maxValueCheck("param2", 10L, 10L);
ValueValidationUtil.maxValueCheck("param3", 9L, 10L);
}
@@ -34,34 +33,34 @@ public void testMaxValueCheck() {
@Test
public void testPositiveCheck() {
// Long
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param1", 0L));
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param2", -1L));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param1", 0L));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param2", -1L));
ValueValidationUtil.positiveCheck("param3", 1L);
// Integer
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param4", 0));
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param5", -1));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param4", 0));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param5", -1));
ValueValidationUtil.positiveCheck("param6", 1);
}
@Test
public void testEmptyCheck() {
- assertThrows(ParameterException.class, () -> ValueValidationUtil.emptyCheck("param1", ""));
- assertThrows(ParameterException.class, () -> ValueValidationUtil.emptyCheck("param2", null));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.emptyCheck("param1", ""));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.emptyCheck("param2", null));
ValueValidationUtil.emptyCheck("param3", "nonEmpty");
}
@Test
public void testMinValueCheck() {
- assertThrows(ParameterException.class, () -> ValueValidationUtil.minValueCheck("param1", 9L, 10L));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.minValueCheck("param1", 9L, 10L));
ValueValidationUtil.minValueCheck("param2", 10L, 10L);
ValueValidationUtil.minValueCheck("param3", 11L, 10L);
}
@Test
public void testPositiveCheckInt() {
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param1", 0));
- assertThrows(ParameterException.class, () -> ValueValidationUtil.positiveCheck("param2", -1));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param1", 0));
+ assertThrows(IllegalArgumentException.class, () -> ValueValidationUtil.positiveCheck("param2", -1));
ValueValidationUtil.positiveCheck("param3", 1);
}
}
diff --git a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/ByteConversionTest.java b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/ByteConversionTest.java
index d669d455df1eb..283e94bfb9c9e 100644
--- a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/ByteConversionTest.java
+++ b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/ByteConversionTest.java
@@ -18,12 +18,12 @@
*/
package org.apache.pulsar.cli.converters;
-import com.beust.jcommander.ParameterException;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
+import org.apache.pulsar.cli.converters.picocli.ByteUnitToIntegerConverter;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import picocli.CommandLine.TypeConversionException;
public class ByteConversionTest {
@@ -65,31 +65,27 @@ public void testSuccessfulByteUnitToLongConverter(String input, long expected) {
}
@Test(dataProvider = "successfulByteUnitUtilTestCases")
- public void testSuccessfulByteUnitIntegerConverter(String input, long expected) {
- ByteUnitIntegerConverter converter = new ByteUnitIntegerConverter("optionName");
+ public void testSuccessfulByteUnitIntegerConverter(String input, long expected) throws Exception {
+ ByteUnitToIntegerConverter converter = new ByteUnitToIntegerConverter();
// Since the converter returns an Integer, we need to cast expected to int
assertEquals(converter.convert(input), Integer.valueOf((int) expected));
}
@Test(dataProvider = "failingByteUnitUtilTestCases")
public void testFailedByteUnitUtilConversion(String input) {
- if (input.isEmpty()) {
- assertThrows(IllegalArgumentException.class, () -> ByteUnitUtil.validateSizeString(input));
- } else {
- assertThrows(ParameterException.class, () -> ByteUnitUtil.validateSizeString(input));
- }
+ assertThrows(IllegalArgumentException.class, () -> ByteUnitUtil.validateSizeString(input));
}
@Test(dataProvider = "failingByteUnitUtilTestCases")
public void testFailedByteUnitToLongConverter(String input) {
ByteUnitToLongConverter converter = new ByteUnitToLongConverter("optionName");
- assertThrows(ParameterException.class, () -> converter.convert(input));
+ assertThrows(IllegalArgumentException.class, () -> converter.convert(input));
}
@Test(dataProvider = "failingByteUnitUtilTestCases")
public void testFailedByteUnitIntegerConverter(String input) {
- ByteUnitIntegerConverter converter = new ByteUnitIntegerConverter("optionName");
- assertThrows(ParameterException.class, () -> converter.convert(input));
+ ByteUnitToIntegerConverter converter = new ByteUnitToIntegerConverter();
+ assertThrows(TypeConversionException.class, () -> converter.convert(input));
}
}
diff --git a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/TimeConversionTest.java b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/TimeConversionTest.java
index f7adeee0423ae..cc50eed4d03e4 100644
--- a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/TimeConversionTest.java
+++ b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/converters/TimeConversionTest.java
@@ -18,13 +18,13 @@
*/
package org.apache.pulsar.cli.converters;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
import java.util.concurrent.TimeUnit;
-
+import org.apache.pulsar.cli.converters.picocli.TimeUnitToMillisConverter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import static org.testng.Assert.*;
-
public class TimeConversionTest {
@DataProvider
@@ -63,8 +63,8 @@ public void testSuccessfulTimeUnitToSecondsConverter(String input, long expected
}
@Test(dataProvider = "successfulRelativeTimeUtilTestCases")
- public void testSuccessfulTimeUnitToMillisConverter(String input, long expected) {
- TimeUnitToMillisConverter millisConverter = new TimeUnitToMillisConverter("optionName");
+ public void testSuccessfulTimeUnitToMillisConverter(String input, long expected) throws Exception {
+ TimeUnitToMillisConverter millisConverter = new TimeUnitToMillisConverter();
// We multiply the expected by 1000 to convert the seconds into milliseconds
assertEquals(millisConverter.convert(input), Long.valueOf(expected * 1000));
}
diff --git a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/validators/CliUtilValidatorsTest.java b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/validators/CliUtilValidatorsTest.java
index da1f6ec66bd9c..ba7de23373892 100644
--- a/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/validators/CliUtilValidatorsTest.java
+++ b/pulsar-cli-utils/src/test/java/org/apache/pulsar/cli/validators/CliUtilValidatorsTest.java
@@ -19,7 +19,6 @@
package org.apache.pulsar.cli.validators;
import static org.testng.Assert.assertThrows;
-import com.beust.jcommander.ParameterException;
import org.testng.annotations.Test;
public class CliUtilValidatorsTest {
@@ -27,23 +26,23 @@ public class CliUtilValidatorsTest {
@Test
public void testPositiveLongValueValidator() {
PositiveLongValueValidator validator = new PositiveLongValueValidator();
- assertThrows(ParameterException.class, () -> validator.validate("param", -1L));
- assertThrows(ParameterException.class, () -> validator.validate("param", 0L));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", -1L));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", 0L));
validator.validate("param", 1L);
}
@Test
public void testPositiveIntegerValueValidator() {
PositiveIntegerValueValidator validator = new PositiveIntegerValueValidator();
- assertThrows(ParameterException.class, () -> validator.validate("param", -1));
- assertThrows(ParameterException.class, () -> validator.validate("param", 0));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", -1));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", 0));
validator.validate("param", 1);
}
@Test
public void testNonNegativeValueValidator() {
NonNegativeValueValidator validator = new NonNegativeValueValidator();
- assertThrows(ParameterException.class, () -> validator.validate("param", -1L));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", -1L));
validator.validate("param", 0L);
validator.validate("param", 1L);
}
@@ -51,7 +50,7 @@ public void testNonNegativeValueValidator() {
@Test
public void testMinNegativeOneValidator() {
MinNegativeOneValidator validator = new MinNegativeOneValidator();
- assertThrows(ParameterException.class, () -> validator.validate("param", -2L));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", -2L));
validator.validate("param", -1L);
validator.validate("param", 0L);
}
@@ -59,7 +58,7 @@ public void testMinNegativeOneValidator() {
@Test
public void testIntegerMaxValueLongValidator() {
IntegerMaxValueLongValidator validator = new IntegerMaxValueLongValidator();
- assertThrows(ParameterException.class, () -> validator.validate("param", Integer.MAX_VALUE + 1L));
+ assertThrows(IllegalArgumentException.class, () -> validator.validate("param", Integer.MAX_VALUE + 1L));
validator.validate("param", (long) Integer.MAX_VALUE);
}
}
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/CmdFunctionsTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/CmdFunctionsTest.java
index 39ede3bb7aef1..4d906af9424f5 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/CmdFunctionsTest.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/CmdFunctionsTest.java
@@ -29,13 +29,9 @@
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.Arrays;
-import java.util.List;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.admin.cli.CmdFunctions.CreateFunction;
import org.apache.pulsar.admin.cli.CmdFunctions.DeleteFunction;
@@ -55,6 +51,7 @@
import org.apache.pulsar.functions.api.utils.IdentityFunction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import picocli.CommandLine;
/**
* Unit test of {@link CmdFunctions}.
@@ -542,11 +539,12 @@ public void testCreateWithoutOutputTopicWithSkipFlag() throws Exception {
@Test
- public void testCreateWithoutOutputTopic() {
-
- ConsoleOutputCapturer consoleOutputCapturer = new ConsoleOutputCapturer();
- consoleOutputCapturer.start();
-
+ public void testCreateWithoutOutputTopic() throws Exception {
+ @Cleanup
+ StringWriter stringWriter = new StringWriter();
+ @Cleanup
+ PrintWriter printWriter = new PrintWriter(stringWriter);
+ cmd.getCommander().setOut(printWriter);
cmd.run(new String[] {
"create",
"--inputs", INPUT_TOPIC_NAME,
@@ -557,9 +555,8 @@ public void testCreateWithoutOutputTopic() {
});
CreateFunction creater = cmd.getCreater();
- consoleOutputCapturer.stop();
assertNull(creater.getFunctionConfig().getOutput());
- assertTrue(consoleOutputCapturer.getStdout().contains("Created successfully"));
+ assertTrue(stringWriter.toString().contains("Created successfully"));
}
@Test
@@ -655,17 +652,19 @@ public void testStateGetter() throws Exception {
@Test
public void testStateGetterWithoutKey() throws Exception {
- ConsoleOutputCapturer consoleOutputCapturer = new ConsoleOutputCapturer();
- consoleOutputCapturer.start();
- cmd.run(new String[] {
+ CommandLine commander = cmd.getCommander();
+ @Cleanup
+ StringWriter stringWriter = new StringWriter();
+ @Cleanup
+ PrintWriter printWriter = new PrintWriter(stringWriter);
+ commander.setErr(printWriter);
+ cmd.run(new String[]{
"querystate",
"--tenant", TENANT,
"--namespace", NAMESPACE,
"--name", FN_NAME,
});
- consoleOutputCapturer.stop();
- String output = consoleOutputCapturer.getStderr();
- assertTrue(output.replace("\n", "").contains("State key needs to be specified"));
+ assertTrue(stringWriter.toString().startsWith(("State key needs to be specified")));
StateGetter stateGetter = cmd.getStateGetter();
assertEquals(TENANT, stateGetter.getTenant());
assertEquals(NAMESPACE, stateGetter.getNamespace());
@@ -896,79 +895,4 @@ public void testDownloadTransformFunction() throws Exception {
verify(functions, times(1))
.downloadFunction(JAR_NAME, TENANT, NAMESPACE, FN_NAME, true);
}
-
-
- public static class ConsoleOutputCapturer {
- private ByteArrayOutputStream stdout;
- private ByteArrayOutputStream stderr;
- private PrintStream previous;
- private boolean capturing;
-
- public void start() {
- if (capturing) {
- return;
- }
-
- capturing = true;
- previous = System.out;
- stdout = new ByteArrayOutputStream();
- stderr = new ByteArrayOutputStream();
-
- OutputStream outputStreamCombinerstdout =
- new OutputStreamCombiner(Arrays.asList(previous, stdout));
- PrintStream stdoutStream = new PrintStream(outputStreamCombinerstdout);
-
- OutputStream outputStreamCombinerStderr =
- new OutputStreamCombiner(Arrays.asList(previous, stderr));
- PrintStream stderrStream = new PrintStream(outputStreamCombinerStderr);
-
- System.setOut(stdoutStream);
- System.setErr(stderrStream);
- }
-
- public void stop() {
- if (!capturing) {
- return;
- }
-
- System.setOut(previous);
-
- previous = null;
- capturing = false;
- }
-
- public String getStdout() {
- return stdout.toString();
- }
-
- public String getStderr() {
- return stderr.toString();
- }
-
- private static class OutputStreamCombiner extends OutputStream {
- private List outputStreams;
-
- public OutputStreamCombiner(List outputStreams) {
- this.outputStreams = outputStreams;
- }
-
- public void write(int b) throws IOException {
- for (OutputStream os : outputStreams) {
- os.write(b);
- }
- }
-
- public void flush() throws IOException {
- for (OutputStream os : outputStreams) {
- os.flush();
- }
- }
-
- public void close() throws IOException {
- for (OutputStream os : outputStreams) {
- os.close();
- }
- }
- }
- }
}
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/DeprecatedCommanderTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/DeprecatedCommanderTest.java
deleted file mode 100644
index 3112344bedcda..0000000000000
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/DeprecatedCommanderTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.pulsar.admin.cli;
-
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.Assert.assertTrue;
-import com.beust.jcommander.DefaultUsageFormatter;
-import org.apache.pulsar.client.admin.PulsarAdmin;
-import org.apache.pulsar.client.admin.Schemas;
-import org.apache.pulsar.client.admin.Topics;
-import org.mockito.Mockito;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class DeprecatedCommanderTest {
- PulsarAdmin admin;
- Topics mockTopics;
- Schemas mockSchemas;
- CmdTopics cmdTopics;
-
- @BeforeMethod
- public void setup() {
- admin = Mockito.mock(PulsarAdmin.class);
- mockTopics = mock(Topics.class);
- when(admin.topics()).thenReturn(mockTopics);
- mockSchemas = mock(Schemas.class);
- when(admin.schemas()).thenReturn(mockSchemas);
- cmdTopics = new CmdTopics(() -> admin);
- }
-
- @Test
- public void testDeprecatedCommanderWorks() throws Exception {
-
- DefaultUsageFormatter defaultUsageFormatter = new DefaultUsageFormatter(cmdTopics.jcommander);
- StringBuilder builder = new StringBuilder();
- defaultUsageFormatter.usage(builder);
- String defaultOutput = builder.toString();
-
- StringBuilder builder2 = new StringBuilder();
- cmdTopics.jcommander.getUsageFormatter().usage(builder2);
- String outputWithFiltered = builder2.toString();
-
- assertNotEquals(outputWithFiltered, defaultOutput);
- assertFalse(outputWithFiltered.contains("enable-deduplication"));
- assertTrue(defaultOutput.contains("enable-deduplication"));
- assertFalse(outputWithFiltered.contains("get-max-unacked-messages-on-consumer"));
- assertTrue(defaultOutput.contains("get-max-unacked-messages-on-consumer"));
- assertFalse(outputWithFiltered.contains("get-deduplication"));
- assertTrue(defaultOutput.contains("get-deduplication"));
-
- // annotation was changed to hidden, reset it.
- cmdTopics = new CmdTopics(() -> admin);
- CmdUsageFormatter formatter = (CmdUsageFormatter)cmdTopics.jcommander.getUsageFormatter();
- formatter.clearDeprecatedCommand();
- StringBuilder builder3 = new StringBuilder();
- cmdTopics.jcommander.getUsageFormatter().usage(builder3);
- String outputAfterClean = builder3.toString();
-
- assertEquals(outputAfterClean, defaultOutput);
-
- }
-
-}
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
index 2d567a7528dcc..fd1bdf4799848 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
@@ -18,6 +18,8 @@
*/
package org.apache.pulsar.admin.cli;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.longThat;
@@ -33,14 +35,13 @@
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static org.testng.AssertJUnit.assertNotNull;
-
-import com.beust.jcommander.JCommander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
+import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
@@ -122,6 +123,7 @@
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
+import picocli.CommandLine;
@Slf4j
public class PulsarAdminToolTest {
@@ -167,6 +169,8 @@ public void brokers() throws Exception {
brokers.run(split("version"));
verify(mockBrokers).getVersion();
+ doReturn(CompletableFuture.completedFuture(null)).when(mockBrokers)
+ .shutDownBrokerGracefully(anyInt(), anyBoolean());
brokers.run(split("shutdown -m 10 -f"));
verify(mockBrokers).shutDownBrokerGracefully(10,true);
}
@@ -179,15 +183,19 @@ public void brokerStats() throws Exception {
CmdBrokerStats brokerStats = new CmdBrokerStats(() -> admin);
+ doReturn("null").when(mockBrokerStats).getTopics();
brokerStats.run(split("topics"));
verify(mockBrokerStats).getTopics();
+ doReturn(null).when(mockBrokerStats).getLoadReport();
brokerStats.run(split("load-report"));
verify(mockBrokerStats).getLoadReport();
+ doReturn("null").when(mockBrokerStats).getMBeans();
brokerStats.run(split("mbeans"));
verify(mockBrokerStats).getMBeans();
+ doReturn("null").when(mockBrokerStats).getMetrics();
brokerStats.run(split("monitoring-metrics"));
verify(mockBrokerStats).getMetrics();
}
@@ -1569,7 +1577,7 @@ public void topics() throws Exception {
verify(mockLookup).lookupPartitionedTopic("persistent://myprop/clust/ns1/ds1");
cmdTopics.run(split("partitioned-lookup persistent://myprop/clust/ns1/ds1 --sort-by-broker"));
- verify(mockLookup).lookupPartitionedTopic("persistent://myprop/clust/ns1/ds1");
+ verify(mockLookup, times(2)).lookupPartitionedTopic("persistent://myprop/clust/ns1/ds1");
cmdTopics.run(split("bundle-range persistent://myprop/clust/ns1/ds1"));
verify(mockLookup).getBundleRange("persistent://myprop/clust/ns1/ds1");
@@ -2496,21 +2504,20 @@ public void customCommands() throws Exception {
assertTrue(logs.contains("customgroup"));
assertTrue(logs.contains("Custom group 1 description"));
+ // missing subcommand
logs = runCustomCommand(new String[]{"customgroup"});
- assertTrue(logs.contains("command1"));
+ assertTrue(logs.contains("Missing required subcommand"));
assertTrue(logs.contains("Command 1 description"));
- assertTrue(logs.contains("command2"));
assertTrue(logs.contains("Command 2 description"));
+ // missing required parameter
logs = runCustomCommand(new String[]{"customgroup", "command1"});
+ assertTrue(logs.contains("Missing required options and parameters"));
assertTrue(logs.contains("Command 1 description"));
- assertTrue(logs.contains("Usage: command1 [options] Topic"));
- // missing required parameter
logs = runCustomCommand(new String[]{"customgroup", "command1", "mytopic"});
assertTrue(logs.contains("Command 1 description"));
- assertTrue(logs.contains("Usage: command1 [options] Topic"));
- assertTrue(logs.contains("The following option is required"));
+ assertTrue(logs.contains("Missing required option"));
// run a comand that uses PulsarAdmin API
logs = runCustomCommand(new String[]{"customgroup", "command1", "--type", "stats", "mytopic"});
@@ -2578,39 +2585,26 @@ public void customCommandsFactoryImmutable() throws Exception {
}
@Test
- public void testHelpFlag() {
- PulsarAdmin admin = Mockito.mock(PulsarAdmin.class);
+ public void testHelpFlag() throws Exception {
+ Properties properties = new Properties();
+ properties.put("webServiceUrl", "http://localhost:8080");
+
+ PulsarAdminTool pulsarAdminTool = new PulsarAdminTool(properties);
{
- CmdSchemas cmdSchemas = new CmdSchemas(() -> admin);
- cmdSchemas.run(split("-h"));
- assertTrue(cmdSchemas.isHelp());
+ assertTrue(pulsarAdminTool.run(split("schemas -h")));
}
{
- CmdSchemas cmdSchemas = new CmdSchemas(() -> admin);
- cmdSchemas.run(split("--help"));
- assertTrue(cmdSchemas.isHelp());
+ assertTrue(pulsarAdminTool.run(split("schemas --help")));
}
{
- CmdSchemas cmdSchemas = new CmdSchemas(() -> admin);
- cmdSchemas.run(split("delete --help"));
- assertFalse(cmdSchemas.isHelp());
- JCommander commander = cmdSchemas.getJcommander();
- JCommander subCommander = commander.getCommands().get("delete");
- CliCommand subcommand = (CliCommand) subCommander.getObjects().get(0);
- assertTrue(subcommand.isHelp());
+ assertTrue(pulsarAdminTool.run(split("schemas delete -h")));
}
{
- CmdSchemas cmdSchemas = new CmdSchemas(() -> admin);
- cmdSchemas.run(split("delete -h"));
- assertFalse(cmdSchemas.isHelp());
- JCommander commander = cmdSchemas.getJcommander();
- JCommander subCommander = commander.getCommands().get("delete");
- CliCommand subcommand = (CliCommand) subCommander.getObjects().get(0);
- assertTrue(subcommand.isHelp());
+ assertTrue(pulsarAdminTool.run(split("schemas delete --help")));
}
}
@@ -2633,11 +2627,9 @@ private static String runCustomCommand(String[] args) throws Exception {
properties.put("cliExtensionsDirectory", narFile.getParentFile().getAbsolutePath());
properties.put("customCommandFactories", "dummy");
PulsarAdminTool tool = new PulsarAdminTool(properties);
- tool.setPulsarAdminSupplier(new PulsarAdminSupplier(builder, tool.getRootParams()));
-
- // see the custom command help in the main help
+ tool.getPulsarAdminSupplier().setAdminBuilder(builder);
StringBuilder logs = new StringBuilder();
- try (CaptureStdOut capture = new CaptureStdOut(logs)){
+ try (CaptureStdOut capture = new CaptureStdOut(tool.commander, logs)) {
tool.run(args);
}
log.info("Captured out: {}", logs);
@@ -2647,13 +2639,18 @@ private static String runCustomCommand(String[] args) throws Exception {
private static class CaptureStdOut implements AutoCloseable {
final PrintStream currentOut = System.out;
final PrintStream currentErr = System.err;
- final ByteArrayOutputStream logs = new ByteArrayOutputStream();
- final PrintStream capturedOut = new PrintStream(logs, true);
+ final ByteArrayOutputStream logs;
+ final PrintStream capturedOut;
final StringBuilder receiver;
- public CaptureStdOut(StringBuilder receiver) {
+ public CaptureStdOut(CommandLine commandLine, StringBuilder receiver) {
+ logs = new ByteArrayOutputStream();
+ capturedOut = new PrintStream(logs, true);
this.receiver = receiver;
- System.setOut(capturedOut);
- System.setErr(capturedOut);
+ PrintWriter printWriter = new PrintWriter(logs);
+ commandLine.setErr(printWriter);
+ commandLine.setOut(printWriter);
+ System.setOut(new PrintStream(logs));
+ System.setErr(new PrintStream(logs));
}
public void close() {
capturedOut.flush();
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/DocumentTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/DocumentTest.java
index c565fadd2fc9a..84d423c6072b6 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/DocumentTest.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/DocumentTest.java
@@ -20,16 +20,13 @@
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
-
-import com.beust.jcommander.JCommander;
+import java.util.Map;
+import java.util.Properties;
import org.apache.pulsar.broker.service.BrokerTestBase;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-
-import java.util.Map;
-import java.util.Properties;
-
+import picocli.CommandLine;
public class DocumentTest extends BrokerTestBase {
@@ -59,11 +56,12 @@ public void testSpecifyModuleName() {
@Test
public void testGenerator() {
PulsarClientTool pulsarClientTool = new PulsarClientTool(new Properties());
- JCommander commander = pulsarClientTool.jcommander;
+ CommandLine commander = pulsarClientTool.getCommander();
CmdGenerateDocumentation document = new CmdGenerateDocumentation();
- for (Map.Entry cmd : commander.getCommands().entrySet()) {
- String res = document.generateDocument(cmd.getKey(), commander);
- assertTrue(res.contains("pulsar-client " + cmd.getKey() + " [options]"));
- }
+ Map subcommands = commander.getSubcommands();
+ subcommands.forEach((subcommandName, subCommander) -> {
+ String res = document.generateDocument(subcommandName, subCommander);
+ assertTrue(res.contains("pulsar-client " + subcommandName + " [options]"));
+ });
}
}
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java
index e296ab0e0357a..896bee0e030af 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java
@@ -53,11 +53,6 @@ public PulsarClientToolForceBatchNum(Properties properties, String topic, int ba
super(properties);
this.topic = topic;
this.batchNum = batchNum;
- }
-
- @Override
- protected void initJCommander() {
- super.initJCommander();
produceCommand = new CmdProduce() {
@Override
public void updateConfig(ClientBuilder newBuilder, Authentication authentication, String serviceURL) {
@@ -68,7 +63,7 @@ public void updateConfig(ClientBuilder newBuilder, Authentication authentication
}
}
};
- jcommander.addCommand("produce", produceCommand);
+ replaceProducerCommand(produceCommand);
}
private ClientBuilder mockClientBuilder(ClientBuilder newBuilder) throws Exception {
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolTest.java
index 84b8060b3115d..9edee30d8fee8 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolTest.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolTest.java
@@ -357,7 +357,7 @@ public void testArgs() throws Exception {
"--memory-limit", memoryLimitArg,
"produce", "-m", message,
"-n", Integer.toString(numberOfMessages), topicName};
- pulsarClientTool.jcommander.parse(args);
+ pulsarClientTool.getCommander().parseArgs(args);
assertEquals(pulsarClientTool.rootParams.getTlsTrustCertsFilePath(), CA_CERT_FILE_PATH);
assertEquals(pulsarClientTool.rootParams.getAuthParams(), authParams);
assertEquals(pulsarClientTool.rootParams.getAuthPluginClassName(), authPlugin);
@@ -386,8 +386,7 @@ public void testMemoryLimitArgShortName() throws Exception {
"-ml", memoryLimitArg,
"produce", "-m", message,
"-n", Integer.toString(numberOfMessages), topicName};
-
- pulsarClientTool.jcommander.parse(args);
+ pulsarClientTool.getCommander().parseArgs(args);
assertEquals(pulsarClientTool.rootParams.getMemoryLimit(), 10 * 1024 * 1024);
}
@@ -405,7 +404,7 @@ public void testParsingProxyServiceUrlAndProxyProtocolFromProperties() throws Ex
String[] args = {"--url", url,
"produce", "-m", message,
"-n", Integer.toString(numberOfMessages), topicName};
- pulsarClientTool.jcommander.parse(args);
+ pulsarClientTool.getCommander().parseArgs(args);
assertEquals(pulsarClientTool.rootParams.getServiceURL(), url);
assertEquals(pulsarClientTool.rootParams.getProxyServiceURL(), "pulsar+ssl://my-proxy-pulsar:4443");
assertEquals(pulsarClientTool.rootParams.getProxyProtocol(), ProxyProtocol.SNI);
diff --git a/pulsar-client-tools/pom.xml b/pulsar-client-tools/pom.xml
index 75bedca2b3f67..ba3d2b3a4a254 100644
--- a/pulsar-client-tools/pom.xml
+++ b/pulsar-client-tools/pom.xml
@@ -34,8 +34,13 @@
- com.beust
- jcommander
+ info.picocli
+ picocli
+ compile
+
+
+ info.picocli
+ picocli-shell-jline3
compile
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CliCommand.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CliCommand.java
index e984f114c27b1..8a8019cbe8ccc 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CliCommand.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CliCommand.java
@@ -18,8 +18,6 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.util.Arrays;
@@ -27,6 +25,7 @@
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import java.util.concurrent.Callable;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.impl.MessageIdImpl;
@@ -35,44 +34,42 @@
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AuthAction;
import org.apache.pulsar.common.util.ObjectMapperFactory;
-
-public abstract class CliCommand {
-
- @Parameter(names = { "--help", "-h" }, help = true, hidden = true)
- private boolean help = false;
-
- public boolean isHelp() {
- return help;
- }
-
- static String[] validatePropertyCluster(List params) {
- return splitParameter(params, 2);
+import picocli.CommandLine;
+import picocli.CommandLine.Model.CommandSpec;
+import picocli.CommandLine.Spec;
+
+public abstract class CliCommand implements Callable {
+ @Spec
+ private CommandSpec commandSpec;
+
+ static String[] validatePropertyCluster(String params) {
+ String[] parts = params.split("/");
+ if (parts.length != 2) {
+ throw new IllegalArgumentException("Parameter format is incorrect");
+ }
+ return parts;
}
- static String validateNamespace(List params) {
- String namespace = checkArgument(params);
+ static String validateNamespace(String namespace) {
return NamespaceName.get(namespace).toString();
}
- static String validateTopicName(List params) {
- String topic = checkArgument(params);
+ static String validateTopicName(String topic) {
return TopicName.get(topic).toString();
}
- static String validatePersistentTopic(List params) {
- String topic = checkArgument(params);
+ static String validatePersistentTopic(String topic) {
TopicName topicName = TopicName.get(topic);
if (topicName.getDomain() != TopicDomain.persistent) {
- throw new ParameterException("Need to provide a persistent topic name");
+ throw new IllegalArgumentException("Need to provide a persistent topic name");
}
return topicName.toString();
}
- static String validateNonPersistentTopic(List params) {
- String topic = checkArgument(params);
+ static String validateNonPersistentTopic(String topic) {
TopicName topicName = TopicName.get(topic);
if (topicName.getDomain() != TopicDomain.non_persistent) {
- throw new ParameterException("Need to provide a non-persistent topic name");
+ throw new IllegalArgumentException("Need to provide a non-persistent topic name");
}
return topicName.toString();
}
@@ -92,54 +89,7 @@ static MessageId validateMessageIdString(String resetMessageIdStr, int partition
}
}
- static String checkArgument(List arguments) {
- if (arguments.size() != 1) {
- throw new ParameterException("Need to provide just 1 parameter");
- }
-
- return arguments.get(0);
- }
-
- private static String[] splitParameter(List params, int n) {
- if (params.size() != 1) {
- throw new ParameterException("Need to provide just 1 parameter");
- }
-
- String[] parts = params.get(0).split("/");
- if (parts.length != n) {
- throw new ParameterException("Parameter format is incorrect");
- }
-
- return parts;
- }
-
- static String getOneArgument(List params) {
- if (params.size() != 1) {
- throw new ParameterException("Need to provide just 1 parameter");
- }
-
- return params.get(0);
- }
-
- /**
- *
- * @param params
- * List of positional arguments
- * @param pos
- * Positional arguments start with index as 1
- * @param maxArguments
- * Validate against max arguments
- * @return
- */
- static String getOneArgument(List params, int pos, int maxArguments) {
- if (params.size() != maxArguments) {
- throw new ParameterException(String.format("Need to provide %s parameters", maxArguments));
- }
-
- return params.get(pos);
- }
-
- static Set getAuthActions(List actions) {
+ Set getAuthActions(List actions) {
Set res = new TreeSet<>();
AuthAction authAction;
for (String action : actions) {
@@ -170,7 +120,7 @@ void print(Map items) {
void print(T item) {
try {
if (item instanceof String) {
- System.out.println(item);
+ commandSpec.commandLine().getOut().println(item);
} else {
prettyPrint(item);
}
@@ -181,7 +131,7 @@ void print(T item) {
void prettyPrint(T item) {
try {
- System.out.println(WRITER.writeValueAsString(item));
+ commandSpec.commandLine().getOut().println(WRITER.writeValueAsString(item));
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -190,5 +140,22 @@ void prettyPrint(T item) {
private static final ObjectMapper MAPPER = ObjectMapperFactory.create();
private static final ObjectWriter WRITER = MAPPER.writerWithDefaultPrettyPrinter();
+ // Picocli entrypoint.
+ @Override
+ public Integer call() throws Exception {
+ run();
+ return 0;
+ }
+
abstract void run() throws Exception;
+
+ protected class ParameterException extends CommandLine.ParameterException {
+ public ParameterException(String msg) {
+ super(commandSpec.commandLine(), msg);
+ }
+
+ public ParameterException(String msg, Throwable e) {
+ super(commandSpec.commandLine(), msg, e);
+ }
+ }
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java
index 381bc8abcaa3f..07e8a8b5df63b 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java
@@ -19,11 +19,6 @@
package org.apache.pulsar.admin.cli;
import static org.apache.pulsar.client.admin.internal.BaseResource.getApiException;
-import com.beust.jcommander.DefaultUsageFormatter;
-import com.beust.jcommander.IUsageFormatter;
-import com.beust.jcommander.JCommander;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -34,14 +29,12 @@
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
-import org.apache.pulsar.client.admin.PulsarAdminException.ConnectException;
import org.apache.pulsar.client.admin.internal.PulsarAdminImpl;
+import picocli.CommandLine;
public abstract class CmdBase {
- protected final JCommander jcommander;
+ private final CommandLine commander;
private final Supplier adminSupplier;
- private PulsarAdmin admin;
- private IUsageFormatter usageFormatter;
/**
* Default read timeout in milliseconds.
@@ -49,91 +42,18 @@ public abstract class CmdBase {
*/
private static final long DEFAULT_READ_TIMEOUT_MILLIS = 60000;
- @Parameter(names = { "--help", "-h" }, help = true, hidden = true)
- private boolean help = false;
-
- public boolean isHelp() {
- return help;
- }
-
public CmdBase(String cmdName, Supplier adminSupplier) {
this.adminSupplier = adminSupplier;
- jcommander = new JCommander(this);
- usageFormatter = new CmdUsageFormatter(jcommander);
- jcommander.setProgramName("pulsar-admin " + cmdName);
- jcommander.setUsageFormatter(usageFormatter);
- }
-
- protected IUsageFormatter getUsageFormatter() {
- if (usageFormatter == null) {
- usageFormatter = new DefaultUsageFormatter(jcommander);
- }
- return usageFormatter;
- }
-
- private void tryShowCommandUsage() {
- try {
- String chosenCommand = jcommander.getParsedCommand();
- getUsageFormatter().usage(chosenCommand);
- } catch (Exception e) {
- // it is caused by an invalid command, the invalid command can not be parsed
- System.err.println("Invalid command, please use `pulsar-admin --help` to check out how to use");
- }
+ commander = new CommandLine(this);
+ commander.setCommandName(cmdName);
}
public boolean run(String[] args) {
- try {
- jcommander.parse(args);
- } catch (Exception e) {
- System.err.println(e.getMessage());
- System.err.println();
- tryShowCommandUsage();
- return false;
- }
-
- String cmd = jcommander.getParsedCommand();
- if (cmd == null) {
- jcommander.usage();
- return help;
- }
-
- JCommander obj = jcommander.getCommands().get(cmd);
- CliCommand cmdObj = (CliCommand) obj.getObjects().get(0);
-
- if (cmdObj.isHelp()) {
- obj.setProgramName(jcommander.getProgramName() + " " + cmd);
- obj.usage();
- return true;
- }
-
- try {
- cmdObj.run();
- return true;
- } catch (ParameterException e) {
- System.err.println(e.getMessage());
- System.err.println();
- return false;
- } catch (ConnectException e) {
- System.err.println(e.getMessage());
- System.err.println();
- System.err.println("Error connecting to: " + getAdmin().getServiceUrl());
- return false;
- } catch (PulsarAdminException e) {
- System.err.println(e.getHttpError());
- System.err.println();
- System.err.println("Reason: " + e.getMessage());
- return false;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
+ return commander.execute(args) == 0;
}
protected PulsarAdmin getAdmin() {
- if (admin == null) {
- admin = adminSupplier.get();
- }
- return admin;
+ return adminSupplier.get();
}
protected long getReadTimeoutMs() {
@@ -159,7 +79,7 @@ protected T sync(Supplier> executor) throws PulsarAdmin
}
}
- static Map parseListKeyValueMap(List metadata) {
+ Map parseListKeyValueMap(List metadata) {
Map map = null;
if (metadata != null && !metadata.isEmpty()) {
map = new HashMap<>();
@@ -175,7 +95,26 @@ static Map parseListKeyValueMap(List metadata) {
return map;
}
- public JCommander getJcommander() {
- return jcommander;
+ // Used to register the subcomand.
+ protected CommandLine getCommander() {
+ return commander;
+ }
+
+ protected void addCommand(String name, Object cmd) {
+ commander.addSubcommand(name, cmd);
+ }
+
+ protected void addCommand(String name, Object cmd, String... aliases) {
+ commander.addSubcommand(name, cmd, aliases);
+ }
+
+ protected class ParameterException extends CommandLine.ParameterException {
+ public ParameterException(String msg) {
+ super(commander, msg);
+ }
+
+ public ParameterException(String msg, Throwable e) {
+ super(commander, msg, e);
+ }
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBookies.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBookies.java
index 27502a305ac4d..09389d474ff5e 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBookies.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBookies.java
@@ -18,19 +18,18 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
-import com.beust.jcommander.Parameters;
import com.google.common.base.Strings;
import java.util.function.Supplier;
import lombok.NonNull;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.common.policies.data.BookieInfo;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
-@Parameters(commandDescription = "Operations about bookies rack placement")
+@Command(description = "Operations about bookies rack placement")
public class CmdBookies extends CmdBase {
- @Parameters(commandDescription = "Gets the rack placement information for all the bookies in the cluster")
+ @Command(description = "Gets the rack placement information for all the bookies in the cluster")
private class GetAll extends CliCommand {
@Override
@@ -39,10 +38,10 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Gets the rack placement information for a specific bookie in the cluster")
+ @Command(description = "Gets the rack placement information for a specific bookie in the cluster")
private class GetBookie extends CliCommand {
- @Parameter(names = { "-b", "--bookie" },
+ @Option(names = {"-b", "--bookie"},
description = "Bookie address (format: `address:port`)", required = true)
private String bookieAddress;
@@ -52,7 +51,7 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "List bookies")
+ @Command(description = "List bookies")
private class ListBookies extends CliCommand {
@Override
@@ -61,10 +60,10 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Remove rack placement information for a specific bookie in the cluster")
+ @Command(description = "Remove rack placement information for a specific bookie in the cluster")
private class RemoveBookie extends CliCommand {
- @Parameter(names = { "-b", "--bookie" },
+ @Option(names = {"-b", "--bookie"},
description = "Bookie address (format: `address:port`)", required = true)
private String bookieAddress;
@@ -74,19 +73,19 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Updates the rack placement information for a specific bookie in the cluster "
+ @Command(description = "Updates the rack placement information for a specific bookie in the cluster "
+ "(note. bookie address format:`address:port`)")
private class UpdateBookie extends CliCommand {
private static final String PATH_SEPARATOR = "/";
- @Parameter(names = { "-g", "--group" }, description = "Bookie group name", required = false)
+ @Option(names = {"-g", "--group"}, description = "Bookie group name", required = false)
private String group = "default";
- @Parameter(names = { "-b", "--bookie" },
+ @Option(names = {"-b", "--bookie"},
description = "Bookie address (format: `address:port`)", required = true)
private String bookieAddress;
- @Parameter(names = { "-r", "--rack" }, description = "Bookie rack name. "
+ @Option(names = {"-r", "--rack"}, description = "Bookie rack name. "
+ "If you set a bookie rack name to slash (/) "
+ "or an empty string (\"\"): "
+ "when using Pulsar earlier than 2.7.5, 2.8.3, and 2.9.2, "
@@ -104,7 +103,7 @@ private class UpdateBookie extends CliCommand {
+ "but /region0rack0 and /region0/rack/0 are not allowed.", required = true)
private String bookieRack;
- @Parameter(names = {"-hn", "--hostname"}, description = "Bookie host name", required = false)
+ @Option(names = {"-hn", "--hostname"}, description = "Bookie host name", required = false)
private String bookieHost;
@Override
@@ -128,10 +127,10 @@ private void checkArgument(boolean expression, @NonNull Object errorMessage) {
public CmdBookies(Supplier admin) {
super("bookies", admin);
- jcommander.addCommand("racks-placement", new GetAll());
- jcommander.addCommand("list-bookies", new ListBookies());
- jcommander.addCommand("get-bookie-rack", new GetBookie());
- jcommander.addCommand("delete-bookie-rack", new RemoveBookie());
- jcommander.addCommand("set-bookie-rack", new UpdateBookie());
+ addCommand("racks-placement", new GetAll());
+ addCommand("list-bookies", new ListBookies());
+ addCommand("get-bookie-rack", new GetBookie());
+ addCommand("delete-bookie-rack", new RemoveBookie());
+ addCommand("set-bookie-rack", new UpdateBookie());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokerStats.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokerStats.java
index c83beec330f39..b9f7bdabd7c7f 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokerStats.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokerStats.java
@@ -18,8 +18,6 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.gson.Gson;
@@ -29,19 +27,21 @@
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
-import java.util.List;
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.common.stats.AllocatorStats;
import org.apache.pulsar.common.util.ObjectMapperFactory;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations to collect broker statistics")
+@Command(description = "Operations to collect broker statistics")
public class CmdBrokerStats extends CmdBase {
private static final String DEFAULT_INDENTATION = " ";
- @Parameters(commandDescription = "dump metrics for Monitoring")
+ @Command(description = "dump metrics for Monitoring")
private class CmdMonitoringMetrics extends CliCommand {
- @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
+ @Option(names = {"-i", "--indent"}, description = "Indent JSON output", required = false)
private boolean indent = false;
@Override
@@ -67,9 +67,9 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "dump mbean stats")
+ @Command(description = "dump mbean stats")
private class CmdDumpMBeans extends CliCommand {
- @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
+ @Option(names = {"-i", "--indent"}, description = "Indent JSON output", required = false)
private boolean indent = false;
@Override
@@ -88,7 +88,7 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "dump broker load-report")
+ @Command(description = "dump broker load-report")
private class CmdLoadReport extends CliCommand {
@Override
@@ -97,9 +97,9 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "dump topics stats")
+ @Command(description = "dump topics stats")
private class CmdTopics extends CliCommand {
- @Parameter(names = { "-i", "--indent" }, description = "Indent JSON output", required = false)
+ @Option(names = {"-i", "--indent"}, description = "Indent JSON output", required = false)
private boolean indent = false;
@Override
@@ -118,14 +118,14 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "dump allocator stats")
+ @Command(description = "dump allocator stats")
private class CmdAllocatorStats extends CliCommand {
- @Parameter(description = "allocator-name", required = true)
- private List params;
+ @Parameters(description = "allocator-name", arity = "1")
+ private String allocatorName;
@Override
void run() throws Exception {
- AllocatorStats stats = getAdmin().brokerStats().getAllocatorStats(params.get(0));
+ AllocatorStats stats = getAdmin().brokerStats().getAllocatorStats(allocatorName);
ObjectMapper mapper = ObjectMapperFactory.create();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
try (Writer out = new OutputStreamWriter(System.out, StandardCharsets.UTF_8)) {
@@ -138,11 +138,11 @@ void run() throws Exception {
public CmdBrokerStats(Supplier admin) {
super("broker-stats", admin);
- jcommander.addCommand("monitoring-metrics", new CmdMonitoringMetrics());
- jcommander.addCommand("mbeans", new CmdDumpMBeans());
- jcommander.addCommand("topics", new CmdTopics(), "destinations");
- jcommander.addCommand("allocator-stats", new CmdAllocatorStats());
- jcommander.addCommand("load-report", new CmdLoadReport());
+ addCommand("monitoring-metrics", new CmdMonitoringMetrics());
+ addCommand("mbeans", new CmdDumpMBeans());
+ addCommand("topics", new CmdTopics(), "destinations");
+ addCommand("allocator-stats", new CmdAllocatorStats());
+ addCommand("load-report", new CmdLoadReport());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokers.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokers.java
index f1571e96c65c9..b85a784c3c2b8 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokers.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBrokers.java
@@ -18,28 +18,28 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.common.naming.TopicVersion;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations about brokers")
+@Command(description = "Operations about brokers")
public class CmdBrokers extends CmdBase {
- @Parameters(commandDescription = "List active brokers of the cluster")
+ @Command(description = "List active brokers of the cluster")
private class List extends CliCommand {
- @Parameter(description = "cluster-name")
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
@Override
void run() throws Exception {
- String cluster = params == null ? null : getOneArgument(params);
print(getAdmin().brokers().getActiveBrokers(cluster));
}
}
- @Parameters(commandDescription = "Get the information of the leader broker")
+ @Command(description = "Get the information of the leader broker")
private class LeaderBroker extends CliCommand {
@Override
@@ -48,25 +48,25 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "List namespaces owned by the broker")
+ @Command(description = "List namespaces owned by the broker")
private class Namespaces extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
- @Parameter(names = {"-u", "--url"}, description = "broker-url", required = true)
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
+
+ @Option(names = {"-u", "--url"}, description = "broker-url", required = true)
private String brokerUrl;
@Override
void run() throws Exception {
- String cluster = getOneArgument(params);
print(getAdmin().brokers().getOwnedNamespaces(cluster, brokerUrl));
}
}
- @Parameters(commandDescription = "Update dynamic-serviceConfiguration of broker")
+ @Command(description = "Update dynamic-serviceConfiguration of broker")
private class UpdateConfigurationCmd extends CliCommand {
- @Parameter(names = {"-c", "--config"}, description = "service-configuration name", required = true)
+ @Option(names = {"-c", "--config"}, description = "service-configuration name", required = true)
private String configName;
- @Parameter(names = {"-v", "--value"}, description = "service-configuration value", required = true)
+ @Option(names = {"-v", "--value"}, description = "service-configuration value", required = true)
private String configValue;
@Override
@@ -75,9 +75,9 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Delete dynamic-serviceConfiguration of broker")
+ @Command(description = "Delete dynamic-serviceConfiguration of broker")
private class DeleteConfigurationCmd extends CliCommand {
- @Parameter(names = {"-c", "--config"}, description = "service-configuration name", required = true)
+ @Option(names = {"-c", "--config"}, description = "service-configuration name", required = true)
private String configName;
@Override
@@ -86,7 +86,7 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Get all overridden dynamic-configuration values")
+ @Command(description = "Get all overridden dynamic-configuration values")
private class GetAllConfigurationsCmd extends CliCommand {
@Override
@@ -95,7 +95,7 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Get list of updatable configuration name")
+ @Command(description = "Get list of updatable configuration name")
private class GetUpdatableConfigCmd extends CliCommand {
@Override
@@ -104,7 +104,7 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Get runtime configuration values")
+ @Command(description = "Get runtime configuration values")
private class GetRuntimeConfigCmd extends CliCommand {
@Override
@@ -113,7 +113,7 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Get internal configuration information")
+ @Command(description = "Get internal configuration information")
private class GetInternalConfigurationCmd extends CliCommand {
@Override
@@ -123,10 +123,10 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "Run a health check against the broker")
+ @Command(description = "Run a health check against the broker")
private class HealthcheckCmd extends CliCommand {
- @Parameter(names = {"-tv", "--topic-version"}, description = "topic version V1 is default")
+ @Option(names = {"-tv", "--topic-version"}, description = "topic version V1 is default")
private TopicVersion topicVersion;
@Override
@@ -137,15 +137,15 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "Shutdown broker gracefully.")
+ @Command(description = "Shutdown broker gracefully.")
private class ShutDownBrokerGracefully extends CliCommand {
- @Parameter(names = {"--max-concurrent-unload-per-sec", "-m"},
+ @Option(names = {"--max-concurrent-unload-per-sec", "-m"},
description = "Max concurrent unload per second, "
+ "if the value absent(value=0) means no concurrent limitation")
private int maxConcurrentUnloadPerSec;
- @Parameter(names = {"--forced-terminate-topic", "-f"}, description = "Force terminate all topics on Broker")
+ @Option(names = {"--forced-terminate-topic", "-f"}, description = "Force terminate all topics on Broker")
private boolean forcedTerminateTopic;
@Override
@@ -156,7 +156,7 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "Manually trigger backlogQuotaCheck")
+ @Command(description = "Manually trigger backlogQuotaCheck")
private class BacklogQuotaCheckCmd extends CliCommand {
@Override
@@ -167,7 +167,7 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "Get the version of the currently connected broker")
+ @Command(description = "Get the version of the currently connected broker")
private class PulsarVersion extends CliCommand {
@Override
@@ -178,18 +178,18 @@ void run() throws Exception {
public CmdBrokers(Supplier admin) {
super("brokers", admin);
- jcommander.addCommand("list", new List());
- jcommander.addCommand("leader-broker", new LeaderBroker());
- jcommander.addCommand("namespaces", new Namespaces());
- jcommander.addCommand("update-dynamic-config", new UpdateConfigurationCmd());
- jcommander.addCommand("delete-dynamic-config", new DeleteConfigurationCmd());
- jcommander.addCommand("list-dynamic-config", new GetUpdatableConfigCmd());
- jcommander.addCommand("get-all-dynamic-config", new GetAllConfigurationsCmd());
- jcommander.addCommand("get-internal-config", new GetInternalConfigurationCmd());
- jcommander.addCommand("get-runtime-config", new GetRuntimeConfigCmd());
- jcommander.addCommand("healthcheck", new HealthcheckCmd());
- jcommander.addCommand("backlog-quota-check", new BacklogQuotaCheckCmd());
- jcommander.addCommand("version", new PulsarVersion());
- jcommander.addCommand("shutdown", new ShutDownBrokerGracefully());
+ addCommand("list", new List());
+ addCommand("leader-broker", new LeaderBroker());
+ addCommand("namespaces", new Namespaces());
+ addCommand("update-dynamic-config", new UpdateConfigurationCmd());
+ addCommand("delete-dynamic-config", new DeleteConfigurationCmd());
+ addCommand("list-dynamic-config", new GetUpdatableConfigCmd());
+ addCommand("get-all-dynamic-config", new GetAllConfigurationsCmd());
+ addCommand("get-internal-config", new GetInternalConfigurationCmd());
+ addCommand("get-runtime-config", new GetRuntimeConfigCmd());
+ addCommand("healthcheck", new HealthcheckCmd());
+ addCommand("backlog-quota-check", new BacklogQuotaCheckCmd());
+ addCommand("version", new PulsarVersion());
+ addCommand("shutdown", new ShutDownBrokerGracefully());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdClusters.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdClusters.java
index 0ea56e4430951..14f9eeadbffb5 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdClusters.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdClusters.java
@@ -19,13 +19,11 @@
package org.apache.pulsar.admin.cli;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import com.google.common.collect.Sets;
+import java.io.IOException;
import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.Collectors;
-import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.admin.cli.utils.CmdUtils;
import org.apache.pulsar.client.admin.PulsarAdmin;
@@ -36,18 +34,21 @@
import org.apache.pulsar.common.policies.data.ClusterPolicies.ClusterUrl;
import org.apache.pulsar.common.policies.data.FailureDomain;
import org.apache.pulsar.common.policies.data.FailureDomainImpl;
+import picocli.CommandLine.ArgGroup;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations about clusters")
+@Command(description = "Operations about clusters")
public class CmdClusters extends CmdBase {
- @Parameters(commandDescription = "List the existing clusters")
+ @Command(description = "List the existing clusters")
private class List extends CliCommand {
+ @Option(names = {"-c", "--current"},
+ description = "Print the current cluster with (*)", required = false, defaultValue = "false")
+ private boolean current;
- @Parameter(names = { "-c", "--current" },
- description = "Print the current cluster with (*)", required = false)
- private boolean current = false;
-
- void run() throws PulsarAdminException {
+ void run() throws Exception {
java.util.List clusters = getAdmin().clusters().getClusters();
String clusterName = getAdmin().brokers().getRuntimeConfigurations().get("clusterName");
final java.util.List result = clusters.stream().map(c ->
@@ -57,29 +58,30 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the configuration data for the specified cluster")
+ @Command(description = "Get the configuration data for the specified cluster")
private class Get extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
+ @Override
+ void run() throws Exception {
print(getAdmin().clusters().getCluster(cluster));
}
}
- @Parameters(commandDescription = "Provisions a new cluster. This operation requires Pulsar super-user privileges")
- private class Create extends ClusterDetailsCommand {
+ @Command(description = "Provisions a new cluster. This operation requires Pulsar super-user privileges")
+ private class Create extends CliCommand {
+ @ArgGroup(exclusive = false)
+ ClusterDetails clusterDetails = new ClusterDetails();
@Override
- void runCmd() throws Exception {
- String cluster = getOneArgument(params);
- getAdmin().clusters().createCluster(cluster, clusterData);
+ void run() throws PulsarAdminException, IOException {
+ getAdmin().clusters().createCluster(clusterDetails.clusterName, clusterDetails.getClusterData());
}
}
- protected void validateClusterData(ClusterData clusterData) {
+ protected static void validateClusterData(ClusterData clusterData) {
if (clusterData.isBrokerClientTlsEnabled()) {
if (clusterData.isBrokerClientTlsEnabledWithKeyStore()) {
if (StringUtils.isAnyBlank(clusterData.getBrokerClientTlsTrustStoreType(),
@@ -93,29 +95,29 @@ protected void validateClusterData(ClusterData clusterData) {
}
}
- @Parameters(commandDescription = "Update the configuration for a cluster")
- private class Update extends ClusterDetailsCommand {
+ @Command(description = "Update the configuration for a cluster")
+ private class Update extends CliCommand {
+ @ArgGroup(exclusive = false)
+ ClusterDetails clusterDetails = new ClusterDetails();
@Override
- void runCmd() throws Exception {
- String cluster = getOneArgument(params);
- getAdmin().clusters().updateCluster(cluster, clusterData);
+ void run() throws PulsarAdminException, IOException {
+ getAdmin().clusters().updateCluster(clusterDetails.clusterName, clusterDetails.getClusterData());
}
}
- @Parameters(commandDescription = "Deletes an existing cluster")
+ @Command(description = "Deletes an existing cluster")
private class Delete extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", index = "0", arity = "1")
+ private String cluster;
- @Parameter(names = { "-a", "--all" },
- description = "Delete all data (tenants) of the cluster", required = false)
- private boolean deleteAll = false;
+ @Option(names = {"-a", "--all"},
+ description = "Delete all data (tenants) of the cluster", required = false, defaultValue = "false")
+ private boolean deleteAll;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
-
if (deleteAll) {
for (String tenant : getAdmin().tenants().getTenants()) {
for (String namespace : getAdmin().namespaces().getNamespaces(tenant)) {
@@ -137,88 +139,88 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Update peer cluster names")
+ @Command(description = "Update peer cluster names")
private class UpdatePeerClusters extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--peer-clusters", description = "Comma separated peer-cluster names "
+ @Option(names = "--peer-clusters", description = "Comma separated peer-cluster names "
+ "[Pass empty string \"\" to delete list]", required = true)
private String peerClusterNames;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
java.util.LinkedHashSet clusters = StringUtils.isBlank(peerClusterNames) ? null
: Sets.newLinkedHashSet(Arrays.asList(peerClusterNames.split(",")));
getAdmin().clusters().updatePeerClusterNames(cluster, clusters);
}
}
- @Parameters(commandDescription = "Get the cluster migration configuration data for the specified cluster")
+ @Command(description = "Get the cluster migration configuration data for the specified cluster")
private class GetClusterMigration extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
- print(getAdmin().clusters().getClusterMigration(cluster));
+ getAdmin().clusters().getClusterMigration(cluster);
}
}
- @Parameters(commandDescription = "Update cluster migration")
+ @Command(description = "Update cluster migration")
private class UpdateClusterMigration extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--migrated", description = "Is cluster migrated")
+ @Option(names = "--migrated", description = "Is cluster migrated")
private boolean migrated;
- @Parameter(names = "--service-url", description = "New migrated cluster service url")
+ @Option(names = "--service-url", description = "New migrated cluster service url")
private String serviceUrl;
- @Parameter(names = "--service-url-secure",
+ @Option(names = "--service-url-secure",
description = "New migrated cluster service url secure")
private String serviceUrlTls;
- @Parameter(names = "--broker-url", description = "New migrated cluster broker service url")
+ @Option(names = "--broker-url", description = "New migrated cluster broker service url")
private String brokerServiceUrl;
- @Parameter(names = "--broker-url-secure", description = "New migrated cluster broker service url secure")
+ @Option(names = "--broker-url-secure", description = "New migrated cluster broker service url secure")
private String brokerServiceUrlTls;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
ClusterUrl clusterUrl = new ClusterUrl(serviceUrl, serviceUrlTls, brokerServiceUrl, brokerServiceUrlTls);
getAdmin().clusters().updateClusterMigration(cluster, migrated, clusterUrl);
}
}
- @Parameters(commandDescription = "Get list of peer-clusters")
+ @Command(description = "Get list of peer-clusters")
private class GetPeerClusters extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
print(getAdmin().clusters().getPeerClusterNames(cluster));
}
}
- @Parameters(commandDescription = "Create a new failure-domain for a cluster. updates it if already created.")
+ @Command(description = "Create a new failure-domain for a cluster. updates it if already created.")
private class CreateFailureDomain extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--domain-name", description = "domain-name", required = true)
+ @Option(names = "--domain-name", description = "domain-name", required = true)
private String domainName;
- @Parameter(names = "--broker-list", description = "Comma separated broker list", required = false)
+ @Option(names = "--broker-list", description = "Comma separated broker list", required = false)
private String brokerList;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
FailureDomain domain = FailureDomainImpl.builder()
.brokers((isNotBlank(brokerList) ? Sets.newHashSet(brokerList.split(",")) : null))
.build();
@@ -226,19 +228,19 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Update failure-domain for a cluster. Creates a new one if not exist.")
+ @Command(description = "Update failure-domain for a cluster. Creates a new one if not exist.")
private class UpdateFailureDomain extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--domain-name", description = "domain-name", required = true)
+ @Option(names = "--domain-name", description = "domain-name", required = true)
private String domainName;
- @Parameter(names = "--broker-list", description = "Comma separated broker list", required = false)
+ @Option(names = "--broker-list", description = "Comma separated broker list", required = false)
private String brokerList;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
FailureDomain domain = FailureDomainImpl.builder()
.brokers((isNotBlank(brokerList) ? Sets.newHashSet(brokerList.split(",")) : null))
.build();
@@ -246,160 +248,131 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Deletes an existing failure-domain")
+ @Command(description = "Deletes an existing failure-domain")
private class DeleteFailureDomain extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--domain-name", description = "domain-name", required = true)
+ @Option(names = "--domain-name", description = "domain-name", required = true)
private String domainName;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
getAdmin().clusters().deleteFailureDomain(cluster, domainName);
}
}
- @Parameters(commandDescription = "List the existing failure-domains for a cluster")
+ @Command(description = "List the existing failure-domains for a cluster")
private class ListFailureDomains extends CliCommand {
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
-
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
print(getAdmin().clusters().getFailureDomains(cluster));
}
}
- @Parameters(commandDescription = "Get the configuration brokers of a failure-domain")
+ @Command(description = "Get the configuration brokers of a failure-domain")
private class GetFailureDomain extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private java.util.List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String cluster;
- @Parameter(names = "--domain-name", description = "domain-name", required = true)
+ @Option(names = "--domain-name", description = "domain-name", required = true)
private String domainName;
+ @Override
void run() throws PulsarAdminException {
- String cluster = getOneArgument(params);
print(getAdmin().clusters().getFailureDomain(cluster, domainName));
}
}
- /**
- * Base command.
- */
- @Getter
- abstract class BaseCommand extends CliCommand {
- @Override
- void run() throws Exception {
- try {
- processArguments();
- } catch (Exception e) {
- String chosenCommand = jcommander.getParsedCommand();
- getUsageFormatter().usage(chosenCommand);
- throw e;
- }
- runCmd();
- }
-
- void processArguments() throws Exception {
- }
+ private static class ClusterDetails {
+ @Parameters(description = "cluster-name", arity = "1")
+ protected String clusterName;
- abstract void runCmd() throws Exception;
- }
-
- abstract class ClusterDetailsCommand extends BaseCommand {
- @Parameter(description = "cluster-name", required = true)
- protected java.util.List params;
-
- @Parameter(names = "--url", description = "service-url", required = false)
+ @Option(names = "--url", description = "service-url", required = false)
protected String serviceUrl;
- @Parameter(names = "--url-secure", description = "service-url for secure connection", required = false)
+ @Option(names = "--url-secure", description = "service-url for secure connection", required = false)
protected String serviceUrlTls;
- @Parameter(names = "--broker-url", description = "broker-service-url", required = false)
+ @Option(names = "--broker-url", description = "broker-service-url", required = false)
protected String brokerServiceUrl;
- @Parameter(names = "--broker-url-secure",
+ @Option(names = "--broker-url-secure",
description = "broker-service-url for secure connection", required = false)
protected String brokerServiceUrlTls;
- @Parameter(names = "--proxy-url",
+ @Option(names = "--proxy-url",
description = "Proxy-service url when client would like to connect to broker via proxy.")
protected String proxyServiceUrl;
- @Parameter(names = "--auth-plugin", description = "authentication plugin", required = false)
+ @Option(names = "--auth-plugin", description = "authentication plugin", required = false)
protected String authenticationPlugin;
- @Parameter(names = "--auth-parameters", description = "authentication parameters", required = false)
+ @Option(names = "--auth-parameters", description = "authentication parameters", required = false)
protected String authenticationParameters;
- @Parameter(names = "--proxy-protocol",
+ @Option(names = "--proxy-protocol",
description = "protocol to decide type of proxy routing eg: SNI", required = false)
protected ProxyProtocol proxyProtocol;
- @Parameter(names = "--tls-enable", description = "Enable tls connection", required = false)
+ @Option(names = "--tls-enable", description = "Enable tls connection", required = false)
protected Boolean brokerClientTlsEnabled;
- @Parameter(names = "--tls-allow-insecure", description = "Allow insecure tls connection", required = false)
+ @Option(names = "--tls-allow-insecure", description = "Allow insecure tls connection", required = false)
protected Boolean tlsAllowInsecureConnection;
- @Parameter(names = "--tls-enable-keystore",
+ @Option(names = "--tls-enable-keystore",
description = "Whether use KeyStore type to authenticate", required = false)
protected Boolean brokerClientTlsEnabledWithKeyStore;
- @Parameter(names = "--tls-trust-store-type",
+ @Option(names = "--tls-trust-store-type",
description = "TLS TrustStore type configuration for internal client eg: JKS", required = false)
protected String brokerClientTlsTrustStoreType;
- @Parameter(names = "--tls-trust-store",
+ @Option(names = "--tls-trust-store",
description = "TLS TrustStore path for internal client", required = false)
protected String brokerClientTlsTrustStore;
- @Parameter(names = "--tls-trust-store-pwd",
+ @Option(names = "--tls-trust-store-pwd",
description = "TLS TrustStore password for internal client", required = false)
protected String brokerClientTlsTrustStorePassword;
- @Parameter(names = "--tls-key-store-type",
+ @Option(names = "--tls-key-store-type",
description = "TLS TrustStore type configuration for internal client eg: JKS", required = false)
protected String brokerClientTlsKeyStoreType;
- @Parameter(names = "--tls-key-store",
+ @Option(names = "--tls-key-store",
description = "TLS KeyStore path for internal client", required = false)
protected String brokerClientTlsKeyStore;
- @Parameter(names = "--tls-key-store-pwd",
+ @Option(names = "--tls-key-store-pwd",
description = "TLS KeyStore password for internal client", required = false)
protected String brokerClientTlsKeyStorePassword;
- @Parameter(names = "--tls-trust-certs-filepath",
+ @Option(names = "--tls-trust-certs-filepath",
description = "path for the trusted TLS certificate file", required = false)
protected String brokerClientTrustCertsFilePath;
- @Parameter(names = "--tls-key-filepath",
+ @Option(names = "--tls-key-filepath",
description = "path for the TLS private key file", required = false)
protected String brokerClientKeyFilePath;
- @Parameter(names = "--tls-certs-filepath",
+ @Option(names = "--tls-certs-filepath",
description = "path for the TLS certificate file", required = false)
protected String brokerClientCertificateFilePath;
- @Parameter(names = "--listener-name",
+ @Option(names = "--listener-name",
description = "listenerName when client would like to connect to cluster", required = false)
protected String listenerName;
- @Parameter(names = "--cluster-config-file", description = "The path to a YAML config file specifying the "
+ @Option(names = "--cluster-config-file", description = "The path to a YAML config file specifying the "
+ "cluster's configuration")
protected String clusterConfigFile;
- protected ClusterData clusterData;
-
- @Override
- void processArguments() throws Exception {
- super.processArguments();
-
+ protected ClusterData getClusterData() throws IOException {
ClusterData.Builder builder;
if (null != clusterConfigFile) {
builder = CmdUtils.loadConfig(clusterConfigFile, ClusterDataImpl.ClusterDataImplBuilder.class);
@@ -472,27 +445,29 @@ void processArguments() throws Exception {
builder.listenerName(listenerName);
}
- this.clusterData = builder.build();
+ ClusterData clusterData = builder.build();
validateClusterData(clusterData);
+
+ return clusterData;
}
}
public CmdClusters(Supplier admin) {
super("clusters", admin);
- jcommander.addCommand("get", new Get());
- jcommander.addCommand("create", new Create());
- jcommander.addCommand("update", new Update());
- jcommander.addCommand("delete", new Delete());
- jcommander.addCommand("list", new List());
- jcommander.addCommand("update-peer-clusters", new UpdatePeerClusters());
- jcommander.addCommand("get-cluster-migration", new GetClusterMigration());
- jcommander.addCommand("update-cluster-migration", new UpdateClusterMigration());
- jcommander.addCommand("get-peer-clusters", new GetPeerClusters());
- jcommander.addCommand("get-failure-domain", new GetFailureDomain());
- jcommander.addCommand("create-failure-domain", new CreateFailureDomain());
- jcommander.addCommand("update-failure-domain", new UpdateFailureDomain());
- jcommander.addCommand("delete-failure-domain", new DeleteFailureDomain());
- jcommander.addCommand("list-failure-domains", new ListFailureDomains());
+ addCommand("get", new Get());
+ addCommand("create", new Create());
+ addCommand("update", new Update());
+ addCommand("delete", new Delete());
+ addCommand("list", new List());
+ addCommand("update-peer-clusters", new UpdatePeerClusters());
+ addCommand("get-cluster-migration", new GetClusterMigration());
+ addCommand("update-cluster-migration", new UpdateClusterMigration());
+ addCommand("get-peer-clusters", new GetPeerClusters());
+ addCommand("get-failure-domain", new GetFailureDomain());
+ addCommand("create-failure-domain", new CreateFailureDomain());
+ addCommand("update-failure-domain", new UpdateFailureDomain());
+ addCommand("delete-failure-domain", new DeleteFailureDomain());
+ addCommand("list-failure-domains", new ListFailureDomains());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctionWorker.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctionWorker.java
index 8fa2cbad955ef..cfb7f142d2458 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctionWorker.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctionWorker.java
@@ -18,15 +18,15 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameters;
import java.util.function.Supplier;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.PulsarClientException;
+import picocli.CommandLine.Command;
@Slf4j
-@Parameters(commandDescription = "Operations to collect function-worker statistics")
+@Command(description = "Operations to collect function-worker statistics")
public class CmdFunctionWorker extends CmdBase {
/**
@@ -46,7 +46,7 @@ void processArguments() throws Exception {
abstract void runCmd() throws Exception;
}
- @Parameters(commandDescription = "Dump all functions stats running on this broker")
+ @Command(description = "Dump all functions stats running on this broker")
class FunctionsStats extends BaseCommand {
@Override
@@ -55,7 +55,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Dump metrics for Monitoring")
+ @Command(description = "Dump metrics for Monitoring")
class CmdMonitoringMetrics extends BaseCommand {
@Override
@@ -64,7 +64,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Get all workers belonging to this cluster")
+ @Command(description = "Get all workers belonging to this cluster")
class GetCluster extends BaseCommand {
@Override
@@ -73,7 +73,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Get the leader of the worker cluster")
+ @Command(description = "Get the leader of the worker cluster")
class GetClusterLeader extends BaseCommand {
@Override
@@ -82,7 +82,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Get the assignments of the functions across the worker cluster")
+ @Command(description = "Get the assignments of the functions across the worker cluster")
class GetFunctionAssignments extends BaseCommand {
@@ -92,7 +92,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Triggers a rebalance of functions to workers")
+ @Command(description = "Triggers a rebalance of functions to workers")
class Rebalance extends BaseCommand {
@Override
@@ -104,12 +104,12 @@ void runCmd() throws Exception {
public CmdFunctionWorker(Supplier admin) throws PulsarClientException {
super("functions-worker", admin);
- jcommander.addCommand("function-stats", new FunctionsStats());
- jcommander.addCommand("monitoring-metrics", new CmdMonitoringMetrics());
- jcommander.addCommand("get-cluster", new GetCluster());
- jcommander.addCommand("get-cluster-leader", new GetClusterLeader());
- jcommander.addCommand("get-function-assignments", new GetFunctionAssignments());
- jcommander.addCommand("rebalance", new Rebalance());
+ addCommand("function-stats", new FunctionsStats());
+ addCommand("monitoring-metrics", new CmdMonitoringMetrics());
+ addCommand("get-cluster", new GetCluster());
+ addCommand("get-cluster-leader", new GetClusterLeader());
+ addCommand("get-function-assignments", new GetFunctionAssignments());
+ addCommand("rebalance", new Rebalance());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctions.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctions.java
index c94041df0ffaf..15b8fca076104 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctions.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdFunctions.java
@@ -22,10 +22,6 @@
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.pulsar.common.naming.TopicName.DEFAULT_NAMESPACE;
import static org.apache.pulsar.common.naming.TopicName.PUBLIC_TENANT;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
-import com.beust.jcommander.Parameters;
-import com.beust.jcommander.converters.StringConverter;
import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -58,9 +54,11 @@
import org.apache.pulsar.common.functions.Utils;
import org.apache.pulsar.common.functions.WindowConfig;
import org.apache.pulsar.common.util.ObjectMapperFactory;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
@Slf4j
-@Parameters(commandDescription = "Interface for managing Pulsar Functions "
+@Command(description = "Interface for managing Pulsar Functions "
+ "(lightweight, Lambda-style compute processes that work with Pulsar)")
public class CmdFunctions extends CmdBase {
private final LocalRunner localRunner;
@@ -88,13 +86,7 @@ public class CmdFunctions extends CmdBase {
abstract class BaseCommand extends CliCommand {
@Override
void run() throws Exception {
- try {
- processArguments();
- } catch (Exception e) {
- String chosenCommand = jcommander.getParsedCommand();
- getUsageFormatter().usage(chosenCommand);
- throw e;
- }
+ processArguments();
runCmd();
}
@@ -108,21 +100,13 @@ void processArguments() throws Exception {}
*/
@Getter
abstract class NamespaceCommand extends BaseCommand {
- @Parameter(names = "--tenant", description = "The tenant of a Pulsar Function")
+ @Option(names = "--tenant", description = "The tenant of a Pulsar Function",
+ defaultValue = PUBLIC_TENANT)
protected String tenant;
- @Parameter(names = "--namespace", description = "The namespace of a Pulsar Function")
+ @Option(names = "--namespace", description = "The namespace of a Pulsar Function",
+ defaultValue = DEFAULT_NAMESPACE)
protected String namespace;
-
- @Override
- public void processArguments() {
- if (tenant == null) {
- tenant = PUBLIC_TENANT;
- }
- if (namespace == null) {
- namespace = DEFAULT_NAMESPACE;
- }
- }
}
/**
@@ -130,22 +114,22 @@ public void processArguments() {
*/
@Getter
abstract class FunctionCommand extends BaseCommand {
- @Parameter(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function")
+ @Option(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function")
protected String fqfn;
- @Parameter(names = "--tenant", description = "The tenant of a Pulsar Function")
+ @Option(names = "--tenant", description = "The tenant of a Pulsar Function",
+ defaultValue = PUBLIC_TENANT)
protected String tenant;
- @Parameter(names = "--namespace", description = "The namespace of a Pulsar Function")
+ @Option(names = "--namespace", description = "The namespace of a Pulsar Function",
+ defaultValue = DEFAULT_NAMESPACE)
protected String namespace;
- @Parameter(names = "--name", description = "The name of a Pulsar Function")
+ @Option(names = "--name", description = "The name of a Pulsar Function")
protected String functionName;
@Override
void processArguments() throws Exception {
- super.processArguments();
-
boolean usesSetters = (null != tenant || null != namespace || null != functionName);
boolean usesFqfn = (null != fqfn);
@@ -183,214 +167,214 @@ void processArguments() throws Exception {
*/
@Getter
abstract class FunctionDetailsCommand extends BaseCommand {
- @Parameter(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function"
+ @Option(names = "--fqfn", description = "The Fully Qualified Function Name (FQFN) for the function"
+ " #Java, Python")
protected String fqfn;
- @Parameter(names = "--tenant", description = "The tenant of a Pulsar Function #Java, Python, Go")
+ @Option(names = "--tenant", description = "The tenant of a Pulsar Function #Java, Python, Go",
+ defaultValue = PUBLIC_TENANT)
protected String tenant;
- @Parameter(names = "--namespace", description = "The namespace of a Pulsar Function #Java, Python, Go")
+ @Option(names = "--namespace", description = "The namespace of a Pulsar Function #Java, Python, Go",
+ defaultValue = DEFAULT_NAMESPACE)
protected String namespace;
- @Parameter(names = "--name", description = "The name of a Pulsar Function #Java, Python, Go")
+ @Option(names = "--name", description = "The name of a Pulsar Function #Java, Python, Go")
protected String functionName;
// for backwards compatibility purposes
- @Parameter(names = "--className", description = "The class name of a Pulsar Function", hidden = true)
+ @Option(names = "--className", description = "The class name of a Pulsar Function", hidden = true)
protected String deprecatedClassName;
- @Parameter(names = "--classname", description = "The class name of a Pulsar Function #Java, Python")
+ @Option(names = "--classname", description = "The class name of a Pulsar Function #Java, Python")
protected String className;
- @Parameter(names = { "-t", "--function-type" }, description = "The built-in Pulsar Function type")
+ @Option(names = { "-t", "--function-type" }, description = "The built-in Pulsar Function type")
protected String functionType;
- @Parameter(names = "--cleanup-subscription", description = "Whether delete the subscription "
+ @Option(names = "--cleanup-subscription", description = "Whether delete the subscription "
+ "when function is deleted")
protected Boolean cleanupSubscription;
- @Parameter(names = "--jar", description = "Path to the JAR file for the function "
+ @Option(names = "--jar", description = "Path to the JAR file for the function "
+ "(if the function is written in Java). It also supports URL path [http/https/file "
+ "(file protocol assumes that file already exists on worker host)/function "
- + "(package URL from packages management service)] from which worker can download the package. #Java",
- listConverter = StringConverter.class)
+ + "(package URL from packages management service)] from which worker can download the package. #Java")
protected String jarFile;
- @Parameter(names = "--py", description = "Path to the main Python file/Python Wheel file for the function "
+ @Option(names = "--py", description = "Path to the main Python file/Python Wheel file for the function "
+ "(if the function is written in Python). It also supports URL path [http/https/file "
+ "(file protocol assumes that file already exists on worker host)/function "
- + "(package URL from packages management service)] from which worker can download the package. #Python",
- listConverter = StringConverter.class)
+ + "(package URL from packages management service)] from which worker can download the package. #Python")
protected String pyFile;
- @Parameter(names = "--go", description = "Path to the main Go executable binary for the function "
+ @Option(names = "--go", description = "Path to the main Go executable binary for the function "
+ "(if the function is written in Go). It also supports URL path [http/https/file "
+ "(file protocol assumes that file already exists on worker host)/function "
+ "(package URL from packages management service)] from which worker can download the package. #Go")
protected String goFile;
- @Parameter(names = {"-i", "--inputs"}, description = "The input topic or "
+ @Option(names = {"-i", "--inputs"}, description = "The input topic or "
+ "topics (multiple topics can be specified as a comma-separated list) of a Pulsar Function"
+ " #Java, Python, Go")
protected String inputs;
// for backwards compatibility purposes
- @Parameter(names = "--topicsPattern", description = "TopicsPattern to consume from list of topics "
+ @Option(names = "--topicsPattern", description = "TopicsPattern to consume from list of topics "
+ "under a namespace that match the pattern. [--input] and [--topic-pattern] are mutually exclusive. "
+ "Add SerDe class name for a pattern in --custom-serde-inputs (supported for java fun only)",
hidden = true)
protected String deprecatedTopicsPattern;
- @Parameter(names = "--topics-pattern", description = "The topic pattern to consume from a list of topics "
+ @Option(names = "--topics-pattern", description = "The topic pattern to consume from a list of topics "
+ "under a namespace that matches the pattern. [--input] and [--topics-pattern] are mutually "
+ "exclusive. Add SerDe class name for a pattern in --custom-serde-inputs (supported for java "
+ "functions only) #Java, Python")
protected String topicsPattern;
- @Parameter(names = {"-o", "--output"},
+ @Option(names = {"-o", "--output"},
description = "The output topic of a Pulsar Function (If none is specified, no output is written)"
+ " #Java, Python, Go")
protected String output;
- @Parameter(names = "--producer-config", description = "The custom producer configuration (as a JSON string)"
+ @Option(names = "--producer-config", description = "The custom producer configuration (as a JSON string)"
+ " #Java")
protected String producerConfig;
// for backwards compatibility purposes
- @Parameter(names = "--logTopic",
+ @Option(names = "--logTopic",
description = "The topic to which the logs of a Pulsar Function are produced", hidden = true)
protected String deprecatedLogTopic;
- @Parameter(names = "--log-topic", description = "The topic to which the logs of a Pulsar Function are produced"
+ @Option(names = "--log-topic", description = "The topic to which the logs of a Pulsar Function are produced"
+ " #Java, Python, Go")
protected String logTopic;
- @Parameter(names = {"-st", "--schema-type"}, description = "The builtin schema type or "
+ @Option(names = {"-st", "--schema-type"}, description = "The builtin schema type or "
+ "custom schema class name to be used for messages output by the function #Java")
protected String schemaType = "";
// for backwards compatibility purposes
- @Parameter(names = "--customSerdeInputs",
+ @Option(names = "--customSerdeInputs",
description = "The map of input topics to SerDe class names (as a JSON string)", hidden = true)
protected String deprecatedCustomSerdeInputString;
- @Parameter(names = "--custom-serde-inputs",
+ @Option(names = "--custom-serde-inputs",
description = "The map of input topics to SerDe class names (as a JSON string) #Java, Python")
protected String customSerdeInputString;
- @Parameter(names = "--custom-schema-inputs",
+ @Option(names = "--custom-schema-inputs",
description = "The map of input topics to Schema properties (as a JSON string) #Java, Python")
protected String customSchemaInputString;
- @Parameter(names = "--custom-schema-outputs",
+ @Option(names = "--custom-schema-outputs",
description = "The map of input topics to Schema properties (as a JSON string) #Java")
protected String customSchemaOutputString;
- @Parameter(names = "--input-specs",
+ @Option(names = "--input-specs",
description = "The map of inputs to custom configuration (as a JSON string) #Java, Python, Go")
protected String inputSpecs;
- @Parameter(names = "--input-type-class-name",
+ @Option(names = "--input-type-class-name",
description = "The class name of input type class #Java, Python, Go")
protected String inputTypeClassName;
// for backwards compatibility purposes
- @Parameter(names = "--outputSerdeClassName",
+ @Option(names = "--outputSerdeClassName",
description = "The SerDe class to be used for messages output by the function", hidden = true)
protected String deprecatedOutputSerdeClassName;
- @Parameter(names = "--output-serde-classname",
+ @Option(names = "--output-serde-classname",
description = "The SerDe class to be used for messages output by the function #Java, Python")
protected String outputSerdeClassName;
- @Parameter(names = "--output-type-class-name",
+ @Option(names = "--output-type-class-name",
description = "The class name of output type class #Java, Python, Go")
protected String outputTypeClassName;
// for backwards compatibility purposes
- @Parameter(names = "--functionConfigFile", description = "The path to a YAML config file that specifies "
+ @Option(names = "--functionConfigFile", description = "The path to a YAML config file that specifies "
+ "the configuration of a Pulsar Function", hidden = true)
protected String deprecatedFnConfigFile;
- @Parameter(names = "--function-config-file",
+ @Option(names = "--function-config-file",
description = "The path to a YAML config file that specifies the configuration of a Pulsar Function"
+ " #Java, Python, Go")
protected String fnConfigFile;
// for backwards compatibility purposes
- @Parameter(names = "--processingGuarantees", description = "The processing guarantees (aka delivery semantics) "
+ @Option(names = "--processingGuarantees", description = "The processing guarantees (aka delivery semantics) "
+ "applied to the function", hidden = true)
protected FunctionConfig.ProcessingGuarantees deprecatedProcessingGuarantees;
- @Parameter(names = "--processing-guarantees",
+ @Option(names = "--processing-guarantees",
description = "The processing guarantees (as known as delivery semantics) applied to the function."
+ " Available values are: `ATLEAST_ONCE`, `ATMOST_ONCE`, `EFFECTIVELY_ONCE`."
+ " If it is not specified, the `ATLEAST_ONCE` delivery guarantee is used."
+ " #Java, Python, Go")
protected FunctionConfig.ProcessingGuarantees processingGuarantees;
// for backwards compatibility purposes
- @Parameter(names = "--userConfig", description = "User-defined config key/values", hidden = true)
+ @Option(names = "--userConfig", description = "User-defined config key/values", hidden = true)
protected String deprecatedUserConfigString;
- @Parameter(names = "--user-config", description = "User-defined config key/values #Java, Python, Go")
+ @Option(names = "--user-config", description = "User-defined config key/values #Java, Python, Go")
protected String userConfigString;
- @Parameter(names = "--retainOrdering",
+ @Option(names = "--retainOrdering",
description = "Function consumes and processes messages in order", hidden = true)
protected Boolean deprecatedRetainOrdering;
- @Parameter(names = "--retain-ordering", description = "Function consumes and processes messages in order #Java")
+ @Option(names = "--retain-ordering", description = "Function consumes and processes messages in order #Java")
protected Boolean retainOrdering;
- @Parameter(names = "--retain-key-ordering",
+ @Option(names = "--retain-key-ordering",
description = "Function consumes and processes messages in key order #Java")
protected Boolean retainKeyOrdering;
- @Parameter(names = "--batch-builder", description = "BatcherBuilder provides two types of "
+ @Option(names = "--batch-builder", description = "BatcherBuilder provides two types of "
+ "batch construction methods, DEFAULT and KEY_BASED. The default value is: DEFAULT")
protected String batchBuilder;
- @Parameter(names = "--forward-source-message-property", description = "Forwarding input message's properties "
- + "to output topic when processing (use false to disable it) #Java", arity = 1)
+ @Option(names = "--forward-source-message-property", description = "Forwarding input message's properties "
+ + "to output topic when processing (use false to disable it) #Java", arity = "1")
protected Boolean forwardSourceMessageProperty = true;
- @Parameter(names = "--subs-name", description = "Pulsar source subscription name if user wants a specific "
+ @Option(names = "--subs-name", description = "Pulsar source subscription name if user wants a specific "
+ "subscription-name for input-topic consumer #Java, Python, Go")
protected String subsName;
- @Parameter(names = "--subs-position", description = "Pulsar source subscription position if user wants to "
+ @Option(names = "--subs-position", description = "Pulsar source subscription position if user wants to "
+ "consume messages from the specified location #Java")
protected SubscriptionInitialPosition subsPosition;
- @Parameter(names = "--skip-to-latest", description = "Whether or not the consumer skip to latest message "
- + "upon function instance restart", arity = 1)
+ @Option(names = "--skip-to-latest", description = "Whether or not the consumer skip to latest message "
+ + "upon function instance restart", arity = "1")
protected Boolean skipToLatest;
- @Parameter(names = "--parallelism", description = "The parallelism factor of a Pulsar Function "
+ @Option(names = "--parallelism", description = "The parallelism factor of a Pulsar Function "
+ "(i.e. the number of function instances to run) #Java")
protected Integer parallelism;
- @Parameter(names = "--cpu", description = "The cpu in cores that need to be allocated "
+ @Option(names = "--cpu", description = "The cpu in cores that need to be allocated "
+ "per function instance(applicable only to docker runtime) #Java(Process & K8s),Python(K8s),Go(K8s)")
protected Double cpu;
- @Parameter(names = "--ram", description = "The ram in bytes that need to be allocated "
+ @Option(names = "--ram", description = "The ram in bytes that need to be allocated "
+ "per function instance(applicable only to process/docker runtime)"
+ " #Java(Process & K8s),Python(K8s),Go(K8s)")
protected Long ram;
- @Parameter(names = "--disk", description = "The disk in bytes that need to be allocated "
+ @Option(names = "--disk", description = "The disk in bytes that need to be allocated "
+ "per function instance(applicable only to docker runtime) #Java(Process & K8s),Python(K8s),Go(K8s)")
protected Long disk;
// for backwards compatibility purposes
- @Parameter(names = "--windowLengthCount", description = "The number of messages per window", hidden = true)
+ @Option(names = "--windowLengthCount", description = "The number of messages per window", hidden = true)
protected Integer deprecatedWindowLengthCount;
- @Parameter(names = "--window-length-count", description = "The number of messages per window #Java")
+ @Option(names = "--window-length-count", description = "The number of messages per window #Java")
protected Integer windowLengthCount;
// for backwards compatibility purposes
- @Parameter(names = "--windowLengthDurationMs",
+ @Option(names = "--windowLengthDurationMs",
description = "The time duration of the window in milliseconds", hidden = true)
protected Long deprecatedWindowLengthDurationMs;
- @Parameter(names = "--window-length-duration-ms",
+ @Option(names = "--window-length-duration-ms",
description = "The time duration of the window in milliseconds #Java")
protected Long windowLengthDurationMs;
// for backwards compatibility purposes
- @Parameter(names = "--slidingIntervalCount",
+ @Option(names = "--slidingIntervalCount",
description = "The number of messages after which the window slides", hidden = true)
protected Integer deprecatedSlidingIntervalCount;
- @Parameter(names = "--sliding-interval-count",
+ @Option(names = "--sliding-interval-count",
description = "The number of messages after which the window slides #Java")
protected Integer slidingIntervalCount;
// for backwards compatibility purposes
- @Parameter(names = "--slidingIntervalDurationMs",
+ @Option(names = "--slidingIntervalDurationMs",
description = "The time duration after which the window slides", hidden = true)
protected Long deprecatedSlidingIntervalDurationMs;
- @Parameter(names = "--sliding-interval-duration-ms",
+ @Option(names = "--sliding-interval-duration-ms",
description = "The time duration after which the window slides #Java")
protected Long slidingIntervalDurationMs;
// for backwards compatibility purposes
- @Parameter(names = "--autoAck",
+ @Option(names = "--autoAck",
description = "Whether or not the framework acknowledges messages automatically", hidden = true)
protected Boolean deprecatedAutoAck = null;
- @Parameter(names = "--auto-ack",
+ @Option(names = "--auto-ack",
description = "Whether or not the framework acknowledges messages automatically"
- + " #Java, Python, Go", arity = 1)
+ + " #Java, Python, Go", arity = "1")
protected Boolean autoAck;
// for backwards compatibility purposes
- @Parameter(names = "--timeoutMs", description = "The message timeout in milliseconds", hidden = true)
+ @Option(names = "--timeoutMs", description = "The message timeout in milliseconds", hidden = true)
protected Long deprecatedTimeoutMs;
- @Parameter(names = "--timeout-ms", description = "The message timeout in milliseconds #Java, Python")
+ @Option(names = "--timeout-ms", description = "The message timeout in milliseconds #Java, Python")
protected Long timeoutMs;
- @Parameter(names = "--max-message-retries",
+ @Option(names = "--max-message-retries",
description = "How many times should we try to process a message before giving up #Java")
protected Integer maxMessageRetries;
- @Parameter(names = "--custom-runtime-options", description = "A string that encodes options to "
+ @Option(names = "--custom-runtime-options", description = "A string that encodes options to "
+ "customize the runtime, see docs for configured runtime for details #Java")
protected String customRuntimeOptions;
- @Parameter(names = "--secrets", description = "The map of secretName to an object that encapsulates "
+ @Option(names = "--secrets", description = "The map of secretName to an object that encapsulates "
+ "how the secret is fetched by the underlying secrets provider #Java, Python")
protected String secretsString;
- @Parameter(names = "--dead-letter-topic",
+ @Option(names = "--dead-letter-topic",
description = "The topic where messages that are not processed successfully are sent to #Java")
protected String deadLetterTopic;
protected FunctionConfig functionConfig;
@@ -447,7 +431,6 @@ private void mergeArgs() {
@Override
void processArguments() throws Exception {
- super.processArguments();
// merge deprecated args with new args
mergeArgs();
@@ -459,7 +442,15 @@ void processArguments() throws Exception {
}
if (null != fqfn) {
- parseFullyQualifiedFunctionName(fqfn, functionConfig);
+ String[] args = fqfn.split("/");
+ if (args.length != 3) {
+ throw new ParameterException("Fully qualified function names (FQFNs) must "
+ + "be of the form tenant/namespace/name");
+ } else {
+ functionConfig.setTenant(args[0]);
+ functionConfig.setNamespace(args[1]);
+ functionConfig.setName(args[2]);
+ }
} else {
if (null != tenant) {
functionConfig.setTenant(tenant);
@@ -738,73 +729,73 @@ && isBlank(functionConfig.getGo())) {
}
}
- @Parameters(commandDescription = "Run a Pulsar Function locally, rather than deploy to a Pulsar cluster)")
+ @Command(description = "Run a Pulsar Function locally, rather than deploy to a Pulsar cluster)")
class LocalRunner extends FunctionDetailsCommand {
// TODO: this should become BookKeeper URL and it should be fetched from Pulsar client.
// for backwards compatibility purposes
- @Parameter(names = "--stateStorageServiceUrl", description = "The URL for the state storage service "
+ @Option(names = "--stateStorageServiceUrl", description = "The URL for the state storage service "
+ "(the default is Apache BookKeeper)", hidden = true)
protected String deprecatedStateStorageServiceUrl;
- @Parameter(names = "--state-storage-service-url", description = "The URL for the state storage service "
+ @Option(names = "--state-storage-service-url", description = "The URL for the state storage service "
+ "(the default is Apache BookKeeper) #Java, Python")
protected String stateStorageServiceUrl;
// for backwards compatibility purposes
- @Parameter(names = "--brokerServiceUrl", description = "The URL for Pulsar broker", hidden = true)
+ @Option(names = "--brokerServiceUrl", description = "The URL for Pulsar broker", hidden = true)
protected String deprecatedBrokerServiceUrl;
- @Parameter(names = "--broker-service-url", description = "The URL for Pulsar broker #Java, Python, Go")
+ @Option(names = "--broker-service-url", description = "The URL for Pulsar broker #Java, Python, Go")
protected String brokerServiceUrl;
- @Parameter(names = "--web-service-url", description = "The URL for Pulsar web service #Java, Python")
+ @Option(names = "--web-service-url", description = "The URL for Pulsar web service #Java, Python")
protected String webServiceUrl = null;
// for backwards compatibility purposes
- @Parameter(names = "--clientAuthPlugin", description = "Client authentication plugin using "
+ @Option(names = "--clientAuthPlugin", description = "Client authentication plugin using "
+ "which function-process can connect to broker", hidden = true)
protected String deprecatedClientAuthPlugin;
- @Parameter(names = "--client-auth-plugin",
+ @Option(names = "--client-auth-plugin",
description = "Client authentication plugin using which function-process can connect to broker"
+ " #Java, Python")
protected String clientAuthPlugin;
// for backwards compatibility purposes
- @Parameter(names = "--clientAuthParams", description = "Client authentication param", hidden = true)
+ @Option(names = "--clientAuthParams", description = "Client authentication param", hidden = true)
protected String deprecatedClientAuthParams;
- @Parameter(names = "--client-auth-params", description = "Client authentication param #Java, Python")
+ @Option(names = "--client-auth-params", description = "Client authentication param #Java, Python")
protected String clientAuthParams;
// for backwards compatibility purposes
- @Parameter(names = "--use_tls", description = "Use tls connection", hidden = true)
+ @Option(names = "--use_tls", description = "Use tls connection", hidden = true)
protected Boolean deprecatedUseTls = null;
- @Parameter(names = "--use-tls", description = "Use tls connection #Java, Python")
+ @Option(names = "--use-tls", description = "Use tls connection #Java, Python")
protected boolean useTls;
// for backwards compatibility purposes
- @Parameter(names = "--tls_allow_insecure", description = "Allow insecure tls connection", hidden = true)
+ @Option(names = "--tls_allow_insecure", description = "Allow insecure tls connection", hidden = true)
protected Boolean deprecatedTlsAllowInsecureConnection = null;
- @Parameter(names = "--tls-allow-insecure", description = "Allow insecure tls connection #Java, Python")
+ @Option(names = "--tls-allow-insecure", description = "Allow insecure tls connection #Java, Python")
protected boolean tlsAllowInsecureConnection;
// for backwards compatibility purposes
- @Parameter(names = "--hostname_verification_enabled",
+ @Option(names = "--hostname_verification_enabled",
description = "Enable hostname verification", hidden = true)
protected Boolean deprecatedTlsHostNameVerificationEnabled = null;
- @Parameter(names = "--hostname-verification-enabled", description = "Enable hostname verification"
+ @Option(names = "--hostname-verification-enabled", description = "Enable hostname verification"
+ " #Java, Python")
protected boolean tlsHostNameVerificationEnabled;
// for backwards compatibility purposes
- @Parameter(names = "--tls_trust_cert_path", description = "tls trust cert file path", hidden = true)
+ @Option(names = "--tls_trust_cert_path", description = "tls trust cert file path", hidden = true)
protected String deprecatedTlsTrustCertFilePath;
- @Parameter(names = "--tls-trust-cert-path", description = "tls trust cert file path #Java, Python")
+ @Option(names = "--tls-trust-cert-path", description = "tls trust cert file path #Java, Python")
protected String tlsTrustCertFilePath;
// for backwards compatibility purposes
- @Parameter(names = "--instanceIdOffset", description = "Start the instanceIds from this offset", hidden = true)
+ @Option(names = "--instanceIdOffset", description = "Start the instanceIds from this offset", hidden = true)
protected Integer deprecatedInstanceIdOffset = null;
- @Parameter(names = "--instance-id-offset", description = "Start the instanceIds from this offset #Java, Python")
+ @Option(names = "--instance-id-offset", description = "Start the instanceIds from this offset #Java, Python")
protected Integer instanceIdOffset = 0;
- @Parameter(names = "--runtime", description = "either THREAD or PROCESS. Only applies for Java functions #Java")
+ @Option(names = "--runtime", description = "either THREAD or PROCESS. Only applies for Java functions #Java")
protected String runtime;
- @Parameter(names = "--secrets-provider-classname", description = "Whats the classname for secrets provider"
+ @Option(names = "--secrets-provider-classname", description = "Whats the classname for secrets provider"
+ " #Java, Python")
protected String secretsProviderClassName;
- @Parameter(names = "--secrets-provider-config",
+ @Option(names = "--secrets-provider-config",
description = "Config that needs to be passed to secrets provider #Java, Python")
protected String secretsProviderConfig;
- @Parameter(names = "--metrics-port-start", description = "The starting port range for metrics server"
+ @Option(names = "--metrics-port-start", description = "The starting port range for metrics server"
+ " #Java, Python, Go")
protected String metricsPortStart;
@@ -847,7 +838,7 @@ void runCmd() throws Exception {
localRunArgs.add("--functionConfig");
localRunArgs.add(new Gson().toJson(functionConfig));
for (Field field : this.getClass().getDeclaredFields()) {
- if (field.getName().startsWith("DEPRECATED")) {
+ if (field.getName().toUpperCase().startsWith("DEPRECATED")) {
continue;
}
if (field.getName().contains("$")) {
@@ -865,7 +856,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Create a Pulsar Function in cluster mode (deploy it on a Pulsar cluster)")
+ @Command(description = "Create a Pulsar Function in cluster mode (deploy it on a Pulsar cluster)")
class CreateFunction extends FunctionDetailsCommand {
@Override
void runCmd() throws Exception {
@@ -883,7 +874,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Fetch information about a Pulsar Function")
+ @Command(description = "Fetch information about a Pulsar Function")
class GetFunction extends FunctionCommand {
@Override
void runCmd() throws Exception {
@@ -893,10 +884,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Check the current status of a Pulsar Function")
+ @Command(aliases = "getstatus", description = "Check the current status of a Pulsar Function")
class GetFunctionStatus extends FunctionCommand {
- @Parameter(names = "--instance-id", description = "The function instanceId "
+ @Option(names = "--instance-id", description = "The function instanceId "
+ "(Get-status of all instances if instance-id is not provided)")
protected String instanceId;
@@ -911,10 +902,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Get the current stats of a Pulsar Function")
+ @Command(description = "Get the current stats of a Pulsar Function")
class GetFunctionStats extends FunctionCommand {
- @Parameter(names = "--instance-id", description = "The function instanceId "
+ @Option(names = "--instance-id", description = "The function instanceId "
+ "(Get-stats of all instances if instance-id is not provided)")
protected String instanceId;
@@ -930,10 +921,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Restart function instance")
+ @Command(description = "Restart function instance")
class RestartFunction extends FunctionCommand {
- @Parameter(names = "--instance-id", description = "The function instanceId "
+ @Option(names = "--instance-id", description = "The function instanceId "
+ "(restart all instances if instance-id is not provided)")
protected String instanceId;
@@ -953,10 +944,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Stops function instance")
+ @Command(description = "Stops function instance")
class StopFunction extends FunctionCommand {
- @Parameter(names = "--instance-id", description = "The function instanceId "
+ @Option(names = "--instance-id", description = "The function instanceId "
+ "(stop all instances if instance-id is not provided)")
protected String instanceId;
@@ -975,10 +966,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Starts a stopped function instance")
+ @Command(description = "Starts a stopped function instance")
class StartFunction extends FunctionCommand {
- @Parameter(names = "--instance-id", description = "The function instanceId "
+ @Option(names = "--instance-id", description = "The function instanceId "
+ "(start all instances if instance-id is not provided)")
protected String instanceId;
@@ -997,7 +988,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Delete a Pulsar Function that is running on a Pulsar cluster")
+ @Command(description = "Delete a Pulsar Function that is running on a Pulsar cluster")
class DeleteFunction extends FunctionCommand {
@Override
void runCmd() throws Exception {
@@ -1006,10 +997,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Update a Pulsar Function that has been deployed to a Pulsar cluster")
+ @Command(description = "Update a Pulsar Function that has been deployed to a Pulsar cluster")
class UpdateFunction extends FunctionDetailsCommand {
- @Parameter(names = "--update-auth-data", description = "Whether or not to update the auth data #Java, Python")
+ @Option(names = "--update-auth-data", description = "Whether or not to update the auth data #Java, Python")
protected boolean updateAuthData;
@Override
@@ -1046,7 +1037,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "List all Pulsar Functions running under a specific tenant and namespace")
+ @Command(description = "List all Pulsar Functions running under a specific tenant and namespace")
class ListFunctions extends NamespaceCommand {
@Override
void runCmd() throws Exception {
@@ -1054,13 +1045,13 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Fetch the current state associated with a Pulsar Function")
+ @Command(description = "Fetch the current state associated with a Pulsar Function")
class StateGetter extends FunctionCommand {
- @Parameter(names = { "-k", "--key" }, description = "Key name of State")
+ @Option(names = {"-k", "--key"}, description = "Key name of State")
private String key = null;
- @Parameter(names = { "-w", "--watch" }, description = "Watch for changes in the value associated with a key "
+ @Option(names = {"-w", "--watch"}, description = "Watch for changes in the value associated with a key "
+ "for a Pulsar Function")
private boolean watch = false;
@@ -1089,10 +1080,10 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Put the state associated with a Pulsar Function")
+ @Command(description = "Put the state associated with a Pulsar Function")
class StatePutter extends FunctionCommand {
- @Parameter(names = { "-s", "--state" }, description = "The FunctionState that needs to be put", required = true)
+ @Option(names = {"-s", "--state"}, description = "The FunctionState that needs to be put", required = true)
private String state = null;
@Override
@@ -1104,22 +1095,22 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Trigger the specified Pulsar Function with a supplied value")
+ @Command(description = "Trigger the specified Pulsar Function with a supplied value")
class TriggerFunction extends FunctionCommand {
// for backward compatibility purposes
- @Parameter(names = "--triggerValue",
+ @Option(names = "--triggerValue",
description = "The value with which you want to trigger the function", hidden = true)
protected String deprecatedTriggerValue;
- @Parameter(names = "--trigger-value", description = "The value with which you want to trigger the function")
+ @Option(names = "--trigger-value", description = "The value with which you want to trigger the function")
protected String triggerValue;
// for backward compatibility purposes
- @Parameter(names = "--triggerFile", description = "The path to the file that contains the data with which "
+ @Option(names = "--triggerFile", description = "The path to the file that contains the data with which "
+ "you want to trigger the function", hidden = true)
protected String deprecatedTriggerFile;
- @Parameter(names = "--trigger-file", description = "The path to the file that contains the data with which "
+ @Option(names = "--trigger-file", description = "The path to the file that contains the data with which "
+ "you want to trigger the function")
protected String triggerFile;
- @Parameter(names = "--topic", description = "The specific topic name that the function consumes from that"
+ @Option(names = "--topic", description = "The specific topic name that the function consumes from that"
+ " you want to inject the data to")
protected String topic;
@@ -1145,23 +1136,20 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Upload File Data to Pulsar", hidden = true)
+ @Command(description = "Upload File Data to Pulsar")
class UploadFunction extends BaseCommand {
// for backward compatibility purposes
- @Parameter(
+ @Option(
names = "--sourceFile",
- description = "The file whose contents need to be uploaded",
- listConverter = StringConverter.class, hidden = true)
+ description = "The file whose contents need to be uploaded", hidden = true)
protected String deprecatedSourceFile;
- @Parameter(
+ @Option(
names = "--source-file",
- description = "The file whose contents need to be uploaded",
- listConverter = StringConverter.class)
+ description = "The file whose contents need to be uploaded")
protected String sourceFile;
- @Parameter(
+ @Option(
names = "--path",
- description = "Path or functionPkgUrl where the contents need to be stored",
- listConverter = StringConverter.class, required = true)
+ description = "Path or functionPkgUrl where the contents need to be stored", required = true)
protected String path;
private void mergeArgs() {
@@ -1182,25 +1170,22 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Download File Data from Pulsar", hidden = true)
+ @Command(description = "Download File Data from Pulsar")
class DownloadFunction extends FunctionCommand {
// for backward compatibility purposes
- @Parameter(
+ @Option(
names = "--destinationFile",
- description = "The file to store downloaded content",
- listConverter = StringConverter.class, hidden = true)
+ description = "The file to store downloaded content", hidden = true)
protected String deprecatedDestinationFile;
- @Parameter(
+ @Option(
names = "--destination-file",
- description = "The file to store downloaded content",
- listConverter = StringConverter.class)
+ description = "The file to store downloaded content")
protected String destinationFile;
- @Parameter(
+ @Option(
names = "--path",
- description = "Path or functionPkgUrl to store the content",
- listConverter = StringConverter.class, required = false, hidden = true)
+ description = "Path or functionPkgUrl to store the content", required = false, hidden = true)
protected String path;
- @Parameter(
+ @Option(
names = "--transform-function",
description = "Download the transform Function of the connector")
protected Boolean transformFunction = false;
@@ -1235,7 +1220,7 @@ void runCmd() throws Exception {
}
}
- @Parameters(commandDescription = "Reload the available built-in functions")
+ @Command(description = "Reload the available built-in functions")
public class ReloadBuiltInFunctions extends CmdFunctions.BaseCommand {
@Override
@@ -1262,25 +1247,25 @@ public CmdFunctions(Supplier admin) throws PulsarClientException {
restart = new RestartFunction();
stop = new StopFunction();
start = new StartFunction();
- jcommander.addCommand("localrun", getLocalRunner());
- jcommander.addCommand("create", getCreater());
- jcommander.addCommand("delete", getDeleter());
- jcommander.addCommand("update", getUpdater());
- jcommander.addCommand("get", getGetter());
- jcommander.addCommand("restart", getRestarter());
- jcommander.addCommand("stop", getStopper());
- jcommander.addCommand("start", getStarter());
+ addCommand("localrun", getLocalRunner());
+ addCommand("create", getCreater());
+ addCommand("delete", getDeleter());
+ addCommand("update", getUpdater());
+ addCommand("get", getGetter());
+ addCommand("restart", getRestarter());
+ addCommand("stop", getStopper());
+ addCommand("start", getStarter());
// TODO depecreate getstatus
- jcommander.addCommand("status", getStatuser(), "getstatus");
- jcommander.addCommand("stats", getFunctionStats());
- jcommander.addCommand("list", getLister());
- jcommander.addCommand("querystate", getStateGetter());
- jcommander.addCommand("putstate", getStatePutter());
- jcommander.addCommand("trigger", getTriggerer());
- jcommander.addCommand("upload", getUploader());
- jcommander.addCommand("download", getDownloader());
- jcommander.addCommand("reload", new ReloadBuiltInFunctions());
- jcommander.addCommand("available-functions", new ListBuiltInFunctions());
+ addCommand("status", getStatuser(), "getstatus");
+ addCommand("stats", getFunctionStats());
+ addCommand("list", getLister());
+ addCommand("querystate", getStateGetter());
+ addCommand("putstate", getStatePutter());
+ addCommand("trigger", getTriggerer());
+ addCommand("upload", getUploader());
+ addCommand("download", getDownloader());
+ addCommand("reload", new ReloadBuiltInFunctions());
+ addCommand("available-functions", new ListBuiltInFunctions());
}
@VisibleForTesting
@@ -1358,27 +1343,15 @@ StartFunction getStarter() {
return start;
}
- private void parseFullyQualifiedFunctionName(String fqfn, FunctionConfig functionConfig) {
- String[] args = fqfn.split("/");
- if (args.length != 3) {
- throw new ParameterException("Fully qualified function names (FQFNs) must "
- + "be of the form tenant/namespace/name");
- } else {
- functionConfig.setTenant(args[0]);
- functionConfig.setNamespace(args[1]);
- functionConfig.setName(args[2]);
- }
- }
-
- @Parameters(commandDescription = "Get the list of Pulsar Functions supported by Pulsar cluster")
+ @Command(description = "Get the list of Pulsar Functions supported by Pulsar cluster")
public class ListBuiltInFunctions extends BaseCommand {
@Override
void runCmd() throws Exception {
getAdmin().functions().getBuiltInFunctions()
.forEach(function -> {
- System.out.println(function.getName());
- System.out.println(WordUtils.wrap(function.getDescription(), 80));
- System.out.println("----------------------------------------");
+ print(function.getName());
+ print(WordUtils.wrap(function.getDescription(), 80));
+ print("----------------------------------------");
});
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdGenerateDocument.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdGenerateDocument.java
index cab037faf8ffc..3f728ca73ea69 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdGenerateDocument.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdGenerateDocument.java
@@ -18,64 +18,42 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.DefaultUsageFormatter;
-import com.beust.jcommander.IUsageFormatter;
-import com.beust.jcommander.JCommander;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterDescription;
-import com.beust.jcommander.Parameters;
+import static org.apache.pulsar.internal.CommandDescriptionUtil.getArgDescription;
+import static org.apache.pulsar.internal.CommandDescriptionUtil.getCommandDescription;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
-import java.util.Map;
-import java.util.Properties;
+import java.util.Set;
import java.util.function.Supplier;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
+import picocli.CommandLine;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Model.ArgSpec;
+import picocli.CommandLine.Model.CommandSpec;
+import picocli.CommandLine.Model.OptionSpec;
+import picocli.CommandLine.Parameters;
+import picocli.CommandLine.Spec;
@Getter
-@Parameters(commandDescription = "Generate documents automatically.")
+@Command(description = "Generate documents automatically.")
@Slf4j
public class CmdGenerateDocument extends CmdBase {
- private final JCommander baseJcommander;
- private final IUsageFormatter usageFormatter;
-
- private PulsarAdminTool tool;
+ @Spec
+ private CommandSpec pulsarAdminCommandSpec;
public CmdGenerateDocument(Supplier admin) {
super("documents", admin);
- baseJcommander = new JCommander();
- usageFormatter = new DefaultUsageFormatter(baseJcommander);
- try {
- tool = new PulsarAdminTool(new Properties());
- } catch (Exception e) {
- System.err.println(e.getMessage());
- System.err.println();
- baseJcommander.usage();
- return;
- }
- for (Map.Entry> c : tool.commandMap.entrySet()) {
- try {
- if (!c.getKey().equals("documents") && c.getValue() != null) {
- baseJcommander.addCommand(
- c.getKey(), c.getValue().getConstructor(Supplier.class).newInstance(admin));
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- System.err.println();
- baseJcommander.usage();
- return;
- }
- }
- jcommander.addCommand("generate", new GenerateDocument());
+ addCommand("generate", new GenerateDocument());
}
- @Parameters(commandDescription = "Generate document for modules")
+ @Command(description = "Generate document for modules")
private class GenerateDocument extends CliCommand {
- @Parameter(description = "Please specify the module name, if not, documents will be generated for all modules."
+ @Parameters(description = "Please specify the module name, if not, documents will be generated for all modules."
+ "Optional modules(clusters, tenants, brokers, broker-stats, namespaces, topics, schemas, bookies,"
+ "functions, ns-isolation-policy, resource-quotas, functions, sources, sinks)")
private java.util.List modules;
@@ -84,13 +62,17 @@ private class GenerateDocument extends CliCommand {
void run() throws PulsarAdminException {
StringBuilder sb = new StringBuilder();
if (modules == null || modules.isEmpty()) {
- baseJcommander.getCommands().forEach((k, v) ->
- this.generateDocument(sb, k, v)
+ pulsarAdminCommandSpec.parent().subcommands().forEach((k, v) ->
+ this.generateDocument(sb, k, v)
);
} else {
- String module = getOneArgument(modules);
- JCommander obj = baseJcommander.getCommands().get(module);
- this.generateDocument(sb, module, obj);
+ modules.forEach(module -> {
+ CommandLine commandLine = pulsarAdminCommandSpec.parent().subcommands().get(module);
+ if (commandLine == null) {
+ return;
+ }
+ this.generateDocument(sb, module, commandLine);
+ });
}
}
@@ -99,21 +81,29 @@ private boolean needsLangSupport(String module, String subK) {
return module.equals("functions") && Arrays.asList(langSupport).contains(subK);
}
- private void generateDocument(StringBuilder sb, String module, JCommander obj) {
+ private final Set generatedModule = new HashSet<>();
+
+ private void generateDocument(StringBuilder sb, String module, CommandLine obj) {
+ // Filter the deprecated command
+ if (generatedModule.contains(module)) {
+ return;
+ }
+ String commandName = obj.getCommandName();
+ generatedModule.add(commandName);
+
sb.append("# ").append(module).append("\n\n");
- sb.append(usageFormatter.getCommandDescription(module)).append("\n");
+ sb.append(getCommandDescription(obj)).append("\n");
sb.append("\n\n```shell\n")
.append("$ pulsar-admin ").append(module).append(" subcommand")
.append("\n```");
sb.append("\n\n");
- CmdBase cmdObj = (CmdBase) obj.getObjects().get(0);
- cmdObj.jcommander.getCommands().forEach((subK, subV) -> {
+ obj.getSubcommands().forEach((subK, subV) -> {
sb.append("\n\n## ").append(subK).append("\n\n");
- sb.append(cmdObj.getUsageFormatter().getCommandDescription(subK)).append("\n\n");
+ sb.append(getCommandDescription(subV)).append("\n\n");
sb.append("**Command:**\n\n");
sb.append("```shell\n$ pulsar-admin ").append(module).append(" ")
.append(subK).append(" options").append("\n```\n\n");
- List options = cmdObj.jcommander.getCommands().get(subK).getParameters();
+ List options = obj.getCommandSpec().args();
if (options.size() > 0) {
sb.append("**Options:**\n\n");
sb.append("|Flag|Description|Default|");
@@ -124,22 +114,23 @@ private void generateDocument(StringBuilder sb, String module, JCommander obj) {
sb.append("\n|---|---|---|\n");
}
}
- options.stream().filter(
- ele -> ele.getParameterAnnotation() == null
- || !ele.getParameterAnnotation().hidden()
- ).forEach((option) -> {
- String[] descriptions = option.getDescription().replace("\n", " ").split(" #");
- sb.append("| `").append(option.getNames())
- .append("` | ").append(descriptions[0])
- .append("|").append(option.getDefault()).append("|");
- if (needsLangSupport(module, subK) && descriptions.length > 1) {
- sb.append(descriptions[1]);
- }
- sb.append("|\n");
- }
- );
+ options.forEach(ele -> {
+ if (ele.hidden() || !(ele instanceof OptionSpec)) {
+ return;
+ }
+
+ String argDescription = getArgDescription(ele);
+ String[] descriptions = argDescription.replace("\n", " ").split(" #");
+ sb.append("| `").append(Arrays.toString(((OptionSpec) ele).names()))
+ .append("` | ").append(descriptions[0])
+ .append("|").append(ele.defaultValue()).append("|");
+ if (needsLangSupport(module, subK) && descriptions.length > 1) {
+ sb.append(descriptions[1]);
+ }
+ sb.append("|\n");
+ });
+ System.out.println(sb);
});
- System.out.println(sb);
}
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaceIsolationPolicy.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaceIsolationPolicy.java
index 8de7ef500eaa0..e9896decd8c96 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaceIsolationPolicy.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaceIsolationPolicy.java
@@ -18,17 +18,12 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
-import com.beust.jcommander.Parameters;
-import com.beust.jcommander.converters.CommaParameterSplitter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
-import org.apache.pulsar.admin.cli.utils.NameValueParameterSplitter;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData;
@@ -37,46 +32,48 @@
import org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationDataImpl;
import org.apache.pulsar.common.policies.data.NamespaceIsolationData;
import org.apache.pulsar.common.policies.data.NamespaceIsolationDataImpl;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations about namespace isolation policy")
+@Command(description = "Operations about namespace isolation policy")
public class CmdNamespaceIsolationPolicy extends CmdBase {
- @Parameters(commandDescription = "Create/Update a namespace isolation policy for a cluster. "
+ @Command(description = "Create/Update a namespace isolation policy for a cluster. "
+ "This operation requires Pulsar super-user privileges")
private class SetPolicy extends CliCommand {
- @Parameter(description = "cluster-name policy-name", required = true)
- private List params;
+ @Parameters(description = "cluster-name", index = "0", arity = "1")
+ private String clusterName;
+ @Parameters(description = "policy-name", index = "1", arity = "1")
+ private String policyName;
- @Parameter(names = "--namespaces", description = "comma separated namespaces-regex list",
- required = true, splitter = CommaParameterSplitter.class)
+ @Option(names = "--namespaces", description = "comma separated namespaces-regex list",
+ required = true, split = ",")
private List namespaces;
- @Parameter(names = "--primary", description = "comma separated primary-broker-regex list. "
+ @Option(names = "--primary", description = "comma separated primary-broker-regex list. "
+ "In Pulsar, when namespaces (more specifically, namespace bundles) are assigned dynamically to "
+ "brokers, the namespace isolation policy limits the set of brokers that can be used for assignment. "
+ "Before topics are assigned to brokers, you can set the namespace isolation policy with a primary or "
+ "a secondary regex to select desired brokers. If no broker matches the specified regex, you cannot "
+ "create a topic. If there are not enough primary brokers, topics are assigned to secondary brokers. "
+ "If there are not enough secondary brokers, topics are assigned to other brokers which do not have "
- + "any isolation policies.", required = true, splitter = CommaParameterSplitter.class)
+ + "any isolation policies.", required = true, split = ",")
private List primary;
- @Parameter(names = "--secondary", description = "comma separated secondary-broker-regex list",
- required = false, splitter = CommaParameterSplitter.class)
+ @Option(names = "--secondary", description = "comma separated secondary-broker-regex list",
+ required = false, split = ",")
private List secondary = new ArrayList(); // optional
- @Parameter(names = "--auto-failover-policy-type",
+ @Option(names = "--auto-failover-policy-type",
description = "auto failover policy type name ['min_available']", required = true)
private String autoFailoverPolicyTypeName;
- @Parameter(names = "--auto-failover-policy-params",
+ @Option(names = "--auto-failover-policy-params",
description = "comma separated name=value auto failover policy parameters",
- required = true, converter = NameValueParameterSplitter.class)
+ required = true, split = ",")
private Map autoFailoverPolicyParams;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params, 0, 2);
- String policyName = getOneArgument(params, 1, 2);
-
// validate and create the POJO
NamespaceIsolationData namespaceIsolationData = createNamespaceIsolationData(namespaces, primary, secondary,
autoFailoverPolicyTypeName, autoFailoverPolicyParams);
@@ -85,15 +82,13 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "List all namespace isolation policies of a cluster. "
+ @Command(description = "List all namespace isolation policies of a cluster. "
+ "This operation requires Pulsar super-user privileges")
private class GetAllPolicies extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String clusterName;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params);
-
Map policyMap =
getAdmin().clusters().getNamespaceIsolationPolicies(clusterName);
@@ -101,15 +96,13 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "List all brokers with namespace-isolation policies attached to it. "
+ @Command(description = "List all brokers with namespace-isolation policies attached to it. "
+ "This operation requires Pulsar super-user privileges")
private class GetAllBrokersWithPolicies extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private List params;
+ @Parameters(description = "cluster-name", arity = "1")
+ private String clusterName;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params);
-
List brokers = getAdmin().clusters()
.getBrokersWithNamespaceIsolationPolicy(clusterName);
List data = new ArrayList<>();
@@ -118,19 +111,16 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get broker with namespace-isolation policies attached to it. "
+ @Command(description = "Get broker with namespace-isolation policies attached to it. "
+ "This operation requires Pulsar super-user privileges")
private class GetBrokerWithPolicies extends CliCommand {
- @Parameter(description = "cluster-name", required = true)
- private List params;
-
- @Parameter(names = "--broker",
+ @Parameters(description = "cluster-name", arity = "1")
+ private String clusterName;
+ @Option(names = "--broker",
description = "Broker-name to get namespace-isolation policies attached to it", required = true)
private String broker;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params);
-
BrokerNamespaceIsolationDataImpl brokerData = (BrokerNamespaceIsolationDataImpl) getAdmin().clusters()
.getBrokerWithNamespaceIsolationPolicy(clusterName, broker);
@@ -138,16 +128,15 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get namespace isolation policy of a cluster. "
+ @Command(description = "Get namespace isolation policy of a cluster. "
+ "This operation requires Pulsar super-user privileges")
private class GetPolicy extends CliCommand {
- @Parameter(description = "cluster-name policy-name", required = true)
- private List params;
+ @Parameters(description = "cluster-name", index = "0", arity = "1")
+ private String clusterName;
+ @Parameters(description = "policy-name", index = "1", arity = "1")
+ private String policyName;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params, 0, 2);
- String policyName = getOneArgument(params, 1, 2);
-
NamespaceIsolationDataImpl nsIsolationData = (NamespaceIsolationDataImpl) getAdmin().clusters()
.getNamespaceIsolationPolicy(clusterName, policyName);
@@ -155,16 +144,15 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Delete namespace isolation policy of a cluster. "
+ @Command(description = "Delete namespace isolation policy of a cluster. "
+ "This operation requires Pulsar super-user privileges")
private class DeletePolicy extends CliCommand {
- @Parameter(description = "cluster-name policy-name", required = true)
- private List params;
+ @Parameters(description = "cluster-name", index = "0", arity = "1")
+ private String clusterName;
+ @Parameters(description = "policy-name", index = "1", arity = "1")
+ private String policyName;
void run() throws PulsarAdminException {
- String clusterName = getOneArgument(params, 0, 2);
- String policyName = getOneArgument(params, 1, 2);
-
getAdmin().clusters().deleteNamespaceIsolationPolicy(clusterName, policyName);
}
}
@@ -251,12 +239,12 @@ private NamespaceIsolationData createNamespaceIsolationData(List namespa
public CmdNamespaceIsolationPolicy(Supplier admin) {
super("ns-isolation-policy", admin);
- jcommander.addCommand("set", new SetPolicy());
- jcommander.addCommand("get", new GetPolicy());
- jcommander.addCommand("list", new GetAllPolicies());
- jcommander.addCommand("delete", new DeletePolicy());
- jcommander.addCommand("brokers", new GetAllBrokersWithPolicies());
- jcommander.addCommand("broker", new GetBrokerWithPolicies());
+ addCommand("set", new SetPolicy());
+ addCommand("get", new GetPolicy());
+ addCommand("list", new GetAllPolicies());
+ addCommand("delete", new DeletePolicy());
+ addCommand("brokers", new GetAllBrokersWithPolicies());
+ addCommand("broker", new GetBrokerWithPolicies());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
index c825397b8d84c..da8929da97cca 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
@@ -18,10 +18,6 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.ParameterException;
-import com.beust.jcommander.Parameters;
-import com.beust.jcommander.converters.CommaParameterSplitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@@ -36,15 +32,10 @@
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.admin.cli.utils.IOUtils;
-import org.apache.pulsar.cli.converters.ByteUnitIntegerConverter;
-import org.apache.pulsar.cli.converters.ByteUnitToLongConverter;
-import org.apache.pulsar.cli.converters.TimeUnitToMillisConverter;
-import org.apache.pulsar.cli.converters.TimeUnitToSecondsConverter;
-import org.apache.pulsar.cli.validators.IntegerMaxValueLongValidator;
-import org.apache.pulsar.cli.validators.MinNegativeOneValidator;
-import org.apache.pulsar.cli.validators.NonNegativeValueValidator;
-import org.apache.pulsar.cli.validators.PositiveIntegerValueValidator;
-import org.apache.pulsar.cli.validators.PositiveLongValueValidator;
+import org.apache.pulsar.cli.converters.picocli.ByteUnitToIntegerConverter;
+import org.apache.pulsar.cli.converters.picocli.ByteUnitToLongConverter;
+import org.apache.pulsar.cli.converters.picocli.TimeUnitToMillisConverter;
+import org.apache.pulsar.cli.converters.picocli.TimeUnitToSecondsConverter;
import org.apache.pulsar.client.admin.ListNamespaceTopicsOptions;
import org.apache.pulsar.client.admin.Mode;
import org.apache.pulsar.client.admin.PulsarAdmin;
@@ -74,25 +65,27 @@
import org.apache.pulsar.common.policies.data.SubscribeRate;
import org.apache.pulsar.common.policies.data.SubscriptionAuthMode;
import org.apache.pulsar.common.policies.data.TopicType;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations about namespaces")
+@Command(description = "Operations about namespaces")
public class CmdNamespaces extends CmdBase {
- @Parameters(commandDescription = "Get the namespaces for a tenant")
+ @Command(description = "Get the namespaces for a tenant")
private class GetNamespacesPerProperty extends CliCommand {
- @Parameter(description = "tenant-name", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant-name", arity = "1")
+ private String tenant;
@Override
void run() throws PulsarAdminException {
- String tenant = getOneArgument(params);
print(getAdmin().namespaces().getNamespaces(tenant));
}
}
- @Parameters(commandDescription = "Get the namespaces for a tenant in a cluster", hidden = true)
+ @Command(description = "Get the namespaces for a tenant in a cluster", hidden = true)
private class GetNamespacesPerCluster extends CliCommand {
- @Parameter(description = "tenant/cluster", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/cluster", arity = "1")
+ private String params;
@Override
void run() throws PulsarAdminException {
@@ -101,22 +94,22 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the list of topics for a namespace")
+ @Command(description = "Get the list of topics for a namespace")
private class GetTopics extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"-m", "--mode"},
+ @Option(names = {"-m", "--mode"},
description = "Allowed topic domain mode (persistent, non_persistent, all).")
private Mode mode;
- @Parameter(names = { "-ist",
+ @Option(names = { "-ist",
"--include-system-topic" }, description = "Include system topic")
private boolean includeSystemTopic;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
ListNamespaceTopicsOptions options = ListNamespaceTopicsOptions.builder()
.mode(mode)
.includeSystemTopic(includeSystemTopic)
@@ -125,59 +118,59 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the list of bundles for a namespace")
+ @Command(description = "Get the list of bundles for a namespace")
private class GetBundles extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getBundles(namespace));
}
}
- @Parameters(commandDescription = "Get the list of destinations for a namespace", hidden = true)
+ @Command(description = "Get the list of destinations for a namespace", hidden = true)
private class GetDestinations extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getTopics(namespace));
}
}
- @Parameters(commandDescription = "Get the configuration policies of a namespace")
+ @Command(description = "Get the configuration policies of a namespace")
private class GetPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getPolicies(namespace));
}
}
- @Parameters(commandDescription = "Creates a new namespace")
+ @Command(description = "Creates a new namespace")
private class Create extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--clusters", "-c" },
- description = "List of clusters this namespace will be assigned", required = false)
+ @Option(names = { "--clusters", "-c" },
+ description = "List of clusters this namespace will be assigned", required = false, split = ",")
private java.util.List clusters;
- @Parameter(names = { "--bundles", "-b" }, description = "number of bundles to activate", required = false)
+ @Option(names = { "--bundles", "-b" }, description = "number of bundles to activate", required = false)
private int numBundles = 0;
private static final long MAX_BUNDLES = ((long) 1) << 32;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (numBundles < 0 || numBundles > MAX_BUNDLES) {
throw new ParameterException(
"Invalid number of bundles. Number of bundles has to be in the range of (0, 2^32].");
@@ -208,162 +201,162 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Deletes a namespace.")
+ @Command(description = "Deletes a namespace.")
private class Delete extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-f",
+ @Option(names = { "-f",
"--force" }, description = "Delete namespace forcefully by force deleting all topics under it")
private boolean force = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().deleteNamespace(namespace, force);
}
}
- @Parameters(commandDescription = "Grant permissions on a namespace")
+ @Command(description = "Grant permissions on a namespace")
private class GrantPermissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = "--role", description = "Client role to which grant permissions", required = true)
+ @Option(names = "--role", description = "Client role to which grant permissions", required = true)
private String role;
- @Parameter(names = "--actions", description = "Actions to be granted (produce,consume,sources,sinks,"
- + "functions,packages)", required = true)
+ @Option(names = "--actions", description = "Actions to be granted (produce,consume,sources,sinks,"
+ + "functions,packages)", required = true, split = ",")
private List actions;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().grantPermissionOnNamespace(namespace, role, getAuthActions(actions));
}
}
- @Parameters(commandDescription = "Revoke permissions on a namespace")
+ @Command(description = "Revoke permissions on a namespace")
private class RevokePermissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = "--role", description = "Client role to which revoke permissions", required = true)
+ @Option(names = "--role", description = "Client role to which revoke permissions", required = true)
private String role;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().revokePermissionsOnNamespace(namespace, role);
}
}
- @Parameters(commandDescription = "Get permissions to access subscription admin-api")
+ @Command(description = "Get permissions to access subscription admin-api")
private class SubscriptionPermissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getPermissionOnSubscription(namespace));
}
}
- @Parameters(commandDescription = "Grant permissions to access subscription admin-api")
+ @Command(description = "Grant permissions to access subscription admin-api")
private class GrantSubscriptionPermissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"-s", "--subscription"},
+ @Option(names = {"-s", "--subscription"},
description = "Subscription name for which permission will be granted to roles", required = true)
private String subscription;
- @Parameter(names = {"-rs", "--roles"},
+ @Option(names = {"-rs", "--roles"},
description = "Client roles to which grant permissions (comma separated roles)",
- required = true, splitter = CommaParameterSplitter.class)
+ required = true, split = ",")
private List roles;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().grantPermissionOnSubscription(namespace, subscription, Sets.newHashSet(roles));
}
}
- @Parameters(commandDescription = "Revoke permissions to access subscription admin-api")
+ @Command(description = "Revoke permissions to access subscription admin-api")
private class RevokeSubscriptionPermissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"-s", "--subscription"}, description = "Subscription name for which permission "
+ @Option(names = {"-s", "--subscription"}, description = "Subscription name for which permission "
+ "will be revoked to roles", required = true)
private String subscription;
- @Parameter(names = {"-r", "--role"},
+ @Option(names = {"-r", "--role"},
description = "Client role to which revoke permissions", required = true)
private String role;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().revokePermissionOnSubscription(namespace, subscription, role);
}
}
- @Parameters(commandDescription = "Get the permissions on a namespace")
+ @Command(description = "Get the permissions on a namespace")
private class Permissions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getPermissions(namespace));
}
}
- @Parameters(commandDescription = "Set replication clusters for a namespace")
+ @Command(description = "Set replication clusters for a namespace")
private class SetReplicationClusters extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--clusters",
+ @Option(names = { "--clusters",
"-c" }, description = "Replication Cluster Ids list (comma separated values)", required = true)
private String clusterIds;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
List clusters = Lists.newArrayList(clusterIds.split(","));
getAdmin().namespaces().setNamespaceReplicationClusters(namespace, Sets.newHashSet(clusters));
}
}
- @Parameters(commandDescription = "Get replication clusters for a namespace")
+ @Command(description = "Get replication clusters for a namespace")
private class GetReplicationClusters extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getNamespaceReplicationClusters(namespace));
}
}
- @Parameters(commandDescription = "Set subscription types enabled for a namespace")
+ @Command(description = "Set subscription types enabled for a namespace")
private class SetSubscriptionTypesEnabled extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--types", "-t"}, description = "Subscription types enabled list (comma separated values)."
- + " Possible values: (Exclusive, Shared, Failover, Key_Shared).", required = true)
+ @Option(names = {"--types", "-t"}, description = "Subscription types enabled list (comma separated values)."
+ + " Possible values: (Exclusive, Shared, Failover, Key_Shared).", required = true, split = ",")
private List subTypes;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
Set types = new HashSet<>();
subTypes.forEach(s -> {
SubscriptionType subType;
@@ -379,167 +372,166 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get subscription types enabled for a namespace")
+ @Command(description = "Get subscription types enabled for a namespace")
private class GetSubscriptionTypesEnabled extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getSubscriptionTypesEnabled(namespace));
}
}
- @Parameters(commandDescription = "Remove subscription types enabled for a namespace")
+ @Command(description = "Remove subscription types enabled for a namespace")
private class RemoveSubscriptionTypesEnabled extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeSubscriptionTypesEnabled(namespace);
}
}
- @Parameters(commandDescription = "Set Message TTL for a namespace")
+ @Command(description = "Set Message TTL for a namespace")
private class SetMessageTTL extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--messageTTL", "-ttl" },
+ @Option(names = {"--messageTTL", "-ttl"},
description = "Message TTL in seconds (or minutes, hours, days, weeks eg: 100m, 3h, 2d, 5w). "
+ "When the value is set to `0`, TTL is disabled.", required = true,
- converter = TimeUnitToSecondsConverter.class,
- validateValueWith = {NonNegativeValueValidator.class})
+ converter = TimeUnitToSecondsConverter.class)
private Long messageTTLInSecond;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setNamespaceMessageTTL(namespace, messageTTLInSecond.intValue());
}
}
- @Parameters(commandDescription = "Remove Message TTL for a namespace")
+ @Command(description = "Remove Message TTL for a namespace")
private class RemoveMessageTTL extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeNamespaceMessageTTL(namespace);
}
}
- @Parameters(commandDescription = "Get max subscriptions per topic for a namespace")
+ @Command(description = "Get max subscriptions per topic for a namespace")
private class GetMaxSubscriptionsPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxSubscriptionsPerTopic(namespace));
}
}
- @Parameters(commandDescription = "Set max subscriptions per topic for a namespace")
+ @Command(description = "Set max subscriptions per topic for a namespace")
private class SetMaxSubscriptionsPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-subscriptions-per-topic", "-m" }, description = "Max subscriptions per topic",
+ @Option(names = { "--max-subscriptions-per-topic", "-m" }, description = "Max subscriptions per topic",
required = true)
private int maxSubscriptionsPerTopic;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxSubscriptionsPerTopic(namespace, maxSubscriptionsPerTopic);
}
}
- @Parameters(commandDescription = "Remove max subscriptions per topic for a namespace")
+ @Command(description = "Remove max subscriptions per topic for a namespace")
private class RemoveMaxSubscriptionsPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxSubscriptionsPerTopic(namespace);
}
}
- @Parameters(commandDescription = "Set subscription expiration time for a namespace")
+ @Command(description = "Set subscription expiration time for a namespace")
private class SetSubscriptionExpirationTime extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-t", "--time" }, description = "Subscription expiration time in minutes", required = true)
+ @Option(names = { "-t", "--time" }, description = "Subscription expiration time in minutes", required = true)
private int expirationTime;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setSubscriptionExpirationTime(namespace, expirationTime);
}
}
- @Parameters(commandDescription = "Remove subscription expiration time for a namespace")
+ @Command(description = "Remove subscription expiration time for a namespace")
private class RemoveSubscriptionExpirationTime extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeSubscriptionExpirationTime(namespace);
}
}
- @Parameters(commandDescription = "Set Anti-affinity group name for a namespace")
+ @Command(description = "Set Anti-affinity group name for a namespace")
private class SetAntiAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--group", "-g" }, description = "Anti-affinity group name", required = true)
+ @Option(names = { "--group", "-g" }, description = "Anti-affinity group name", required = true)
private String antiAffinityGroup;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setNamespaceAntiAffinityGroup(namespace, antiAffinityGroup);
}
}
- @Parameters(commandDescription = "Get Anti-affinity group name for a namespace")
+ @Command(description = "Get Anti-affinity group name for a namespace")
private class GetAntiAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getNamespaceAntiAffinityGroup(namespace));
}
}
- @Parameters(commandDescription = "Get Anti-affinity namespaces grouped with the given anti-affinity group name")
+ @Command(description = "Get Anti-affinity namespaces grouped with the given anti-affinity group name")
private class GetAntiAffinityNamespaces extends CliCommand {
- @Parameter(names = { "--tenant",
+ @Option(names = { "--tenant",
"-p" }, description = "tenant is only used for authorization. "
+ "Client has to be admin of any of the tenant to access this api", required = false)
private String tenant;
- @Parameter(names = { "--cluster", "-c" }, description = "Cluster name", required = true)
+ @Option(names = { "--cluster", "-c" }, description = "Cluster name", required = true)
private String cluster;
- @Parameter(names = { "--group", "-g" }, description = "Anti-affinity group name", required = true)
+ @Option(names = { "--group", "-g" }, description = "Anti-affinity group name", required = true)
private String antiAffinityGroup;
@Override
@@ -548,56 +540,56 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Remove Anti-affinity group name for a namespace")
+ @Command(description = "Remove Anti-affinity group name for a namespace")
private class DeleteAntiAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().deleteNamespaceAntiAffinityGroup(namespace);
}
}
- @Parameters(commandDescription = "Get Deduplication for a namespace")
+ @Command(description = "Get Deduplication for a namespace")
private class GetDeduplication extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getDeduplicationStatus(namespace));
}
}
- @Parameters(commandDescription = "Remove Deduplication for a namespace")
+ @Command(description = "Remove Deduplication for a namespace")
private class RemoveDeduplication extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeDeduplicationStatus(namespace);
}
}
- @Parameters(commandDescription = "Enable or disable deduplication for a namespace")
+ @Command(description = "Enable or disable deduplication for a namespace")
private class SetDeduplication extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable deduplication")
+ @Option(names = { "--enable", "-e" }, description = "Enable deduplication")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable deduplication")
+ @Option(names = { "--disable", "-d" }, description = "Disable deduplication")
private boolean disable = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enable == disable) {
throw new ParameterException("Need to specify either --enable or --disable");
@@ -606,28 +598,28 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Enable or disable autoTopicCreation for a namespace, overriding broker settings")
+ @Command(description = "Enable or disable autoTopicCreation for a namespace, overriding broker settings")
private class SetAutoTopicCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable allowAutoTopicCreation on namespace")
+ @Option(names = { "--enable", "-e" }, description = "Enable allowAutoTopicCreation on namespace")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable allowAutoTopicCreation on namespace")
+ @Option(names = { "--disable", "-d" }, description = "Disable allowAutoTopicCreation on namespace")
private boolean disable = false;
- @Parameter(names = { "--type", "-t" }, description = "Type of topic to be auto-created. "
+ @Option(names = { "--type", "-t" }, description = "Type of topic to be auto-created. "
+ "Possible values: (partitioned, non-partitioned). Default value: non-partitioned")
private String type = "non-partitioned";
- @Parameter(names = { "--num-partitions", "-n" }, description = "Default number of partitions of topic to "
+ @Option(names = { "--num-partitions", "-n" }, description = "Default number of partitions of topic to "
+ "be auto-created, applicable to partitioned topics only", required = false)
private Integer defaultNumPartitions = null;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
type = type.toLowerCase().trim();
if (enable == disable) {
@@ -654,42 +646,42 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get autoTopicCreation info for a namespace")
+ @Command(description = "Get autoTopicCreation info for a namespace")
private class GetAutoTopicCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getAutoTopicCreation(namespace));
}
}
- @Parameters(commandDescription = "Remove override of autoTopicCreation for a namespace")
+ @Command(description = "Remove override of autoTopicCreation for a namespace")
private class RemoveAutoTopicCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeAutoTopicCreation(namespace);
}
}
- @Parameters(commandDescription = "Enable autoSubscriptionCreation for a namespace, overriding broker settings")
+ @Command(description = "Enable autoSubscriptionCreation for a namespace, overriding broker settings")
private class SetAutoSubscriptionCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable allowAutoSubscriptionCreation on namespace")
+ @Option(names = {"--enable", "-e"}, description = "Enable allowAutoSubscriptionCreation on namespace")
private boolean enable = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setAutoSubscriptionCreation(namespace,
AutoSubscriptionCreationOverride.builder()
.allowAutoSubscriptionCreation(enable)
@@ -697,58 +689,57 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the autoSubscriptionCreation for a namespace")
+ @Command(description = "Get the autoSubscriptionCreation for a namespace")
private class GetAutoSubscriptionCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getAutoSubscriptionCreation(namespace));
}
}
- @Parameters(commandDescription = "Remove override of autoSubscriptionCreation for a namespace")
+ @Command(description = "Remove override of autoSubscriptionCreation for a namespace")
private class RemoveAutoSubscriptionCreation extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeAutoSubscriptionCreation(namespace);
}
}
- @Parameters(commandDescription = "Remove the retention policy for a namespace")
+ @Command(description = "Remove the retention policy for a namespace")
private class RemoveRetention extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeRetention(namespace);
}
}
- @Parameters(commandDescription = "Set the retention policy for a namespace")
+ @Command(description = "Set the retention policy for a namespace")
private class SetRetention extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--time",
+ @Option(names = { "--time",
"-t" }, description = "Retention time with optional time unit suffix. "
+ "For example, 100m, 3h, 2d, 5w. "
+ "If the time unit is not specified, the default unit is seconds. For example, "
+ "-t 120 sets retention to 2 minutes. "
+ "0 means no retention and -1 means infinite time retention.", required = true,
- converter = TimeUnitToSecondsConverter.class,
- validateValueWith = MinNegativeOneValidator.class)
+ converter = TimeUnitToSecondsConverter.class)
private Long retentionTimeInSec;
- @Parameter(names = { "--size", "-s" }, description = "Retention size limit with optional size unit suffix. "
+ @Option(names = { "--size", "-s" }, description = "Retention size limit with optional size unit suffix. "
+ "For example, 4096, 10M, 16G, 3T. The size unit suffix character can be k/K, m/M, g/G, or t/T. "
+ "If the size unit suffix is not specified, the default unit is bytes. "
+ "0 or less than 1MB means no retention and -1 means infinite size retention", required = true,
@@ -757,7 +748,7 @@ private class SetRetention extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
final int retentionTimeInMin = retentionTimeInSec != -1
? (int) TimeUnit.SECONDS.toMinutes(retentionTimeInSec)
: retentionTimeInSec.intValue();
@@ -769,28 +760,28 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the retention policy for a namespace")
+ @Command(description = "Get the retention policy for a namespace")
private class GetRetention extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getRetention(namespace));
}
}
- @Parameters(commandDescription = "Set the bookie-affinity group name")
+ @Command(description = "Set the bookie-affinity group name")
private class SetBookieAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--primary-group",
+ @Option(names = { "--primary-group",
"-pg" }, description = "Bookie-affinity primary-groups (comma separated) name "
+ "where namespace messages should be written", required = true)
private String bookieAffinityGroupNamePrimary;
- @Parameter(names = { "--secondary-group",
+ @Option(names = { "--secondary-group",
"-sg" }, description = "Bookie-affinity secondary-group (comma separated) name where namespace "
+ "messages should be written. If you want to verify whether there are enough bookies in groups, "
+ "use `--secondary-group` flag. Messages in this namespace are stored in secondary groups. "
@@ -800,7 +791,7 @@ private class SetBookieAffinityGroup extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setBookieAffinityGroup(namespace,
BookieAffinityGroupData.builder()
.bookkeeperAffinityGroupPrimary(bookieAffinityGroupNamePrimary)
@@ -809,70 +800,70 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set the bookie-affinity group name")
+ @Command(description = "Set the bookie-affinity group name")
private class DeleteBookieAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().deleteBookieAffinityGroup(namespace);
}
}
- @Parameters(commandDescription = "Get the bookie-affinity group name")
+ @Command(description = "Get the bookie-affinity group name")
private class GetBookieAffinityGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getBookieAffinityGroup(namespace));
}
}
- @Parameters(commandDescription = "Get message TTL for a namespace")
+ @Command(description = "Get message TTL for a namespace")
private class GetMessageTTL extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getNamespaceMessageTTL(namespace));
}
}
- @Parameters(commandDescription = "Get subscription expiration time for a namespace")
+ @Command(description = "Get subscription expiration time for a namespace")
private class GetSubscriptionExpirationTime extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getSubscriptionExpirationTime(namespace));
}
}
- @Parameters(commandDescription = "Unload a namespace from the current serving broker")
+ @Command(description = "Unload a namespace from the current serving broker")
private class Unload extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
+ @Option(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
private String bundle;
- @Parameter(names = { "--destinationBroker", "-d" },
+ @Option(names = { "--destinationBroker", "-d" },
description = "Target brokerWebServiceAddress to which the bundle has to be allocated to. "
+ "--destinationBroker cannot be set when --bundle is not specified.")
private String destinationBroker;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (bundle == null) {
@@ -886,38 +877,38 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Split a namespace-bundle from the current serving broker")
+ @Command(description = "Split a namespace-bundle from the current serving broker")
private class SplitBundle extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--bundle",
+ @Option(names = { "--bundle",
"-b" }, description = "{start-boundary}_{end-boundary} "
+ "(mutually exclusive with --bundle-type)", required = false)
private String bundle;
- @Parameter(names = { "--bundle-type",
+ @Option(names = { "--bundle-type",
"-bt" }, description = "bundle type (mutually exclusive with --bundle)", required = false)
private BundleType bundleType;
- @Parameter(names = { "--unload",
+ @Option(names = { "--unload",
"-u" }, description = "Unload newly split bundles after splitting old bundle", required = false)
private boolean unload;
- @Parameter(names = { "--split-algorithm-name", "-san" }, description = "Algorithm name for split "
+ @Option(names = { "--split-algorithm-name", "-san" }, description = "Algorithm name for split "
+ "namespace bundle. Valid options are: [range_equally_divide, topic_count_equally_divide, "
+ "specified_positions_divide, flow_or_qps_equally_divide]. Use broker side config if absent"
, required = false)
private String splitAlgorithmName;
- @Parameter(names = { "--split-boundaries",
+ @Option(names = { "--split-boundaries",
"-sb" }, description = "Specified split boundary for bundle split, will split one bundle "
+ "to multi bundles only works with specified_positions_divide algorithm", required = false)
private List splitBoundaries;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (StringUtils.isBlank(bundle) && bundleType == null) {
throw new ParameterException("Must pass one of the params: --bundle / --bundle-type");
}
@@ -935,18 +926,18 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the positions for one or more topic(s) in a namespace bundle")
+ @Command(description = "Get the positions for one or more topic(s) in a namespace bundle")
private class GetTopicHashPositions extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(
+ @Option(
names = { "--bundle", "-b" },
description = "{start-boundary}_{end-boundary} format namespace bundle",
required = false)
private String bundle;
- @Parameter(
+ @Option(
names = { "--topic-list", "-tl" },
description = "The list of topics(both non-partitioned topic and partitioned topic) to get positions "
+ "in this bundle, if none topic provided, will get the positions of all topics in this bundle",
@@ -955,7 +946,7 @@ private class GetTopicHashPositions extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (StringUtils.isBlank(bundle)) {
throw new ParameterException("Must pass one of the params: --bundle ");
}
@@ -963,34 +954,34 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set message-dispatch-rate for all topics of the namespace")
+ @Command(description = "Set message-dispatch-rate for all topics of the namespace")
private class SetDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--msg-dispatch-rate",
+ @Option(names = { "--msg-dispatch-rate",
"-md" }, description = "message-dispatch-rate "
+ "(default -1 will be overwrite if not passed)", required = false)
private int msgDispatchRate = -1;
- @Parameter(names = { "--byte-dispatch-rate",
+ @Option(names = { "--byte-dispatch-rate",
"-bd" }, description = "byte-dispatch-rate "
+ "(default -1 will be overwrite if not passed)", required = false)
private long byteDispatchRate = -1;
- @Parameter(names = { "--dispatch-rate-period",
+ @Option(names = { "--dispatch-rate-period",
"-dt" }, description = "dispatch-rate-period in second type "
+ "(default 1 second will be overwrite if not passed)", required = false)
private int dispatchRatePeriodSec = 1;
- @Parameter(names = { "--relative-to-publish-rate",
+ @Option(names = { "--relative-to-publish-rate",
"-rp" }, description = "dispatch rate relative to publish-rate (if publish-relative flag is enabled "
+ "then broker will apply throttling value to (publish-rate + dispatch rate))", required = false)
private boolean relativeToPublishRate = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setDispatchRate(namespace,
DispatchRate.builder()
.dispatchThrottlingRateInMsg(msgDispatchRate)
@@ -1001,106 +992,106 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Remove configured message-dispatch-rate for all topics of the namespace")
+ @Command(description = "Remove configured message-dispatch-rate for all topics of the namespace")
private class RemoveDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeDispatchRate(namespace);
}
}
- @Parameters(commandDescription = "Get configured message-dispatch-rate for all topics of the namespace "
+ @Command(description = "Get configured message-dispatch-rate for all topics of the namespace "
+ "(Disabled if value < 0)")
private class GetDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getDispatchRate(namespace));
}
}
- @Parameters(commandDescription = "Set subscribe-rate per consumer for all topics of the namespace")
+ @Command(description = "Set subscribe-rate per consumer for all topics of the namespace")
private class SetSubscribeRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--subscribe-rate",
+ @Option(names = { "--subscribe-rate",
"-sr" }, description = "subscribe-rate (default -1 will be overwrite if not passed)", required = false)
private int subscribeRate = -1;
- @Parameter(names = { "--subscribe-rate-period",
+ @Option(names = { "--subscribe-rate-period",
"-st" }, description = "subscribe-rate-period in second type "
+ "(default 30 second will be overwrite if not passed)", required = false)
private int subscribeRatePeriodSec = 30;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setSubscribeRate(namespace,
new SubscribeRate(subscribeRate, subscribeRatePeriodSec));
}
}
- @Parameters(commandDescription = "Get configured subscribe-rate per consumer for all topics of the namespace")
+ @Command(description = "Get configured subscribe-rate per consumer for all topics of the namespace")
private class GetSubscribeRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getSubscribeRate(namespace));
}
}
- @Parameters(commandDescription = "Remove configured subscribe-rate per consumer for all topics of the namespace")
+ @Command(description = "Remove configured subscribe-rate per consumer for all topics of the namespace")
private class RemoveSubscribeRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeSubscribeRate(namespace);
}
}
- @Parameters(commandDescription = "Set subscription message-dispatch-rate for all subscription of the namespace")
+ @Command(description = "Set subscription message-dispatch-rate for all subscription of the namespace")
private class SetSubscriptionDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--msg-dispatch-rate",
+ @Option(names = { "--msg-dispatch-rate",
"-md" }, description = "message-dispatch-rate "
+ "(default -1 will be overwrite if not passed)", required = false)
private int msgDispatchRate = -1;
- @Parameter(names = { "--byte-dispatch-rate",
+ @Option(names = { "--byte-dispatch-rate",
"-bd" }, description = "byte-dispatch-rate (default -1 will be overwrite if not passed)", required = false)
private long byteDispatchRate = -1;
- @Parameter(names = { "--dispatch-rate-period",
+ @Option(names = { "--dispatch-rate-period",
"-dt" }, description = "dispatch-rate-period in second type "
+ "(default 1 second will be overwrite if not passed)", required = false)
private int dispatchRatePeriodSec = 1;
- @Parameter(names = { "--relative-to-publish-rate",
+ @Option(names = { "--relative-to-publish-rate",
"-rp" }, description = "dispatch rate relative to publish-rate (if publish-relative flag is enabled "
+ "then broker will apply throttling value to (publish-rate + dispatch rate))", required = false)
private boolean relativeToPublishRate = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setSubscriptionDispatchRate(namespace,
DispatchRate.builder()
.dispatchThrottlingRateInMsg(msgDispatchRate)
@@ -1111,100 +1102,100 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Remove subscription configured message-dispatch-rate "
+ @Command(description = "Remove subscription configured message-dispatch-rate "
+ "for all topics of the namespace")
private class RemoveSubscriptionDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeSubscriptionDispatchRate(namespace);
}
}
- @Parameters(commandDescription = "Get subscription configured message-dispatch-rate for all topics of "
+ @Command(description = "Get subscription configured message-dispatch-rate for all topics of "
+ "the namespace (Disabled if value < 0)")
private class GetSubscriptionDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getSubscriptionDispatchRate(namespace));
}
}
- @Parameters(commandDescription = "Set publish-rate for all topics of the namespace")
+ @Command(description = "Set publish-rate for all topics of the namespace")
private class SetPublishRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--msg-publish-rate",
+ @Option(names = { "--msg-publish-rate",
"-m" }, description = "message-publish-rate (default -1 will be overwrite if not passed)", required = false)
private int msgPublishRate = -1;
- @Parameter(names = { "--byte-publish-rate",
+ @Option(names = { "--byte-publish-rate",
"-b" }, description = "byte-publish-rate (default -1 will be overwrite if not passed)", required = false)
private long bytePublishRate = -1;
- @Override
+ @Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setPublishRate(namespace,
new PublishRate(msgPublishRate, bytePublishRate));
}
}
- @Parameters(commandDescription = "Remove publish-rate for all topics of the namespace")
+ @Command(description = "Remove publish-rate for all topics of the namespace")
private class RemovePublishRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removePublishRate(namespace);
}
}
- @Parameters(commandDescription = "Get configured message-publish-rate for all topics of the namespace "
- + "(Disabled if value < 0)")
+ @Command(name = "get-publish-rate",
+ description = "Get configured message-publish-rate for all topics of the namespace (Disabled if value < 0)")
private class GetPublishRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Override
+ @Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getPublishRate(namespace));
}
}
- @Parameters(commandDescription = "Set replicator message-dispatch-rate for all topics of the namespace")
+ @Command(description = "Set replicator message-dispatch-rate for all topics of the namespace")
private class SetReplicatorDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--msg-dispatch-rate",
+ @Option(names = { "--msg-dispatch-rate",
"-md" }, description = "message-dispatch-rate "
+ "(default -1 will be overwrite if not passed)", required = false)
private int msgDispatchRate = -1;
- @Parameter(names = { "--byte-dispatch-rate",
+ @Option(names = { "--byte-dispatch-rate",
"-bd" }, description = "byte-dispatch-rate (default -1 will be overwrite if not passed)", required = false)
private long byteDispatchRate = -1;
- @Parameter(names = { "--dispatch-rate-period",
+ @Option(names = { "--dispatch-rate-period",
"-dt" }, description = "dispatch-rate-period in second type "
+ "(default 1 second will be overwrite if not passed)", required = false)
private int dispatchRatePeriodSec = 1;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setReplicatorDispatchRate(namespace,
DispatchRate.builder()
.dispatchThrottlingRateInMsg(msgDispatchRate)
@@ -1214,65 +1205,65 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get replicator configured message-dispatch-rate for all topics of the namespace "
+ @Command(description = "Get replicator configured message-dispatch-rate for all topics of the namespace "
+ "(Disabled if value < 0)")
private class GetReplicatorDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getReplicatorDispatchRate(namespace));
}
}
- @Parameters(commandDescription = "Remove replicator configured message-dispatch-rate "
+ @Command(description = "Remove replicator configured message-dispatch-rate "
+ "for all topics of the namespace")
private class RemoveReplicatorDispatchRate extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeReplicatorDispatchRate(namespace);
}
}
- @Parameters(commandDescription = "Get the backlog quota policies for a namespace")
+ @Command(description = "Get the backlog quota policies for a namespace")
private class GetBacklogQuotaMap extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getBacklogQuotaMap(namespace));
}
}
- @Parameters(commandDescription = "Set a backlog quota policy for a namespace")
+ @Command(description = "Set a backlog quota policy for a namespace")
private class SetBacklogQuota extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-l", "--limit" }, description = "Size limit (eg: 10M, 16G)",
+ @Option(names = { "-l", "--limit" }, description = "Size limit (eg: 10M, 16G)",
converter = ByteUnitToLongConverter.class)
- private Long limit = 0L;
+ private Long limit;
- @Parameter(names = { "-lt", "--limitTime" },
+ @Option(names = { "-lt", "--limitTime" },
description = "Time limit in second (or minutes, hours, days, weeks eg: 100m, 3h, 2d, 5w), "
+ "non-positive number for disabling time limit.",
converter = TimeUnitToSecondsConverter.class)
private Long limitTimeInSec;
- @Parameter(names = { "-p", "--policy" }, description = "Retention policy to enforce when the limit is reached. "
+ @Option(names = { "-p", "--policy" }, description = "Retention policy to enforce when the limit is reached. "
+ "Valid options are: [producer_request_hold, producer_exception, consumer_backlog_eviction]",
required = true)
private String policyStr;
- @Parameter(names = {"-t", "--type"}, description = "Backlog quota type to set. Valid options are: "
+ @Option(names = {"-t", "--type"}, description = "Backlog quota type to set. Valid options are: "
+ "destination_storage (default) and message_age. "
+ "destination_storage limits backlog by size. "
+ "message_age limits backlog by time, that is, message timestamp (broker or publish timestamp). "
@@ -1298,7 +1289,7 @@ void run() throws PulsarAdminException {
backlogQuotaTypeStr, Arrays.toString(BacklogQuota.BacklogQuotaType.values())));
}
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
BacklogQuota.Builder builder = BacklogQuota.builder().retentionPolicy(policy);
if (backlogQuotaType == BacklogQuota.BacklogQuotaType.destination_storage) {
@@ -1318,18 +1309,18 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Remove a backlog quota policy from a namespace")
+ @Command(description = "Remove a backlog quota policy from a namespace")
private class RemoveBacklogQuota extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"-t", "--type"}, description = "Backlog quota type to remove. Valid options are: "
+ @Option(names = {"-t", "--type"}, description = "Backlog quota type to remove. Valid options are: "
+ "destination_storage, message_age")
private String backlogQuotaTypeStr = BacklogQuota.BacklogQuotaType.destination_storage.name();
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
BacklogQuota.BacklogQuotaType backlogQuotaType;
try {
backlogQuotaType = BacklogQuota.BacklogQuotaType.valueOf(backlogQuotaTypeStr);
@@ -1341,56 +1332,56 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the persistence policies for a namespace")
+ @Command(description = "Get the persistence policies for a namespace")
private class GetPersistence extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getPersistence(namespace));
}
}
- @Parameters(commandDescription = "Remove the persistence policies for a namespace")
+ @Command(description = "Remove the persistence policies for a namespace")
private class RemovePersistence extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removePersistence(namespace);
}
}
- @Parameters(commandDescription = "Set the persistence policies for a namespace")
+ @Command(description = "Set the persistence policies for a namespace")
private class SetPersistence extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-e",
+ @Option(names = { "-e",
"--bookkeeper-ensemble" }, description = "Number of bookies to use for a topic")
private int bookkeeperEnsemble = 2;
- @Parameter(names = { "-w",
+ @Option(names = { "-w",
"--bookkeeper-write-quorum" }, description = "How many writes to make of each entry")
private int bookkeeperWriteQuorum = 2;
- @Parameter(names = { "-a",
+ @Option(names = { "-a",
"--bookkeeper-ack-quorum" },
description = "Number of acks (guaranteed copies) to wait for each entry")
private int bookkeeperAckQuorum = 2;
- @Parameter(names = { "-r",
+ @Option(names = { "-r",
"--ml-mark-delete-max-rate" },
description = "Throttling rate of mark-delete operation (0 means no throttle)")
private double managedLedgerMaxMarkDeleteRate = 0;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (bookkeeperEnsemble <= 0 || bookkeeperWriteQuorum <= 0 || bookkeeperAckQuorum <= 0) {
throw new ParameterException("[--bookkeeper-ensemble], [--bookkeeper-write-quorum] "
+ "and [--bookkeeper-ack-quorum] must greater than 0.");
@@ -1403,18 +1394,18 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Clear backlog for a namespace")
+ @Command(description = "Clear backlog for a namespace")
private class ClearBacklog extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--sub", "-s" }, description = "subscription name")
+ @Option(names = { "--sub", "-s" }, description = "subscription name")
private String subscription;
- @Parameter(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
+ @Option(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
private String bundle;
- @Parameter(names = { "--force", "-force" }, description = "Whether to force clear backlog without prompt")
+ @Option(names = { "--force", "-force" }, description = "Whether to force clear backlog without prompt")
private boolean force;
@Override
@@ -1426,7 +1417,7 @@ void run() throws PulsarAdminException, IOException {
return;
}
}
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (subscription != null && bundle != null) {
getAdmin().namespaces().clearNamespaceBundleBacklogForSubscription(namespace, bundle, subscription);
} else if (subscription != null) {
@@ -1439,20 +1430,20 @@ void run() throws PulsarAdminException, IOException {
}
}
- @Parameters(commandDescription = "Unsubscribe the given subscription on all topics on a namespace")
+ @Command(description = "Unsubscribe the given subscription on all topics on a namespace")
private class Unsubscribe extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--sub", "-s" }, description = "subscription name", required = true)
+ @Option(names = { "--sub", "-s" }, description = "subscription name", required = true)
private String subscription;
- @Parameter(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
+ @Option(names = { "--bundle", "-b" }, description = "{start-boundary}_{end-boundary}")
private String bundle;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (bundle != null) {
getAdmin().namespaces().unsubscribeNamespaceBundle(namespace, bundle, subscription);
} else {
@@ -1462,20 +1453,20 @@ void run() throws Exception {
}
- @Parameters(commandDescription = "Enable or disable message encryption required for a namespace")
+ @Command(description = "Enable or disable message encryption required for a namespace")
private class SetEncryptionRequired extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable message encryption required")
+ @Option(names = { "--enable", "-e" }, description = "Enable message encryption required")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable message encryption required")
+ @Option(names = { "--disable", "-d" }, description = "Disable message encryption required")
private boolean disable = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enable == disable) {
throw new ParameterException("Need to specify either --enable or --disable");
@@ -1484,91 +1475,90 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get encryption required for a namespace")
+ @Command(description = "Get encryption required for a namespace")
private class GetEncryptionRequired extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getEncryptionRequiredStatus(namespace));
}
}
- @Parameters(commandDescription = "Get the delayed delivery policy for a namespace")
+ @Command(description = "Get the delayed delivery policy for a namespace")
private class GetDelayedDelivery extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getDelayedDelivery(namespace));
}
}
- @Parameters(commandDescription = "Remove delayed delivery policies from a namespace")
+ @Command(description = "Remove delayed delivery policies from a namespace")
private class RemoveDelayedDelivery extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeDelayedDeliveryMessages(namespace);
}
}
- @Parameters(commandDescription = "Get the inactive topic policy for a namespace")
+ @Command(description = "Get the inactive topic policy for a namespace")
private class GetInactiveTopicPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getInactiveTopicPolicies(namespace));
}
}
- @Parameters(commandDescription = "Remove inactive topic policies from a namespace")
+ @Command(description = "Remove inactive topic policies from a namespace")
private class RemoveInactiveTopicPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeInactiveTopicPolicies(namespace);
}
}
- @Parameters(commandDescription = "Set the inactive topic policies on a namespace")
+ @Command(description = "Set the inactive topic policies on a namespace")
private class SetInactiveTopicPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable-delete-while-inactive", "-e" }, description = "Enable delete while inactive")
+ @Option(names = { "--enable-delete-while-inactive", "-e" }, description = "Enable delete while inactive")
private boolean enableDeleteWhileInactive = false;
- @Parameter(names = { "--disable-delete-while-inactive", "-d" }, description = "Disable delete while inactive")
+ @Option(names = { "--disable-delete-while-inactive", "-d" }, description = "Disable delete while inactive")
private boolean disableDeleteWhileInactive = false;
- @Parameter(names = {"--max-inactive-duration", "-t"}, description = "Max duration of topic inactivity in "
+ @Option(names = {"--max-inactive-duration", "-t"}, description = "Max duration of topic inactivity in "
+ "seconds, topics that are inactive for longer than this value will be deleted "
+ "(eg: 1s, 10s, 1m, 5h, 3d)", required = true,
- converter = TimeUnitToSecondsConverter.class,
- validateValueWith = IntegerMaxValueLongValidator.class)
+ converter = TimeUnitToSecondsConverter.class)
private Long maxInactiveDurationInSeconds;
- @Parameter(names = { "--delete-mode", "-m" }, description = "Mode of delete inactive topic, Valid options are: "
+ @Option(names = { "--delete-mode", "-m" }, description = "Mode of delete inactive topic, Valid options are: "
+ "[delete_when_no_subscriptions, delete_when_subscriptions_caught_up]", required = true)
private String inactiveTopicDeleteMode;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enableDeleteWhileInactive == disableDeleteWhileInactive) {
throw new ParameterException("Need to specify either enable-delete-while-inactive or "
+ "disable-delete-while-inactive");
@@ -1585,31 +1575,31 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set the delayed delivery policy on a namespace")
+ @Command(description = "Set the delayed delivery policy on a namespace")
private class SetDelayedDelivery extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable delayed delivery messages")
+ @Option(names = { "--enable", "-e" }, description = "Enable delayed delivery messages")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable delayed delivery messages")
+ @Option(names = { "--disable", "-d" }, description = "Disable delayed delivery messages")
private boolean disable = false;
- @Parameter(names = { "--time", "-t" }, description = "The tick time for when retrying on "
+ @Option(names = { "--time", "-t" }, description = "The tick time for when retrying on "
+ "delayed delivery messages, affecting the accuracy of the delivery time compared to "
+ "the scheduled time. (eg: 1s, 10s, 1m, 5h, 3d)",
converter = TimeUnitToMillisConverter.class)
private Long delayedDeliveryTimeInMills = 1000L;
- @Parameter(names = { "--maxDelay", "-md" },
+ @Option(names = { "--maxDelay", "-md" },
description = "The max allowed delay for delayed delivery. (eg: 1s, 10s, 1m, 5h, 3d)",
converter = TimeUnitToMillisConverter.class)
private Long delayedDeliveryMaxDelayInMillis = 0L;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enable == disable) {
throw new ParameterException("Need to specify either --enable or --disable");
}
@@ -1622,304 +1612,304 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set subscription auth mode on a namespace")
+ @Command(description = "Set subscription auth mode on a namespace")
private class SetSubscriptionAuthMode extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-m", "--subscription-auth-mode" }, description = "Subscription authorization mode for "
+ @Option(names = { "-m", "--subscription-auth-mode" }, description = "Subscription authorization mode for "
+ "Pulsar policies. Valid options are: [None, Prefix]", required = true)
private String mode;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setSubscriptionAuthMode(namespace, SubscriptionAuthMode.valueOf(mode));
}
}
- @Parameters(commandDescription = "Get subscriptionAuthMod for a namespace")
+ @Command(description = "Get subscriptionAuthMod for a namespace")
private class GetSubscriptionAuthMode extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getSubscriptionAuthMode(namespace));
}
}
- @Parameters(commandDescription = "Get deduplicationSnapshotInterval for a namespace")
+ @Command(description = "Get deduplicationSnapshotInterval for a namespace")
private class GetDeduplicationSnapshotInterval extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getDeduplicationSnapshotInterval(namespace));
}
}
- @Parameters(commandDescription = "Remove deduplicationSnapshotInterval for a namespace")
+ @Command(description = "Remove deduplicationSnapshotInterval for a namespace")
private class RemoveDeduplicationSnapshotInterval extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeDeduplicationSnapshotInterval(namespace);
}
}
- @Parameters(commandDescription = "Set deduplicationSnapshotInterval for a namespace")
+ @Command(description = "Set deduplicationSnapshotInterval for a namespace")
private class SetDeduplicationSnapshotInterval extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--interval", "-i"}
+ @Option(names = {"--interval", "-i"}
, description = "deduplicationSnapshotInterval for a namespace", required = true)
private int interval;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setDeduplicationSnapshotInterval(namespace, interval);
}
}
- @Parameters(commandDescription = "Get maxProducersPerTopic for a namespace")
+ @Command(description = "Get maxProducersPerTopic for a namespace")
private class GetMaxProducersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxProducersPerTopic(namespace));
}
}
- @Parameters(commandDescription = "Remove max producers per topic for a namespace")
+ @Command(description = "Remove max producers per topic for a namespace")
private class RemoveMaxProducersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxProducersPerTopic(namespace);
}
}
- @Parameters(commandDescription = "Set maxProducersPerTopic for a namespace")
+ @Command(description = "Set maxProducersPerTopic for a namespace")
private class SetMaxProducersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-producers-per-topic", "-p" },
+ @Option(names = { "--max-producers-per-topic", "-p" },
description = "maxProducersPerTopic for a namespace", required = true)
private int maxProducersPerTopic;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxProducersPerTopic(namespace, maxProducersPerTopic);
}
}
- @Parameters(commandDescription = "Get maxConsumersPerTopic for a namespace")
+ @Command(description = "Get maxConsumersPerTopic for a namespace")
private class GetMaxConsumersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxConsumersPerTopic(namespace));
}
}
- @Parameters(commandDescription = "Set maxConsumersPerTopic for a namespace")
+ @Command(description = "Set maxConsumersPerTopic for a namespace")
private class SetMaxConsumersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-consumers-per-topic", "-c" },
+ @Option(names = { "--max-consumers-per-topic", "-c" },
description = "maxConsumersPerTopic for a namespace", required = true)
private int maxConsumersPerTopic;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxConsumersPerTopic(namespace, maxConsumersPerTopic);
}
}
- @Parameters(commandDescription = "Remove max consumers per topic for a namespace")
+ @Command(description = "Remove max consumers per topic for a namespace")
private class RemoveMaxConsumersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxConsumersPerTopic(namespace);
}
}
- @Parameters(commandDescription = "Get maxConsumersPerSubscription for a namespace")
+ @Command(description = "Get maxConsumersPerSubscription for a namespace")
private class GetMaxConsumersPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxConsumersPerSubscription(namespace));
}
}
- @Parameters(commandDescription = "Remove maxConsumersPerSubscription for a namespace")
+ @Command(description = "Remove maxConsumersPerSubscription for a namespace")
private class RemoveMaxConsumersPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxConsumersPerSubscription(namespace);
}
}
- @Parameters(commandDescription = "Set maxConsumersPerSubscription for a namespace")
+ @Command(description = "Set maxConsumersPerSubscription for a namespace")
private class SetMaxConsumersPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-consumers-per-subscription", "-c" },
+ @Option(names = { "--max-consumers-per-subscription", "-c" },
description = "maxConsumersPerSubscription for a namespace", required = true)
private int maxConsumersPerSubscription;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxConsumersPerSubscription(namespace, maxConsumersPerSubscription);
}
}
- @Parameters(commandDescription = "Get maxUnackedMessagesPerConsumer for a namespace")
+ @Command(description = "Get maxUnackedMessagesPerConsumer for a namespace")
private class GetMaxUnackedMessagesPerConsumer extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxUnackedMessagesPerConsumer(namespace));
}
}
- @Parameters(commandDescription = "Set maxUnackedMessagesPerConsumer for a namespace")
+ @Command(description = "Set maxUnackedMessagesPerConsumer for a namespace")
private class SetMaxUnackedMessagesPerConsumer extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-unacked-messages-per-topic", "-c" },
+ @Option(names = { "--max-unacked-messages-per-topic", "-c" },
description = "maxUnackedMessagesPerConsumer for a namespace", required = true)
private int maxUnackedMessagesPerConsumer;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxUnackedMessagesPerConsumer(namespace, maxUnackedMessagesPerConsumer);
}
}
- @Parameters(commandDescription = "Remove maxUnackedMessagesPerConsumer for a namespace")
+ @Command(description = "Remove maxUnackedMessagesPerConsumer for a namespace")
private class RemoveMaxUnackedMessagesPerConsumer extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxUnackedMessagesPerConsumer(namespace);
}
}
- @Parameters(commandDescription = "Get maxUnackedMessagesPerSubscription for a namespace")
+ @Command(description = "Get maxUnackedMessagesPerSubscription for a namespace")
private class GetMaxUnackedMessagesPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxUnackedMessagesPerSubscription(namespace));
}
}
- @Parameters(commandDescription = "Set maxUnackedMessagesPerSubscription for a namespace")
+ @Command(description = "Set maxUnackedMessagesPerSubscription for a namespace")
private class SetMaxUnackedMessagesPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--max-unacked-messages-per-subscription", "-c" },
+ @Option(names = {"--max-unacked-messages-per-subscription", "-c"},
description = "maxUnackedMessagesPerSubscription for a namespace", required = true)
private int maxUnackedMessagesPerSubscription;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxUnackedMessagesPerSubscription(namespace, maxUnackedMessagesPerSubscription);
}
}
- @Parameters(commandDescription = "Remove maxUnackedMessagesPerSubscription for a namespace")
+ @Command(description = "Remove maxUnackedMessagesPerSubscription for a namespace")
private class RemoveMaxUnackedMessagesPerSubscription extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxUnackedMessagesPerSubscription(namespace);
}
}
- @Parameters(commandDescription = "Get compactionThreshold for a namespace")
+ @Command(description = "Get compactionThreshold for a namespace")
private class GetCompactionThreshold extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getCompactionThreshold(namespace));
}
}
- @Parameters(commandDescription = "Remove compactionThreshold for a namespace")
+ @Command(description = "Remove compactionThreshold for a namespace")
private class RemoveCompactionThreshold extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeCompactionThreshold(namespace);
}
}
- @Parameters(commandDescription = "Set compactionThreshold for a namespace")
+ @Command(description = "Set compactionThreshold for a namespace")
private class SetCompactionThreshold extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--threshold", "-t" },
+ @Option(names = { "--threshold", "-t" },
description = "Maximum number of bytes in a topic backlog before compaction is triggered "
+ "(eg: 10M, 16G, 3T). 0 disables automatic compaction",
required = true,
@@ -1928,30 +1918,30 @@ private class SetCompactionThreshold extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setCompactionThreshold(namespace, threshold);
}
}
- @Parameters(commandDescription = "Get offloadThreshold for a namespace")
+ @Command(description = "Get offloadThreshold for a namespace")
private class GetOffloadThreshold extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print("offloadThresholdInBytes: " + getAdmin().namespaces().getOffloadThreshold(namespace));
print("offloadThresholdInSeconds: " + getAdmin().namespaces().getOffloadThresholdInSeconds(namespace));
}
}
- @Parameters(commandDescription = "Set offloadThreshold for a namespace")
+ @Command(description = "Set offloadThreshold for a namespace")
private class SetOffloadThreshold extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--size", "-s" },
+ @Option(names = { "--size", "-s" },
description = "Maximum number of bytes stored in the pulsar cluster for a topic before data will"
+ " start being automatically offloaded to longterm storage (eg: 10M, 16G, 3T, 100)."
+ " -1 falls back to the cluster's namespace default."
@@ -1961,7 +1951,7 @@ private class SetOffloadThreshold extends CliCommand {
converter = ByteUnitToLongConverter.class)
private Long threshold = -1L;
- @Parameter(names = {"--time", "-t"},
+ @Option(names = {"--time", "-t"},
description = "Maximum number of seconds stored on the pulsar cluster for a topic"
+ " before the broker will start offloading to longterm storage (eg: 10m, 5h, 3d, 2w).",
converter = TimeUnitToSecondsConverter.class)
@@ -1969,20 +1959,20 @@ private class SetOffloadThreshold extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setOffloadThreshold(namespace, threshold);
getAdmin().namespaces().setOffloadThresholdInSeconds(namespace, thresholdInSeconds);
}
}
- @Parameters(commandDescription = "Get offloadDeletionLag, in minutes, for a namespace")
+ @Command(description = "Get offloadDeletionLag, in minutes, for a namespace")
private class GetOffloadDeletionLag extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
Long lag = getAdmin().namespaces().getOffloadDeleteLagMs(namespace);
if (lag != null) {
System.out.println(TimeUnit.MINUTES.convert(lag, TimeUnit.MILLISECONDS) + " minute(s)");
@@ -1992,12 +1982,12 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set offloadDeletionLag for a namespace")
+ @Command(description = "Set offloadDeletionLag for a namespace")
private class SetOffloadDeletionLag extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--lag", "-l" },
+ @Option(names = { "--lag", "-l" },
description = "Duration to wait after offloading a ledger segment, before deleting the copy of that"
+ " segment from cluster local storage. (eg: 10m, 5h, 3d, 2w).",
required = true,
@@ -2006,53 +1996,53 @@ private class SetOffloadDeletionLag extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setOffloadDeleteLag(namespace, lagInSec,
TimeUnit.SECONDS);
}
}
- @Parameters(commandDescription = "Clear offloadDeletionLag for a namespace")
+ @Command(description = "Clear offloadDeletionLag for a namespace")
private class ClearOffloadDeletionLag extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().clearOffloadDeleteLag(namespace);
}
}
- @Parameters(commandDescription = "Get the schema auto-update strategy for a namespace", hidden = true)
+ @Command(description = "Get the schema auto-update strategy for a namespace")
private class GetSchemaAutoUpdateStrategy extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
System.out.println(getAdmin().namespaces().getSchemaAutoUpdateCompatibilityStrategy(namespace)
.toString().toUpperCase());
}
}
- @Parameters(commandDescription = "Set the schema auto-update strategy for a namespace", hidden = true)
+ @Command(description = "Set the schema auto-update strategy for a namespace")
private class SetSchemaAutoUpdateStrategy extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--compatibility", "-c" },
+ @Option(names = { "--compatibility", "-c" },
description = "Compatibility level required for new schemas created via a Producer. "
+ "Possible values (Full, Backward, Forward).")
private String strategyParam = null;
- @Parameter(names = { "--disabled", "-d" }, description = "Disable automatic schema updates")
+ @Option(names = { "--disabled", "-d" }, description = "Disable automatic schema updates")
private boolean disabled = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
SchemaAutoUpdateCompatibilityStrategy strategy = null;
String strategyStr = strategyParam != null ? strategyParam.toUpperCase() : "";
@@ -2073,25 +2063,25 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the schema compatibility strategy for a namespace")
+ @Command(description = "Get the schema compatibility strategy for a namespace")
private class GetSchemaCompatibilityStrategy extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
System.out.println(getAdmin().namespaces().getSchemaCompatibilityStrategy(namespace)
.toString().toUpperCase());
}
}
- @Parameters(commandDescription = "Set the schema compatibility strategy for a namespace")
+ @Command(description = "Set the schema compatibility strategy for a namespace")
private class SetSchemaCompatibilityStrategy extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--compatibility", "-c" },
+ @Option(names = { "--compatibility", "-c" },
description = "Compatibility level required for new schemas created via a Producer. "
+ "Possible values (FULL, BACKWARD, FORWARD, "
+ "UNDEFINED, BACKWARD_TRANSITIVE, "
@@ -2102,7 +2092,7 @@ private class SetSchemaCompatibilityStrategy extends CliCommand {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
String strategyStr = strategyParam != null ? strategyParam.toUpperCase() : "";
SchemaCompatibilityStrategy strategy;
@@ -2116,33 +2106,33 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the namespace whether allow auto update schema")
+ @Command(description = "Get the namespace whether allow auto update schema")
private class GetIsAllowAutoUpdateSchema extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
System.out.println(getAdmin().namespaces().getIsAllowAutoUpdateSchema(namespace));
}
}
- @Parameters(commandDescription = "Set the namespace whether allow auto update schema")
+ @Command(description = "Set the namespace whether allow auto update schema")
private class SetIsAllowAutoUpdateSchema extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable schema validation enforced")
+ @Option(names = { "--enable", "-e" }, description = "Enable schema validation enforced")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable schema validation enforced")
+ @Option(names = { "--disable", "-d" }, description = "Disable schema validation enforced")
private boolean disable = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enable == disable) {
throw new ParameterException("Need to specify either --enable or --disable");
@@ -2151,36 +2141,36 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Get the schema validation enforced")
+ @Command(description = "Get the schema validation enforced")
private class GetSchemaValidationEnforced extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "-ap", "--applied" }, description = "Get the applied policy of the namespace")
+ @Option(names = { "-ap", "--applied" }, description = "Get the applied policy of the namespace")
private boolean applied = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
System.out.println(getAdmin().namespaces().getSchemaValidationEnforced(namespace, applied));
}
}
- @Parameters(commandDescription = "Set the schema whether open schema validation enforced")
+ @Command(description = "Set the schema whether open schema validation enforced")
private class SetSchemaValidationEnforced extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--enable", "-e" }, description = "Enable schema validation enforced")
+ @Option(names = { "--enable", "-e" }, description = "Enable schema validation enforced")
private boolean enable = false;
- @Parameter(names = { "--disable", "-d" }, description = "Disable schema validation enforced")
+ @Option(names = { "--disable", "-d" }, description = "Disable schema validation enforced")
private boolean disable = false;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (enable == disable) {
throw new ParameterException("Need to specify either --enable or --disable");
@@ -2189,103 +2179,100 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Set the offload policies for a namespace")
+ @Command(description = "Set the offload policies for a namespace")
private class SetOffloadPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(
+ @Option(
names = {"--driver", "-d"},
description = "Driver to use to offload old data to long term storage, "
+ "(Possible values: S3, aws-s3, google-cloud-storage, filesystem, azureblob)",
required = true)
private String driver;
- @Parameter(
+ @Option(
names = {"--region", "-r"},
description = "The long term storage region, "
- + "default is s3ManagedLedgerOffloadRegion or gcsManagedLedgerOffloadRegion in broker.conf",
+ + "default is s3ManagedLedgerOffloadRegion or gcsManagedLedgerOffloadRegion in broker.conf",
required = false)
private String region;
- @Parameter(
+ @Option(
names = {"--bucket", "-b"},
description = "Bucket to place offloaded ledger into",
required = false)
private String bucket;
- @Parameter(
+ @Option(
names = {"--endpoint", "-e"},
description = "Alternative endpoint to connect to, "
+ "s3 default is s3ManagedLedgerOffloadServiceEndpoint in broker.conf",
required = false)
private String endpoint;
- @Parameter(
+ @Option(
names = {"--aws-id", "-i"},
description = "AWS Credential Id to use when using driver S3 or aws-s3",
required = false)
private String awsId;
- @Parameter(
+ @Option(
names = {"--aws-secret", "-s"},
description = "AWS Credential Secret to use when using driver S3 or aws-s3",
required = false)
private String awsSecret;
- @Parameter(
+ @Option(
names = {"--s3-role", "-ro"},
description = "S3 Role used for STSAssumeRoleSessionCredentialsProvider",
required = false)
private String s3Role;
- @Parameter(
+ @Option(
names = {"--s3-role-session-name", "-rsn"},
description = "S3 role session name used for STSAssumeRoleSessionCredentialsProvider",
required = false)
private String s3RoleSessionName;
- @Parameter(
+ @Option(
names = {"--maxBlockSize", "-mbs"},
description = "Max block size (eg: 32M, 64M), default is 64MB"
+ "s3 and google-cloud-storage requires this parameter",
required = false,
- converter = ByteUnitIntegerConverter.class,
- validateValueWith = {PositiveIntegerValueValidator.class})
+ converter = ByteUnitToIntegerConverter.class)
private Integer maxBlockSizeInBytes = OffloadPoliciesImpl.DEFAULT_MAX_BLOCK_SIZE_IN_BYTES;
- @Parameter(
+ @Option(
names = {"--readBufferSize", "-rbs"},
description = "Read buffer size (eg: 1M, 5M), default is 1MB",
required = false,
- converter = ByteUnitIntegerConverter.class,
- validateValueWith = {PositiveIntegerValueValidator.class})
+ converter = ByteUnitToIntegerConverter.class)
private Integer readBufferSizeInBytes = OffloadPoliciesImpl.DEFAULT_READ_BUFFER_SIZE_IN_BYTES;
- @Parameter(
+ @Option(
names = {"--offloadAfterElapsed", "-oae"},
description = "Delay time in Millis for deleting the bookkeeper ledger after offload "
+ "(or seconds,minutes,hours,days,weeks eg: 10s, 100m, 3h, 2d, 5w).",
required = false,
- converter = TimeUnitToMillisConverter.class,
- validateValueWith = PositiveLongValueValidator.class)
+ converter = TimeUnitToMillisConverter.class)
private Long offloadAfterElapsedInMillis = OffloadPoliciesImpl.DEFAULT_OFFLOAD_DELETION_LAG_IN_MILLIS;
- @Parameter(
+ @Option(
names = {"--offloadAfterThreshold", "-oat"},
description = "Offload after threshold size (eg: 1M, 5M)",
required = false,
converter = ByteUnitToLongConverter.class)
private Long offloadAfterThresholdInBytes = OffloadPoliciesImpl.DEFAULT_OFFLOAD_THRESHOLD_IN_BYTES;
- @Parameter(
+ @Option(
names = {"--offloadAfterThresholdInSeconds", "-oats"},
description = "Offload after threshold seconds (or minutes,hours,days,weeks eg: 100m, 3h, 2d, 5w).",
required = false,
converter = TimeUnitToSecondsConverter.class)
private Long offloadThresholdInSeconds = OffloadPoliciesImpl.DEFAULT_OFFLOAD_THRESHOLD_IN_SECONDS;
- @Parameter(
+ @Option(
names = {"--offloadedReadPriority", "-orp"},
description = "Read priority for offloaded messages. By default, once messages are offloaded to "
+ "long-term storage, brokers read messages from long-term storage, but messages can "
@@ -2311,7 +2298,7 @@ public boolean isS3Driver(String driver) {
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (!driverSupported(driver)) {
throw new ParameterException("The driver " + driver + " is not supported, "
@@ -2347,104 +2334,104 @@ void run() throws PulsarAdminException {
}
}
- @Parameters(commandDescription = "Remove the offload policies for a namespace")
+ @Command(description = "Remove the offload policies for a namespace")
private class RemoveOffloadPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeOffloadPolicies(namespace);
}
}
- @Parameters(commandDescription = "Get the offload policies for a namespace")
+ @Command(description = "Get the offload policies for a namespace")
private class GetOffloadPolicies extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getOffloadPolicies(namespace));
}
}
- @Parameters(commandDescription = "Set max topics per namespace")
+ @Command(description = "Set max topics per namespace")
private class SetMaxTopicsPerNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--max-topics-per-namespace", "-t"},
+ @Option(names = {"--max-topics-per-namespace", "-t"},
description = "max topics per namespace", required = true)
private int maxTopicsPerNamespace;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setMaxTopicsPerNamespace(namespace, maxTopicsPerNamespace);
}
}
- @Parameters(commandDescription = "Get max topics per namespace")
+ @Command(description = "Get max topics per namespace")
private class GetMaxTopicsPerNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getMaxTopicsPerNamespace(namespace));
}
}
- @Parameters(commandDescription = "Remove max topics per namespace")
+ @Command(description = "Remove max topics per namespace")
private class RemoveMaxTopicsPerNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeMaxTopicsPerNamespace(namespace);
}
}
- @Parameters(commandDescription = "Set property for a namespace")
+ @Command(description = "Set property for a namespace")
private class SetPropertyForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--key", "-k"}, description = "Key of the property", required = true)
+ @Option(names = {"--key", "-k"}, description = "Key of the property", required = true)
private String key;
- @Parameter(names = {"--value", "-v"}, description = "Value of the property", required = true)
+ @Option(names = {"--value", "-v"}, description = "Value of the property", required = true)
private String value;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setProperty(namespace, key, value);
}
}
- @Parameters(commandDescription = "Set properties of a namespace")
+ @Command(description = "Set properties of a namespace")
private class SetPropertiesForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--properties", "-p"}, description = "key value pair properties(a=a,b=b,c=c)",
+ @Option(names = {"--properties", "-p"}, description = "key value pair properties(a=a,b=b,c=c)",
required = true)
private java.util.List properties;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
if (properties.size() == 0) {
throw new ParameterException(String.format("Required at least one property for the namespace, "
+ "but found %d.", properties.size()));
@@ -2454,386 +2441,387 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Get property for a namespace")
+ @Command(description = "Get property for a namespace")
private class GetPropertyForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--key", "-k"}, description = "Key of the property", required = true)
+ @Option(names = {"--key", "-k"}, description = "Key of the property", required = true)
private String key;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getProperty(namespace, key));
}
}
- @Parameters(commandDescription = "Get properties of a namespace")
+ @Command(description = "Get properties of a namespace")
private class GetPropertiesForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws Exception {
- final String namespace = validateNamespace(params);
+ final String namespace = validateNamespace(namespaceName);
final Map properties = getAdmin().namespaces().getProperties(namespace);
prettyPrint(properties);
}
}
- @Parameters(commandDescription = "Remove property for a namespace")
+ @Command(description = "Remove property for a namespace")
private class RemovePropertyForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = {"--key", "-k"}, description = "Key of the property", required = true)
+ @Option(names = {"--key", "-k"}, description = "Key of the property", required = true)
private String key;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().removeProperty(namespace, key));
}
}
- @Parameters(commandDescription = "Clear all properties for a namespace")
+ @Command(description = "Clear all properties for a namespace")
private class ClearPropertiesForNamespace extends CliCommand {
- @Parameter(description = "tenant/namespace\n", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws Exception {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().clearProperties(namespace);
}
}
- @Parameters(commandDescription = "Get ResourceGroup for a namespace")
+ @Command(description = "Get ResourceGroup for a namespace")
private class GetResourceGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getNamespaceResourceGroup(namespace));
}
}
- @Parameters(commandDescription = "Set ResourceGroup for a namespace")
+ @Command(description = "Set ResourceGroup for a namespace")
private class SetResourceGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--resource-group-name", "-rgn" }, description = "ResourceGroup name", required = true)
+ @Option(names = {"--resource-group-name", "-rgn"}, description = "ResourceGroup name", required = true)
private String rgName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setNamespaceResourceGroup(namespace, rgName);
}
}
- @Parameters(commandDescription = "Remove ResourceGroup from a namespace")
+ @Command(description = "Remove ResourceGroup from a namespace")
private class RemoveResourceGroup extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeNamespaceResourceGroup(namespace);
}
}
- @Parameters(commandDescription = "Update migration state for a namespace")
+
+ @Command(description = "Update migration state for a namespace")
private class UpdateMigrationState extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = "--migrated", description = "Is namespace migrated")
+ @Option(names = "--migrated", description = "Is namespace migrated")
private boolean migrated;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().updateMigrationState(namespace, migrated);
}
}
- @Parameters(commandDescription = "Get entry filters for a namespace")
+ @Command(description = "Get entry filters for a namespace")
private class GetEntryFiltersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getNamespaceEntryFilters(namespace));
}
}
- @Parameters(commandDescription = "Set entry filters for a namespace")
+ @Command(description = "Set entry filters for a namespace")
private class SetEntryFiltersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
- @Parameter(names = { "--entry-filters-name", "-efn" },
+ @Option(names = { "--entry-filters-name", "-efn" },
description = "The class name for the entry filter.", required = true)
- private String entryFiltersName = "";
+ private String entryFiltersName = "";
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setNamespaceEntryFilters(namespace, new EntryFilters(entryFiltersName));
}
}
- @Parameters(commandDescription = "Remove entry filters for a namespace")
+ @Command(description = "Remove entry filters for a namespace")
private class RemoveEntryFiltersPerTopic extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeNamespaceEntryFilters(namespace);
}
}
- @Parameters(commandDescription = "Enable dispatcherPauseOnAckStatePersistent for a namespace")
+ @Command(description = "Enable dispatcherPauseOnAckStatePersistent for a namespace")
private class SetDispatcherPauseOnAckStatePersistent extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().setDispatcherPauseOnAckStatePersistent(namespace);
}
}
- @Parameters(commandDescription = "Get the dispatcherPauseOnAckStatePersistent for a namespace")
+ @Command(description = "Get the dispatcherPauseOnAckStatePersistent for a namespace")
private class GetDispatcherPauseOnAckStatePersistent extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getAdmin().namespaces().getDispatcherPauseOnAckStatePersistent(namespace));
}
}
- @Parameters(commandDescription = "Remove dispatcherPauseOnAckStatePersistent for a namespace")
+ @Command(description = "Remove dispatcherPauseOnAckStatePersistent for a namespace")
private class RemoveDispatcherPauseOnAckStatePersistent extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
getAdmin().namespaces().removeDispatcherPauseOnAckStatePersistent(namespace);
}
}
public CmdNamespaces(Supplier admin) {
super("namespaces", admin);
- jcommander.addCommand("list", new GetNamespacesPerProperty());
- jcommander.addCommand("list-cluster", new GetNamespacesPerCluster());
+ addCommand("list", new GetNamespacesPerProperty());
+ addCommand("list-cluster", new GetNamespacesPerCluster());
- jcommander.addCommand("topics", new GetTopics());
- jcommander.addCommand("bundles", new GetBundles());
- jcommander.addCommand("destinations", new GetDestinations());
- jcommander.addCommand("policies", new GetPolicies());
- jcommander.addCommand("create", new Create());
- jcommander.addCommand("delete", new Delete());
+ addCommand("topics", new GetTopics());
+ addCommand("bundles", new GetBundles());
+ addCommand("destinations", new GetDestinations());
+ addCommand("policies", new GetPolicies());
+ addCommand("create", new Create());
+ addCommand("delete", new Delete());
- jcommander.addCommand("permissions", new Permissions());
- jcommander.addCommand("grant-permission", new GrantPermissions());
- jcommander.addCommand("revoke-permission", new RevokePermissions());
+ addCommand("permissions", new Permissions());
+ addCommand("grant-permission", new GrantPermissions());
+ addCommand("revoke-permission", new RevokePermissions());
- jcommander.addCommand("subscription-permission", new SubscriptionPermissions());
- jcommander.addCommand("grant-subscription-permission", new GrantSubscriptionPermissions());
- jcommander.addCommand("revoke-subscription-permission", new RevokeSubscriptionPermissions());
+ addCommand("subscription-permission", new SubscriptionPermissions());
+ addCommand("grant-subscription-permission", new GrantSubscriptionPermissions());
+ addCommand("revoke-subscription-permission", new RevokeSubscriptionPermissions());
- jcommander.addCommand("set-clusters", new SetReplicationClusters());
- jcommander.addCommand("get-clusters", new GetReplicationClusters());
+ addCommand("set-clusters", new SetReplicationClusters());
+ addCommand("get-clusters", new GetReplicationClusters());
- jcommander.addCommand("set-subscription-types-enabled", new SetSubscriptionTypesEnabled());
- jcommander.addCommand("get-subscription-types-enabled", new GetSubscriptionTypesEnabled());
- jcommander.addCommand("remove-subscription-types-enabled", new RemoveSubscriptionTypesEnabled());
+ addCommand("set-subscription-types-enabled", new SetSubscriptionTypesEnabled());
+ addCommand("get-subscription-types-enabled", new GetSubscriptionTypesEnabled());
+ addCommand("remove-subscription-types-enabled", new RemoveSubscriptionTypesEnabled());
- jcommander.addCommand("get-backlog-quotas", new GetBacklogQuotaMap());
- jcommander.addCommand("set-backlog-quota", new SetBacklogQuota());
- jcommander.addCommand("remove-backlog-quota", new RemoveBacklogQuota());
+ addCommand("get-backlog-quotas", new GetBacklogQuotaMap());
+ addCommand("set-backlog-quota", new SetBacklogQuota());
+ addCommand("remove-backlog-quota", new RemoveBacklogQuota());
- jcommander.addCommand("get-persistence", new GetPersistence());
- jcommander.addCommand("set-persistence", new SetPersistence());
- jcommander.addCommand("remove-persistence", new RemovePersistence());
+ addCommand("get-persistence", new GetPersistence());
+ addCommand("set-persistence", new SetPersistence());
+ addCommand("remove-persistence", new RemovePersistence());
- jcommander.addCommand("get-message-ttl", new GetMessageTTL());
- jcommander.addCommand("set-message-ttl", new SetMessageTTL());
- jcommander.addCommand("remove-message-ttl", new RemoveMessageTTL());
+ addCommand("get-message-ttl", new GetMessageTTL());
+ addCommand("set-message-ttl", new SetMessageTTL());
+ addCommand("remove-message-ttl", new RemoveMessageTTL());
- jcommander.addCommand("get-max-subscriptions-per-topic", new GetMaxSubscriptionsPerTopic());
- jcommander.addCommand("set-max-subscriptions-per-topic", new SetMaxSubscriptionsPerTopic());
- jcommander.addCommand("remove-max-subscriptions-per-topic", new RemoveMaxSubscriptionsPerTopic());
+ addCommand("get-max-subscriptions-per-topic", new GetMaxSubscriptionsPerTopic());
+ addCommand("set-max-subscriptions-per-topic", new SetMaxSubscriptionsPerTopic());
+ addCommand("remove-max-subscriptions-per-topic", new RemoveMaxSubscriptionsPerTopic());
- jcommander.addCommand("get-subscription-expiration-time", new GetSubscriptionExpirationTime());
- jcommander.addCommand("set-subscription-expiration-time", new SetSubscriptionExpirationTime());
- jcommander.addCommand("remove-subscription-expiration-time", new RemoveSubscriptionExpirationTime());
+ addCommand("get-subscription-expiration-time", new GetSubscriptionExpirationTime());
+ addCommand("set-subscription-expiration-time", new SetSubscriptionExpirationTime());
+ addCommand("remove-subscription-expiration-time", new RemoveSubscriptionExpirationTime());
- jcommander.addCommand("get-anti-affinity-group", new GetAntiAffinityGroup());
- jcommander.addCommand("set-anti-affinity-group", new SetAntiAffinityGroup());
- jcommander.addCommand("get-anti-affinity-namespaces", new GetAntiAffinityNamespaces());
- jcommander.addCommand("delete-anti-affinity-group", new DeleteAntiAffinityGroup());
+ addCommand("get-anti-affinity-group", new GetAntiAffinityGroup());
+ addCommand("set-anti-affinity-group", new SetAntiAffinityGroup());
+ addCommand("get-anti-affinity-namespaces", new GetAntiAffinityNamespaces());
+ addCommand("delete-anti-affinity-group", new DeleteAntiAffinityGroup());
- jcommander.addCommand("set-deduplication", new SetDeduplication());
- jcommander.addCommand("get-deduplication", new GetDeduplication());
- jcommander.addCommand("remove-deduplication", new RemoveDeduplication());
+ addCommand("set-deduplication", new SetDeduplication());
+ addCommand("get-deduplication", new GetDeduplication());
+ addCommand("remove-deduplication", new RemoveDeduplication());
- jcommander.addCommand("set-auto-topic-creation", new SetAutoTopicCreation());
- jcommander.addCommand("get-auto-topic-creation", new GetAutoTopicCreation());
- jcommander.addCommand("remove-auto-topic-creation", new RemoveAutoTopicCreation());
+ addCommand("set-auto-topic-creation", new SetAutoTopicCreation());
+ addCommand("get-auto-topic-creation", new GetAutoTopicCreation());
+ addCommand("remove-auto-topic-creation", new RemoveAutoTopicCreation());
- jcommander.addCommand("set-auto-subscription-creation", new SetAutoSubscriptionCreation());
- jcommander.addCommand("get-auto-subscription-creation", new GetAutoSubscriptionCreation());
- jcommander.addCommand("remove-auto-subscription-creation", new RemoveAutoSubscriptionCreation());
+ addCommand("set-auto-subscription-creation", new SetAutoSubscriptionCreation());
+ addCommand("get-auto-subscription-creation", new GetAutoSubscriptionCreation());
+ addCommand("remove-auto-subscription-creation", new RemoveAutoSubscriptionCreation());
- jcommander.addCommand("get-retention", new GetRetention());
- jcommander.addCommand("set-retention", new SetRetention());
- jcommander.addCommand("remove-retention", new RemoveRetention());
+ addCommand("get-retention", new GetRetention());
+ addCommand("set-retention", new SetRetention());
+ addCommand("remove-retention", new RemoveRetention());
- jcommander.addCommand("set-bookie-affinity-group", new SetBookieAffinityGroup());
- jcommander.addCommand("get-bookie-affinity-group", new GetBookieAffinityGroup());
- jcommander.addCommand("delete-bookie-affinity-group", new DeleteBookieAffinityGroup());
+ addCommand("set-bookie-affinity-group", new SetBookieAffinityGroup());
+ addCommand("get-bookie-affinity-group", new GetBookieAffinityGroup());
+ addCommand("delete-bookie-affinity-group", new DeleteBookieAffinityGroup());
- jcommander.addCommand("unload", new Unload());
+ addCommand("unload", new Unload());
- jcommander.addCommand("split-bundle", new SplitBundle());
- jcommander.addCommand("get-topic-positions", new GetTopicHashPositions());
+ addCommand("split-bundle", new SplitBundle());
+ addCommand("get-topic-positions", new GetTopicHashPositions());
- jcommander.addCommand("set-dispatch-rate", new SetDispatchRate());
- jcommander.addCommand("remove-dispatch-rate", new RemoveDispatchRate());
- jcommander.addCommand("get-dispatch-rate", new GetDispatchRate());
+ addCommand("set-dispatch-rate", new SetDispatchRate());
+ addCommand("remove-dispatch-rate", new RemoveDispatchRate());
+ addCommand("get-dispatch-rate", new GetDispatchRate());
- jcommander.addCommand("set-subscribe-rate", new SetSubscribeRate());
- jcommander.addCommand("get-subscribe-rate", new GetSubscribeRate());
- jcommander.addCommand("remove-subscribe-rate", new RemoveSubscribeRate());
+ addCommand("set-subscribe-rate", new SetSubscribeRate());
+ addCommand("get-subscribe-rate", new GetSubscribeRate());
+ addCommand("remove-subscribe-rate", new RemoveSubscribeRate());
- jcommander.addCommand("set-subscription-dispatch-rate", new SetSubscriptionDispatchRate());
- jcommander.addCommand("get-subscription-dispatch-rate", new GetSubscriptionDispatchRate());
- jcommander.addCommand("remove-subscription-dispatch-rate", new RemoveSubscriptionDispatchRate());
+ addCommand("set-subscription-dispatch-rate", new SetSubscriptionDispatchRate());
+ addCommand("get-subscription-dispatch-rate", new GetSubscriptionDispatchRate());
+ addCommand("remove-subscription-dispatch-rate", new RemoveSubscriptionDispatchRate());
- jcommander.addCommand("set-publish-rate", new SetPublishRate());
- jcommander.addCommand("get-publish-rate", new GetPublishRate());
- jcommander.addCommand("remove-publish-rate", new RemovePublishRate());
+ addCommand("set-publish-rate", new SetPublishRate());
+ addCommand("get-publish-rate", new GetPublishRate());
+ addCommand("remove-publish-rate", new RemovePublishRate());
- jcommander.addCommand("set-replicator-dispatch-rate", new SetReplicatorDispatchRate());
- jcommander.addCommand("get-replicator-dispatch-rate", new GetReplicatorDispatchRate());
- jcommander.addCommand("remove-replicator-dispatch-rate", new RemoveReplicatorDispatchRate());
+ addCommand("set-replicator-dispatch-rate", new SetReplicatorDispatchRate());
+ addCommand("get-replicator-dispatch-rate", new GetReplicatorDispatchRate());
+ addCommand("remove-replicator-dispatch-rate", new RemoveReplicatorDispatchRate());
- jcommander.addCommand("clear-backlog", new ClearBacklog());
+ addCommand("clear-backlog", new ClearBacklog());
- jcommander.addCommand("unsubscribe", new Unsubscribe());
+ addCommand("unsubscribe", new Unsubscribe());
- jcommander.addCommand("set-encryption-required", new SetEncryptionRequired());
- jcommander.addCommand("get-encryption-required", new GetEncryptionRequired());
- jcommander.addCommand("set-subscription-auth-mode", new SetSubscriptionAuthMode());
- jcommander.addCommand("get-subscription-auth-mode", new GetSubscriptionAuthMode());
+ addCommand("set-encryption-required", new SetEncryptionRequired());
+ addCommand("get-encryption-required", new GetEncryptionRequired());
+ addCommand("set-subscription-auth-mode", new SetSubscriptionAuthMode());
+ addCommand("get-subscription-auth-mode", new GetSubscriptionAuthMode());
- jcommander.addCommand("set-delayed-delivery", new SetDelayedDelivery());
- jcommander.addCommand("get-delayed-delivery", new GetDelayedDelivery());
- jcommander.addCommand("remove-delayed-delivery", new RemoveDelayedDelivery());
+ addCommand("set-delayed-delivery", new SetDelayedDelivery());
+ addCommand("get-delayed-delivery", new GetDelayedDelivery());
+ addCommand("remove-delayed-delivery", new RemoveDelayedDelivery());
- jcommander.addCommand("get-inactive-topic-policies", new GetInactiveTopicPolicies());
- jcommander.addCommand("set-inactive-topic-policies", new SetInactiveTopicPolicies());
- jcommander.addCommand("remove-inactive-topic-policies", new RemoveInactiveTopicPolicies());
+ addCommand("get-inactive-topic-policies", new GetInactiveTopicPolicies());
+ addCommand("set-inactive-topic-policies", new SetInactiveTopicPolicies());
+ addCommand("remove-inactive-topic-policies", new RemoveInactiveTopicPolicies());
- jcommander.addCommand("get-max-producers-per-topic", new GetMaxProducersPerTopic());
- jcommander.addCommand("set-max-producers-per-topic", new SetMaxProducersPerTopic());
- jcommander.addCommand("remove-max-producers-per-topic", new RemoveMaxProducersPerTopic());
+ addCommand("get-max-producers-per-topic", new GetMaxProducersPerTopic());
+ addCommand("set-max-producers-per-topic", new SetMaxProducersPerTopic());
+ addCommand("remove-max-producers-per-topic", new RemoveMaxProducersPerTopic());
- jcommander.addCommand("get-max-consumers-per-topic", new GetMaxConsumersPerTopic());
- jcommander.addCommand("set-max-consumers-per-topic", new SetMaxConsumersPerTopic());
- jcommander.addCommand("remove-max-consumers-per-topic", new RemoveMaxConsumersPerTopic());
+ addCommand("get-max-consumers-per-topic", new GetMaxConsumersPerTopic());
+ addCommand("set-max-consumers-per-topic", new SetMaxConsumersPerTopic());
+ addCommand("remove-max-consumers-per-topic", new RemoveMaxConsumersPerTopic());
- jcommander.addCommand("get-max-consumers-per-subscription", new GetMaxConsumersPerSubscription());
- jcommander.addCommand("set-max-consumers-per-subscription", new SetMaxConsumersPerSubscription());
- jcommander.addCommand("remove-max-consumers-per-subscription", new RemoveMaxConsumersPerSubscription());
+ addCommand("get-max-consumers-per-subscription", new GetMaxConsumersPerSubscription());
+ addCommand("set-max-consumers-per-subscription", new SetMaxConsumersPerSubscription());
+ addCommand("remove-max-consumers-per-subscription", new RemoveMaxConsumersPerSubscription());
- jcommander.addCommand("get-max-unacked-messages-per-subscription", new GetMaxUnackedMessagesPerSubscription());
- jcommander.addCommand("set-max-unacked-messages-per-subscription", new SetMaxUnackedMessagesPerSubscription());
- jcommander.addCommand("remove-max-unacked-messages-per-subscription",
+ addCommand("get-max-unacked-messages-per-subscription", new GetMaxUnackedMessagesPerSubscription());
+ addCommand("set-max-unacked-messages-per-subscription", new SetMaxUnackedMessagesPerSubscription());
+ addCommand("remove-max-unacked-messages-per-subscription",
new RemoveMaxUnackedMessagesPerSubscription());
- jcommander.addCommand("get-max-unacked-messages-per-consumer", new GetMaxUnackedMessagesPerConsumer());
- jcommander.addCommand("set-max-unacked-messages-per-consumer", new SetMaxUnackedMessagesPerConsumer());
- jcommander.addCommand("remove-max-unacked-messages-per-consumer", new RemoveMaxUnackedMessagesPerConsumer());
+ addCommand("get-max-unacked-messages-per-consumer", new GetMaxUnackedMessagesPerConsumer());
+ addCommand("set-max-unacked-messages-per-consumer", new SetMaxUnackedMessagesPerConsumer());
+ addCommand("remove-max-unacked-messages-per-consumer", new RemoveMaxUnackedMessagesPerConsumer());
- jcommander.addCommand("get-compaction-threshold", new GetCompactionThreshold());
- jcommander.addCommand("set-compaction-threshold", new SetCompactionThreshold());
- jcommander.addCommand("remove-compaction-threshold", new RemoveCompactionThreshold());
+ addCommand("get-compaction-threshold", new GetCompactionThreshold());
+ addCommand("set-compaction-threshold", new SetCompactionThreshold());
+ addCommand("remove-compaction-threshold", new RemoveCompactionThreshold());
- jcommander.addCommand("get-offload-threshold", new GetOffloadThreshold());
- jcommander.addCommand("set-offload-threshold", new SetOffloadThreshold());
+ addCommand("get-offload-threshold", new GetOffloadThreshold());
+ addCommand("set-offload-threshold", new SetOffloadThreshold());
- jcommander.addCommand("get-offload-deletion-lag", new GetOffloadDeletionLag());
- jcommander.addCommand("set-offload-deletion-lag", new SetOffloadDeletionLag());
- jcommander.addCommand("clear-offload-deletion-lag", new ClearOffloadDeletionLag());
+ addCommand("get-offload-deletion-lag", new GetOffloadDeletionLag());
+ addCommand("set-offload-deletion-lag", new SetOffloadDeletionLag());
+ addCommand("clear-offload-deletion-lag", new ClearOffloadDeletionLag());
- jcommander.addCommand("get-schema-autoupdate-strategy", new GetSchemaAutoUpdateStrategy());
- jcommander.addCommand("set-schema-autoupdate-strategy", new SetSchemaAutoUpdateStrategy());
+ addCommand("get-schema-autoupdate-strategy", new GetSchemaAutoUpdateStrategy());
+ addCommand("set-schema-autoupdate-strategy", new SetSchemaAutoUpdateStrategy());
- jcommander.addCommand("get-schema-compatibility-strategy", new GetSchemaCompatibilityStrategy());
- jcommander.addCommand("set-schema-compatibility-strategy", new SetSchemaCompatibilityStrategy());
+ addCommand("get-schema-compatibility-strategy", new GetSchemaCompatibilityStrategy());
+ addCommand("set-schema-compatibility-strategy", new SetSchemaCompatibilityStrategy());
- jcommander.addCommand("get-is-allow-auto-update-schema", new GetIsAllowAutoUpdateSchema());
- jcommander.addCommand("set-is-allow-auto-update-schema", new SetIsAllowAutoUpdateSchema());
+ addCommand("get-is-allow-auto-update-schema", new GetIsAllowAutoUpdateSchema());
+ addCommand("set-is-allow-auto-update-schema", new SetIsAllowAutoUpdateSchema());
- jcommander.addCommand("get-schema-validation-enforce", new GetSchemaValidationEnforced());
- jcommander.addCommand("set-schema-validation-enforce", new SetSchemaValidationEnforced());
+ addCommand("get-schema-validation-enforce", new GetSchemaValidationEnforced());
+ addCommand("set-schema-validation-enforce", new SetSchemaValidationEnforced());
- jcommander.addCommand("set-offload-policies", new SetOffloadPolicies());
- jcommander.addCommand("remove-offload-policies", new RemoveOffloadPolicies());
- jcommander.addCommand("get-offload-policies", new GetOffloadPolicies());
+ addCommand("set-offload-policies", new SetOffloadPolicies());
+ addCommand("remove-offload-policies", new RemoveOffloadPolicies());
+ addCommand("get-offload-policies", new GetOffloadPolicies());
- jcommander.addCommand("set-deduplication-snapshot-interval", new SetDeduplicationSnapshotInterval());
- jcommander.addCommand("get-deduplication-snapshot-interval", new GetDeduplicationSnapshotInterval());
- jcommander.addCommand("remove-deduplication-snapshot-interval", new RemoveDeduplicationSnapshotInterval());
+ addCommand("set-deduplication-snapshot-interval", new SetDeduplicationSnapshotInterval());
+ addCommand("get-deduplication-snapshot-interval", new GetDeduplicationSnapshotInterval());
+ addCommand("remove-deduplication-snapshot-interval", new RemoveDeduplicationSnapshotInterval());
- jcommander.addCommand("set-max-topics-per-namespace", new SetMaxTopicsPerNamespace());
- jcommander.addCommand("get-max-topics-per-namespace", new GetMaxTopicsPerNamespace());
- jcommander.addCommand("remove-max-topics-per-namespace", new RemoveMaxTopicsPerNamespace());
+ addCommand("set-max-topics-per-namespace", new SetMaxTopicsPerNamespace());
+ addCommand("get-max-topics-per-namespace", new GetMaxTopicsPerNamespace());
+ addCommand("remove-max-topics-per-namespace", new RemoveMaxTopicsPerNamespace());
- jcommander.addCommand("set-property", new SetPropertyForNamespace());
- jcommander.addCommand("get-property", new GetPropertyForNamespace());
- jcommander.addCommand("remove-property", new RemovePropertyForNamespace());
- jcommander.addCommand("set-properties", new SetPropertiesForNamespace());
- jcommander.addCommand("get-properties", new GetPropertiesForNamespace());
- jcommander.addCommand("clear-properties", new ClearPropertiesForNamespace());
+ addCommand("set-property", new SetPropertyForNamespace());
+ addCommand("get-property", new GetPropertyForNamespace());
+ addCommand("remove-property", new RemovePropertyForNamespace());
+ addCommand("set-properties", new SetPropertiesForNamespace());
+ addCommand("get-properties", new GetPropertiesForNamespace());
+ addCommand("clear-properties", new ClearPropertiesForNamespace());
- jcommander.addCommand("get-resource-group", new GetResourceGroup());
- jcommander.addCommand("set-resource-group", new SetResourceGroup());
- jcommander.addCommand("remove-resource-group", new RemoveResourceGroup());
+ addCommand("get-resource-group", new GetResourceGroup());
+ addCommand("set-resource-group", new SetResourceGroup());
+ addCommand("remove-resource-group", new RemoveResourceGroup());
- jcommander.addCommand("get-entry-filters", new GetEntryFiltersPerTopic());
- jcommander.addCommand("set-entry-filters", new SetEntryFiltersPerTopic());
- jcommander.addCommand("remove-entry-filters", new RemoveEntryFiltersPerTopic());
+ addCommand("get-entry-filters", new GetEntryFiltersPerTopic());
+ addCommand("set-entry-filters", new SetEntryFiltersPerTopic());
+ addCommand("remove-entry-filters", new RemoveEntryFiltersPerTopic());
- jcommander.addCommand("update-migration-state", new UpdateMigrationState());
+ addCommand("update-migration-state", new UpdateMigrationState());
- jcommander.addCommand("set-dispatcher-pause-on-ack-state-persistent",
+ addCommand("set-dispatcher-pause-on-ack-state-persistent",
new SetDispatcherPauseOnAckStatePersistent());
- jcommander.addCommand("get-dispatcher-pause-on-ack-state-persistent",
+ addCommand("get-dispatcher-pause-on-ack-state-persistent",
new GetDispatcherPauseOnAckStatePersistent());
- jcommander.addCommand("remove-dispatcher-pause-on-ack-state-persistent",
+ addCommand("remove-dispatcher-pause-on-ack-state-persistent",
new RemoveDispatcherPauseOnAckStatePersistent());
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNonPersistentTopics.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNonPersistentTopics.java
index c344a76853c1d..cb75ea345787c 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNonPersistentTopics.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNonPersistentTopics.java
@@ -18,28 +18,29 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.NonPersistentTopics;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
@SuppressWarnings("deprecation")
-@Parameters(commandDescription = "Operations on non-persistent topics", hidden = true)
+@Command(description = "Operations on non-persistent topics", hidden = true)
public class CmdNonPersistentTopics extends CmdBase {
private NonPersistentTopics nonPersistentTopics;
public CmdNonPersistentTopics(Supplier admin) {
super("non-persistent", admin);
- jcommander.addCommand("create-partitioned-topic", new CreatePartitionedCmd());
- jcommander.addCommand("lookup", new Lookup());
- jcommander.addCommand("stats", new GetStats());
- jcommander.addCommand("stats-internal", new GetInternalStats());
- jcommander.addCommand("get-partitioned-topic-metadata", new GetPartitionedTopicMetadataCmd());
- jcommander.addCommand("list", new GetList());
- jcommander.addCommand("list-in-bundle", new GetListInBundle());
+ addCommand("create-partitioned-topic", new CreatePartitionedCmd());
+ addCommand("lookup", new Lookup());
+ addCommand("stats", new GetStats());
+ addCommand("stats-internal", new GetInternalStats());
+ addCommand("get-partitioned-topic-metadata", new GetPartitionedTopicMetadataCmd());
+ addCommand("list", new GetList());
+ addCommand("list-in-bundle", new GetListInBundle());
}
private NonPersistentTopics getNonPersistentTopics() {
@@ -49,99 +50,97 @@ private NonPersistentTopics getNonPersistentTopics() {
return nonPersistentTopics;
}
- @Parameters(commandDescription = "Lookup a topic from the current serving broker")
+ @Command(description = "Lookup a topic from the current serving broker")
private class Lookup extends CliCommand {
- @Parameter(description = "non-persistent://tenant/namespace/topic", required = true)
- private java.util.List params;
+ @Parameters(description = "non-persistent://tenant/namespace/topic", arity = "1")
+ private String topicName;
@Override
void run() throws PulsarAdminException {
- String topic = validateTopicName(params);
+ String topic = validateTopicName(topicName);
print(getAdmin().lookups().lookupTopic(topic));
}
}
- @Parameters(commandDescription = "Get the stats for the topic and its connected producers and consumers. "
+ @Command(description = "Get the stats for the topic and its connected producers and consumers. "
+ "All the rates are computed over a 1 minute window and are relative the last completed 1 minute period.")
private class GetStats extends CliCommand {
- @Parameter(description = "non-persistent://tenant/namespace/topic", required = true)
- private java.util.List params;
+ @Parameters(description = "non-persistent://tenant/namespace/topic", arity = "1")
+ private String topicName;
@Override
void run() throws PulsarAdminException {
- String persistentTopic = validateNonPersistentTopic(params);
+ String persistentTopic = validateNonPersistentTopic(topicName);
print(getNonPersistentTopics().getStats(persistentTopic));
}
}
- @Parameters(commandDescription = "Get the internal stats for the topic")
+ @Command(description = "Get the internal stats for the topic")
private class GetInternalStats extends CliCommand {
- @Parameter(description = "non-persistent://tenant/namespace/topic", required = true)
- private java.util.List params;
+ @Parameters(description = "non-persistent://tenant/namespace/topic", arity = "1")
+ private String topicName;
@Override
void run() throws PulsarAdminException {
- String persistentTopic = validateNonPersistentTopic(params);
+ String persistentTopic = validateNonPersistentTopic(topicName);
print(getNonPersistentTopics().getInternalStats(persistentTopic));
}
}
- @Parameters(commandDescription = "Create a partitioned topic. "
+ @Command(description = "Create a partitioned topic. "
+ "The partitioned topic has to be created before creating a producer on it.")
private class CreatePartitionedCmd extends CliCommand {
- @Parameter(description = "non-persistent://tenant/namespace/topic", required = true)
- private java.util.List params;
+ @Parameters(description = "non-persistent://tenant/namespace/topic", arity = "1")
+ private String topicName;
- @Parameter(names = { "-p",
+ @Option(names = { "-p",
"--partitions" }, description = "Number of partitions for the topic", required = true)
private int numPartitions;
@Override
void run() throws Exception {
- String persistentTopic = validateNonPersistentTopic(params);
+ String persistentTopic = validateNonPersistentTopic(topicName);
getNonPersistentTopics().createPartitionedTopic(persistentTopic, numPartitions);
}
}
- @Parameters(commandDescription = "Get the partitioned topic metadata. "
+ @Command(description = "Get the partitioned topic metadata. "
+ "If the topic is not created or is a non-partitioned topic, it returns empty topic with 0 partitions")
private class GetPartitionedTopicMetadataCmd extends CliCommand {
- @Parameter(description = "non-persistent://tenant/namespace/topic", required = true)
- private java.util.List params;
+ @Parameters(description = "non-persistent://tenant/namespace/topic", arity = "1")
+ private String topicName;
@Override
void run() throws Exception {
- String persistentTopic = validateNonPersistentTopic(params);
- print(getNonPersistentTopics().getPartitionedTopicMetadata(persistentTopic));
+ String nonPersistentTopic = validateNonPersistentTopic(topicName);
+ print(getNonPersistentTopics().getPartitionedTopicMetadata(nonPersistentTopic));
}
}
- @Parameters(commandDescription = "Get list of non-persistent topics present under a namespace")
+ @Command(description = "Get list of non-persistent topics present under a namespace")
private class GetList extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespace;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
print(getNonPersistentTopics().getList(namespace));
}
}
- @Parameters(commandDescription = "Get list of non-persistent topics present under a namespace bundle")
+ @Command(description = "Get list of non-persistent topics present under a namespace bundle")
private class GetListInBundle extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespace;
- @Parameter(names = { "-b",
+ @Option(names = { "-b",
"--bundle" }, description = "bundle range", required = true)
private String bundleRange;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
print(getNonPersistentTopics().getListInBundle(namespace, bundleRange));
}
}
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPackages.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPackages.java
index 24214a89c57c3..68547d233460a 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPackages.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPackages.java
@@ -18,20 +18,20 @@
*/
package org.apache.pulsar.admin.cli;
-import com.beust.jcommander.DynamicParameter;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.Packages;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.packages.management.core.common.PackageMetadata;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
/**
* Commands for administering packages.
*/
-@Parameters(commandDescription = "Operations about packages")
+@Command(description = "Operations about packages")
class CmdPackages extends CmdBase {
private Packages packages;
@@ -40,13 +40,13 @@ public CmdPackages(Supplier admin) {
super("packages", admin);
- jcommander.addCommand("get-metadata", new GetMetadataCmd());
- jcommander.addCommand("update-metadata", new UpdateMetadataCmd());
- jcommander.addCommand("upload", new UploadCmd());
- jcommander.addCommand("download", new DownloadCmd());
- jcommander.addCommand("list", new ListPackagesCmd());
- jcommander.addCommand("list-versions", new ListPackageVersionsCmd());
- jcommander.addCommand("delete", new DeletePackageCmd());
+ addCommand("get-metadata", new GetMetadataCmd());
+ addCommand("update-metadata", new UpdateMetadataCmd());
+ addCommand("upload", new UploadCmd());
+ addCommand("download", new DownloadCmd());
+ addCommand("list", new ListPackagesCmd());
+ addCommand("list-versions", new ListPackageVersionsCmd());
+ addCommand("delete", new DeletePackageCmd());
}
private Packages getPackages() {
@@ -56,9 +56,9 @@ private Packages getPackages() {
return packages;
}
- @Parameters(commandDescription = "Get a package metadata information.")
+ @Command(description = "Get a package metadata information.")
private class GetMetadataCmd extends CliCommand {
- @Parameter(description = "type://tenant/namespace/packageName@version", required = true)
+ @Parameters(description = "type://tenant/namespace/packageName@version", arity = "1")
private String packageName;
@Override
@@ -67,18 +67,18 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Update a package metadata information.")
+ @Command(description = "Update a package metadata information.")
private class UpdateMetadataCmd extends CliCommand {
- @Parameter(description = "type://tenant/namespace/packageName@version", required = true)
+ @Parameters(description = "type://tenant/namespace/packageName@version", arity = "1")
private String packageName;
- @Parameter(names = {"-d", "--description"}, description = "descriptions of a package", required = true)
+ @Option(names = {"-d", "--description"}, description = "descriptions of a package", required = true)
private String description;
- @Parameter(names = {"-c", "--contact"}, description = "contact info of a package")
+ @Option(names = {"-c", "--contact"}, description = "contact info of a package")
private String contact;
- @DynamicParameter(names = {"--properties", "-P"}, description = "external information of a package")
+ @Option(names = {"--properties", "-P"}, description = "external information of a package")
private Map properties = new HashMap<>();
@Override
@@ -89,21 +89,21 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Upload a package")
+ @Command(description = "Upload a package")
private class UploadCmd extends CliCommand {
- @Parameter(description = "type://tenant/namespace/packageName@version", required = true)
+ @Parameters(description = "type://tenant/namespace/packageName@version", arity = "1")
private String packageName;
- @Parameter(names = "--description", description = "descriptions of a package", required = true)
+ @Option(names = "--description", description = "descriptions of a package", required = true)
private String description;
- @Parameter(names = "--contact", description = "contact information of a package")
+ @Option(names = "--contact", description = "contact information of a package")
private String contact;
- @DynamicParameter(names = {"--properties", "-P"}, description = "external information of a package")
+ @Option(names = {"--properties", "-P"}, description = "external information of a package")
private Map properties = new HashMap<>();
- @Parameter(names = "--path", description = "file path of the package", required = true)
+ @Option(names = "--path", description = "file path of the package", required = true)
private String path;
@Override
@@ -117,12 +117,12 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Download a package")
+ @Command(description = "Download a package")
private class DownloadCmd extends CliCommand {
- @Parameter(description = "type://tenant/namespace/packageName@version", required = true)
+ @Parameters(description = "type://tenant/namespace/packageName@version", arity = "1")
private String packageName;
- @Parameter(names = "--path", description = "download destiny path of the package", required = true)
+ @Option(names = "--path", description = "download destiny path of the package", required = true)
private String path;
@Override
@@ -132,10 +132,10 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "List all versions of the given package")
+ @Command(description = "List all versions of the given package")
private class ListPackageVersionsCmd extends CliCommand {
- @Parameter(description = "the package name you want to query, don't need to specify the package version. "
- + "type://tenant/namespace/packageName", required = true)
+ @Parameters(description = "the package name you want to query, don't need to specify the package version. "
+ + "type://tenant/namespace/packageName", arity = "1")
private String packageName;
@Override
@@ -144,12 +144,12 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "List all packages with given type in the specified namespace")
+ @Command(description = "List all packages with given type in the specified namespace")
private class ListPackagesCmd extends CliCommand {
- @Parameter(names = "--type", description = "type of the package", required = true)
+ @Option(names = "--type", description = "type of the package", required = true)
private String type;
- @Parameter(description = "namespace of the package", required = true)
+ @Parameters(description = "namespace of the package", arity = "1")
private String namespace;
@Override
@@ -158,9 +158,9 @@ void run() throws Exception {
}
}
- @Parameters(commandDescription = "Delete a package")
- private class DeletePackageCmd extends CliCommand{
- @Parameter(description = "type://tenant/namespace/packageName@version", required = true)
+ @Command(description = "Delete a package")
+ private class DeletePackageCmd extends CliCommand {
+ @Parameters(description = "type://tenant/namespace/packageName@version", arity = "1")
private String packageName;
@Override
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPersistentTopics.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPersistentTopics.java
index cdfcaefc7f6e4..3dc0ba7b6f24a 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPersistentTopics.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdPersistentTopics.java
@@ -19,8 +19,6 @@
package org.apache.pulsar.admin.cli;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
-import com.beust.jcommander.Parameter;
-import com.beust.jcommander.Parameters;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.buffer.ByteBuf;
@@ -31,19 +29,21 @@
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
-import org.apache.pulsar.cli.converters.TimeUnitToMillisConverter;
-import org.apache.pulsar.cli.converters.TimeUnitToSecondsConverter;
+import org.apache.pulsar.cli.converters.picocli.TimeUnitToMillisConverter;
+import org.apache.pulsar.cli.converters.picocli.TimeUnitToSecondsConverter;
import org.apache.pulsar.client.admin.LongRunningProcessStatus;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.admin.Topics;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
-import org.apache.pulsar.client.cli.NoSplitter;
import org.apache.pulsar.client.impl.BatchMessageIdImpl;
import org.apache.pulsar.client.impl.MessageIdImpl;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
-@Parameters(commandDescription = "Operations on persistent topics. The persistent-topics "
+@Command(description = "Operations on persistent topics. The persistent-topics "
+ "has been deprecated in favor of topics", hidden = true)
public class CmdPersistentTopics extends CmdBase {
private Topics persistentTopics;
@@ -51,39 +51,39 @@ public class CmdPersistentTopics extends CmdBase {
public CmdPersistentTopics(Supplier admin) {
super("persistent", admin);
- jcommander.addCommand("list", new ListCmd());
- jcommander.addCommand("list-partitioned-topics", new PartitionedTopicListCmd());
- jcommander.addCommand("permissions", new Permissions());
- jcommander.addCommand("grant-permission", new GrantPermissions());
- jcommander.addCommand("revoke-permission", new RevokePermissions());
- jcommander.addCommand("lookup", new Lookup());
- jcommander.addCommand("bundle-range", new GetBundleRange());
- jcommander.addCommand("delete", new DeleteCmd());
- jcommander.addCommand("unload", new UnloadCmd());
- jcommander.addCommand("truncate", new TruncateCmd());
- jcommander.addCommand("subscriptions", new ListSubscriptions());
- jcommander.addCommand("unsubscribe", new DeleteSubscription());
- jcommander.addCommand("create-subscription", new CreateSubscription());
- jcommander.addCommand("stats", new GetStats());
- jcommander.addCommand("stats-internal", new GetInternalStats());
- jcommander.addCommand("info-internal", new GetInternalInfo());
- jcommander.addCommand("partitioned-stats", new GetPartitionedStats());
- jcommander.addCommand("partitioned-stats-internal", new GetPartitionedStatsInternal());
- jcommander.addCommand("skip", new Skip());
- jcommander.addCommand("skip-all", new SkipAll());
- jcommander.addCommand("expire-messages", new ExpireMessages());
- jcommander.addCommand("expire-messages-all-subscriptions", new ExpireMessagesForAllSubscriptions());
- jcommander.addCommand("create-partitioned-topic", new CreatePartitionedCmd());
- jcommander.addCommand("update-partitioned-topic", new UpdatePartitionedCmd());
- jcommander.addCommand("get-partitioned-topic-metadata", new GetPartitionedTopicMetadataCmd());
- jcommander.addCommand("delete-partitioned-topic", new DeletePartitionedCmd());
- jcommander.addCommand("peek-messages", new PeekMessages());
- jcommander.addCommand("get-message-by-id", new GetMessageById());
- jcommander.addCommand("last-message-id", new GetLastMessageId());
- jcommander.addCommand("reset-cursor", new ResetCursor());
- jcommander.addCommand("terminate", new Terminate());
- jcommander.addCommand("compact", new Compact());
- jcommander.addCommand("compaction-status", new CompactionStatusCmd());
+ addCommand("list", new ListCmd());
+ addCommand("list-partitioned-topics", new PartitionedTopicListCmd());
+ addCommand("permissions", new Permissions());
+ addCommand("grant-permission", new GrantPermissions());
+ addCommand("revoke-permission", new RevokePermissions());
+ addCommand("lookup", new Lookup());
+ addCommand("bundle-range", new GetBundleRange());
+ addCommand("delete", new DeleteCmd());
+ addCommand("unload", new UnloadCmd());
+ addCommand("truncate", new TruncateCmd());
+ addCommand("subscriptions", new ListSubscriptions());
+ addCommand("unsubscribe", new DeleteSubscription());
+ addCommand("create-subscription", new CreateSubscription());
+ addCommand("stats", new GetStats());
+ addCommand("stats-internal", new GetInternalStats());
+ addCommand("info-internal", new GetInternalInfo());
+ addCommand("partitioned-stats", new GetPartitionedStats());
+ addCommand("partitioned-stats-internal", new GetPartitionedStatsInternal());
+ addCommand("skip", new Skip());
+ addCommand("skip-all", new SkipAll());
+ addCommand("expire-messages", new ExpireMessages());
+ addCommand("expire-messages-all-subscriptions", new ExpireMessagesForAllSubscriptions());
+ addCommand("create-partitioned-topic", new CreatePartitionedCmd());
+ addCommand("update-partitioned-topic", new UpdatePartitionedCmd());
+ addCommand("get-partitioned-topic-metadata", new GetPartitionedTopicMetadataCmd());
+ addCommand("delete-partitioned-topic", new DeletePartitionedCmd());
+ addCommand("peek-messages", new PeekMessages());
+ addCommand("get-message-by-id", new GetMessageById());
+ addCommand("last-message-id", new GetLastMessageId());
+ addCommand("reset-cursor", new ResetCursor());
+ addCommand("terminate", new Terminate());
+ addCommand("compact", new Compact());
+ addCommand("compaction-status", new CompactionStatusCmd());
}
private Topics getPersistentTopics() {
@@ -93,420 +93,420 @@ private Topics getPersistentTopics() {
return persistentTopics;
}
- @Parameters(commandDescription = "Get the list of topics under a namespace.")
+ @Command(description = "Get the list of topics under a namespace.")
private class ListCmd extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getPersistentTopics().getList(namespace));
}
}
- @Parameters(commandDescription = "Get the list of partitioned topics under a namespace.")
+ @Command(description = "Get the list of partitioned topics under a namespace.")
private class PartitionedTopicListCmd extends CliCommand {
- @Parameter(description = "tenant/namespace", required = true)
- private java.util.List params;
+ @Parameters(description = "tenant/namespace", arity = "1")
+ private String namespaceName;
@Override
void run() throws PulsarAdminException {
- String namespace = validateNamespace(params);
+ String namespace = validateNamespace(namespaceName);
print(getPersistentTopics().getPartitionedTopicList(namespace));
}
}
- @Parameters(commandDescription = "Grant a new permission to a client role on a single topic.")
+ @Command(description = "Grant a new permission to a client role on a single topic.")
private class GrantPermissions extends CliCommand {
- @Parameter(description = "persistent://tenant/namespace/topic", required = true)
- private java.util.List