com.beust.jcommander.Parameter Java Examples
The following examples show how to use
com.beust.jcommander.Parameter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandLineTest.java From attic-aurora with Apache License 2.0 | 6 votes |
private static void assertEqualOptions(CliOptions expected, CliOptions actual) { List<Object> actualObjects = CommandLine.getOptionsObjects(actual); for (Object expectedOptionContainer : CommandLine.getOptionsObjects(expected)) { Iterable<Field> paramFields = FluentIterable .from(expectedOptionContainer.getClass().getDeclaredFields()) .filter(f -> f.getAnnotation(Parameter.class) != null); Object actualOptionContainer = FluentIterable.from(actualObjects) .firstMatch(Predicates.instanceOf(expectedOptionContainer.getClass())) .get(); for (Field field : paramFields) { Parameter declaration = field.getAnnotation(Parameter.class); try { assertEquals(String.format("Value for %s does not match", declaration.names()[0]), field.get(expectedOptionContainer), field.get(actualOptionContainer)); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } }
Example #2
Source File: ConfigTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldAllowMultipleValues() { class Settable { @Parameter( names = {"-D"}, variableArity = true) @ConfigValue(section = "food", name = "kinds", example = "[]") public List<String> field; } Settable settable = new Settable(); JCommander commander = JCommander.newBuilder() .addObject(settable) .build(); commander.parse("-D", "peas", "-D", "cheese", "-D", "sausages", "--boo"); Config config = new AnnotatedConfig(settable); assertEquals(Optional.of(settable.field), config.getAll("food", "kinds")); }
Example #3
Source File: AbstractCmd.java From ballerina-message-broker with Apache License 2.0 | 6 votes |
/** * Append global level flags info to the provided StringBuilder instance. * * @param sb StringBuilder instance which logs should be appended into. */ private static void appendGlobalFlagsInfo(StringBuilder sb) { int maxLength = 0; Map<String, String> globalFlags = new HashMap<>(); for (Field field : AbstractCmd.class.getDeclaredFields()) { Parameter param = field.getAnnotation(Parameter.class); if (Objects.isNull(param)) { continue; } String key = String.join(",", param.names()); maxLength = Math.max(maxLength, key.length()); globalFlags.put(key, param.description()); } sb.append("Global Flags:\n"); int finalMaxLength = maxLength; globalFlags.keySet().forEach((flag) -> { sb.append(String.format("%2s%-" + String.valueOf(finalMaxLength + LOGS_PADDING) + "s", "", flag)); sb.append(globalFlags.get(flag)); sb.append("\n"); }); }
Example #4
Source File: DescribedOption.java From selenium with Apache License 2.0 | 6 votes |
private static Stream<DescribedOption> getAllFields(HasRoles hasRoles) { Set<DescribedOption> fields = new HashSet<>(); Class<?> clazz = hasRoles.getClass(); while (clazz != null && !Object.class.equals(clazz)) { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); Parameter param = field.getAnnotation(Parameter.class); ConfigValue configValue = field.getAnnotation(ConfigValue.class); if (param != null && configValue != null) { fields.add(new DescribedOption(field.getGenericType(), param, configValue)); } } clazz = clazz.getSuperclass(); } return fields.stream(); }
Example #5
Source File: GeowaveOperationGrpcGenerator.java From geowave with Apache License 2.0 | 6 votes |
public String processOperation(final Class<?> operation, final ProcessOperationResult pr) throws IOException { final Field[] fields = operation.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isAnnotationPresent(Parameter.class)) { final String type = GeoWaveGrpcOperationParser.getGrpcType(fields[i].getType()); pr.message += "\n\t" + type; if (type.equalsIgnoreCase("repeated")) { final ParameterizedType parameterizedType = (ParameterizedType) fields[i].getGenericType(); final Type actualType = parameterizedType.getActualTypeArguments()[0]; pr.message += " " + GeoWaveGrpcOperationParser.getGrpcType(actualType.getClass()); } pr.message += " " + fields[i].getName() + " = " + pr.currFieldPosition + ";"; pr.currFieldPosition++; } if (fields[i].isAnnotationPresent(ParametersDelegate.class)) { processOperation(fields[i].getType(), pr); } } return ""; }
Example #6
Source File: MarkdownGenerator.java From copybara with Apache License 2.0 | 6 votes |
private ImmutableList<DocFlag> generateFlagsInfo(Element classElement) throws ElementException { ImmutableList.Builder<DocFlag> result = ImmutableList.builder(); AnnotationHelper<UsesFlags> annotation = annotationHelper(classElement, UsesFlags.class); if (annotation == null) { return result.build(); } for (DeclaredType flag : annotation.getClassListValue("value")) { Element flagClass = flag.asElement(); for (Element member : flagClass.getEnclosedElements()) { Parameter flagAnnotation = member.getAnnotation(Parameter.class); if (flagAnnotation == null || !(member instanceof VariableElement) || flagAnnotation.hidden()) { continue; } result.add(new DocFlag(Joiner.on(", ").join(flagAnnotation.names()), simplerJavaTypes(member.asType()), flagAnnotation.description())); } } return result.build(); }
Example #7
Source File: ParameterRestFieldValue.java From geowave with Apache License 2.0 | 5 votes |
public ParameterRestFieldValue( final Field field, final Parameter parameter, final Object instance) { super(field, parameter); this.instance = instance; }
Example #8
Source File: JCommanderParameterUtils.java From geowave with Apache License 2.0 | 5 votes |
private static GeoWaveBaseConverter<?> getParameterBaseConverter(final Parameter parameter) { GeoWaveBaseConverter<?> converter = null; try { final Constructor<?> ctor = parameter.converter().getConstructor(String.class); if (ctor != null) { converter = (GeoWaveBaseConverter<?>) ctor.newInstance(new Object[] {""}); } } catch (final Exception e) { LOGGER.error( "An error occurred getting converter from parameter: " + e.getLocalizedMessage(), e); } return converter; }
Example #9
Source File: AbstractConfigCommand.java From halyard with Apache License 2.0 | 5 votes |
@Parameter( names = {"--deployment"}, description = "If supplied, use this Halyard deployment. This will _not_ create a new deployment.") public void setDeployment(String deployment) { GlobalConfigOptions.getGlobalConfigOptions().setDeployment(deployment); }
Example #10
Source File: CLISettings.java From sherlock with GNU General Public License v3.0 | 5 votes |
/** * Attempt to load configuration elements from a * file if the path to the config file has been * specified in the commandline settings. * * @throws IOException if an error reading/location the file occurs */ public void loadFromConfig() throws IOException { // If the config file is defined, attempt to load settings // from a properties file if (CONFIG_FILE == null) { log.info("No configuration file specified, using default/passed settings"); return; } log.info("Attempting to read config file at: {}", CONFIG_FILE); Field[] configFields = Utils.findFields(getClass(), Parameter.class); Properties props = new Properties(); InputStream is = new FileInputStream(CONFIG_FILE); props.load(is); for (Field configField : configFields) { String configName = configField.getName(); Class<?> type = configField.getType(); String configValue = props.getProperty(configName); if (configValue != null && configValue.length() > 0) { configField.setAccessible(true); try { if (type.getName().equals("int")) { configField.set(null, Integer.valueOf(configValue)); } else if (type.getName().equals("boolean")) { configField.set(null, Boolean.valueOf(configValue)); } else { configField.set(null, configValue); } } catch (IllegalAccessException | IllegalArgumentException e) { log.error("Could not set {} to {}: {}", configName, configValue, e.toString()); throw new IOException(String.format( "Failed to set %s to value %s", configName, configValue )); } } } }
Example #11
Source File: NestableCommand.java From halyard with Apache License 2.0 | 5 votes |
@Parameter( names = {"-c", "--color"}, description = "Enable terminal color output.", arity = 1) public void setColor(boolean color) { GlobalOptions.getGlobalOptions().setColor(color); }
Example #12
Source File: NestableCommand.java From halyard with Apache License 2.0 | 5 votes |
@Parameter( names = {"-l", "--log"}, converter = LogLevelConverter.class, description = "Set the log level of the CLI.") public void setLog(Level log) { GlobalOptions.getGlobalOptions().setLog(log); }
Example #13
Source File: NestableCommand.java From halyard with Apache License 2.0 | 5 votes |
@Parameter( names = {"-q", "--quiet"}, description = "Show no task information or messages. When set, ANSI formatting will be disabled, and all prompts will be accepted.") public void setQuiet(boolean quiet) { GlobalOptions.getGlobalOptions().setQuiet(quiet); GlobalOptions.getGlobalOptions().setColor(!quiet); }
Example #14
Source File: NestableCommand.java From halyard with Apache License 2.0 | 5 votes |
@Parameter( names = {"-o", "--output"}, converter = FormatConverter.class, help = true, description = "Format the CLIs output.") public void setOutput(AnsiFormatUtils.Format output) { GlobalOptions.getGlobalOptions().setOutput(output); }
Example #15
Source File: CommandSupport.java From updatebot with Apache License 2.0 | 5 votes |
private void appendPullRequestsCommentArguments(StringBuilder builder, List<Field> fields, boolean namedArguments) { for (Field field : fields) { Parameter parameter = field.getAnnotation(Parameter.class); String[] names = parameter.names(); if (names.length > 0) { String name = names[0]; if (!namedArguments) { continue; } builder.append(" "); builder.append(name); } else { if (namedArguments) { continue; } } Object value = getFieldValue(field, this); if (value != null) { builder.append(" "); if (value instanceof Collection) { builder.append(Strings.join((Collection) value, " ")); } else if (value instanceof Object[]) { builder.append(Strings.join(" ", (Object[]) value)); } else { builder.append(value); } } } }
Example #16
Source File: DescribedOption.java From selenium with Apache License 2.0 | 5 votes |
DescribedOption(Type type, Parameter parameter, ConfigValue configValue) { Objects.requireNonNull(type); Objects.requireNonNull(parameter); Objects.requireNonNull(configValue); this.section = configValue.section(); this.optionName = configValue.name(); this.type = getType(type); this.description = parameter.description(); this.repeats = isCollection(type); this.quotable = isTomlStringType(type); this.example = configValue.example(); this.flags = ImmutableSortedSet.<String>naturalOrder().add(parameter.names()).build(); }
Example #17
Source File: StoreLoader.java From geowave with Apache License 2.0 | 4 votes |
/** * Attempt to load the data store configuration from the config file. * * @param configFile * @return {@code true} if the configuration was successfully loaded */ public boolean loadFromConfig( final Properties props, final String namespace, final File configFile, final Console console) { dataStorePlugin = new DataStorePluginOptions(); // load all plugin options and initialize dataStorePlugin with type and // options if (!dataStorePlugin.load(props, namespace)) { return false; } // knowing the datastore plugin options and class type, get all fields // and parameters in order to detect which are password fields if ((configFile != null) && (dataStorePlugin.getFactoryOptions() != null)) { File tokenFile = SecurityUtils.getFormattedTokenKeyFileForConfig(configFile); final Field[] fields = dataStorePlugin.getFactoryOptions().getClass().getDeclaredFields(); for (final Field field : fields) { for (final Annotation annotation : field.getAnnotations()) { if (annotation.annotationType() == Parameter.class) { final Parameter parameter = (Parameter) annotation; if (JCommanderParameterUtils.isPassword(parameter)) { final String storeFieldName = ((namespace != null) && !"".equals(namespace.trim())) ? namespace + "." + DefaultPluginOptions.OPTS + "." + field.getName() : field.getName(); if (props.containsKey(storeFieldName)) { final String value = props.getProperty(storeFieldName); String decryptedValue = value; try { decryptedValue = SecurityUtils.decryptHexEncodedValue( value, tokenFile.getAbsolutePath(), console); } catch (final Exception e) { LOGGER.error( "An error occurred encrypting specified password value: " + e.getLocalizedMessage(), e); } props.setProperty(storeFieldName, decryptedValue); } } } } } tokenFile = null; } // reload datastore plugin with new password-encrypted properties if (!dataStorePlugin.load(props, namespace)) { return false; } return true; }
Example #18
Source File: StoreFactoryOptions.java From geowave with Apache License 2.0 | 4 votes |
/** * Method to perform global validation for all plugin options * * @throws Exception */ public void validatePluginOptions(final Properties properties, final Console console) throws ParameterException { LOGGER.trace("ENTER :: validatePluginOptions()"); final PropertiesUtils propsUtils = new PropertiesUtils(properties); final boolean defaultEchoEnabled = propsUtils.getBoolean(Constants.CONSOLE_DEFAULT_ECHO_ENABLED_KEY, false); final boolean passwordEchoEnabled = propsUtils.getBoolean(Constants.CONSOLE_PASSWORD_ECHO_ENABLED_KEY, defaultEchoEnabled); LOGGER.debug( "Default console echo is {}, Password console echo is {}", new Object[] { defaultEchoEnabled ? "enabled" : "disabled", passwordEchoEnabled ? "enabled" : "disabled"}); for (final Field field : this.getClass().getDeclaredFields()) { for (final Annotation annotation : field.getAnnotations()) { if (annotation.annotationType() == Parameter.class) { final Parameter parameter = (Parameter) annotation; if (JCommanderParameterUtils.isRequired(parameter)) { field.setAccessible(true); // HPFortify // "Access Specifier Manipulation" // False Positive: These // fields are being modified // by trusted code, // in a way that is not // influenced by user input Object value = null; try { value = field.get(this); if (value == null) { console.println( "Field [" + field.getName() + "] is required: " + Arrays.toString(parameter.names()) + ": " + parameter.description()); console.print("Enter value for [" + field.getName() + "]: "); final boolean echoEnabled = JCommanderParameterUtils.isPassword(parameter) ? passwordEchoEnabled : defaultEchoEnabled; char[] password = console.readPassword(echoEnabled); final String strPassword = new String(password); password = null; if (!"".equals(strPassword.trim())) { value = ((strPassword != null) && !"".equals(strPassword.trim())) ? strPassword.trim() : null; } if (value == null) { throw new ParameterException( "Value for [" + field.getName() + "] cannot be null"); } else { field.set(this, value); } } } catch (final Exception ex) { LOGGER.error( "An error occurred validating plugin options for [" + this.getClass().getName() + "]: " + ex.getLocalizedMessage(), ex); } } } } } }
Example #19
Source File: NestableCommand.java From halyard with Apache License 2.0 | 4 votes |
@Parameter( names = {"--daemon-endpoint"}, description = "If supplied, connect to the daemon at this address.") public void setDaemonEndpoint(String address) { GlobalOptions.getGlobalOptions().setDaemonEndpoint(address); }
Example #20
Source File: RestFieldFactory.java From geowave with Apache License 2.0 | 4 votes |
private static <T extends RestField<?>> List<T> internalCreateRestFields( final Field field, final Parameter parameter, final Object instance, final ParameterInitializer<T> parameterInitializer, final MainParamInitializer<T> mainParamInitializer) { // handle case for core/main params for a command // for now we parse based on assumptions within description // TODO see Issue #1185 for details on a more explicit main // parameter suggestion final String desc = parameter.description(); // this is intended to match one or more "<" + at least one alphanumeric // or some select special character + ">" if (List.class.isAssignableFrom(field.getType()) && !desc.isEmpty() && desc.matches("(<[a-zA-Z0-9:/\\s]+>\\s*)+")) { int currentEndParamIndex = 0; // this simply is collecting names and a flag to indicate if its a // list final List<Pair<String, Boolean>> individualParams = new ArrayList<>(); do { final int currentStartParamIndex = desc.indexOf('<', currentEndParamIndex); if ((currentStartParamIndex < 0) || (currentStartParamIndex >= (desc.length() - 1))) { break; } currentEndParamIndex = desc.indexOf('>', currentStartParamIndex + 1); final String fullName = desc.substring(currentStartParamIndex + 1, currentEndParamIndex).trim(); if (!fullName.isEmpty()) { if (fullName.startsWith("comma separated list of ")) { individualParams.add(ImmutablePair.of(fullName.substring(24).trim(), true)); } else if (fullName.startsWith("comma delimited ")) { individualParams.add(ImmutablePair.of(fullName.substring(16).trim(), true)); } else { individualParams.add(ImmutablePair.of(fullName, false)); } } } while ((currentEndParamIndex > 0) && (currentEndParamIndex < desc.length())); final int totalSize = individualParams.size(); return Lists.transform(individualParams, new Function<Pair<String, Boolean>, T>() { int i = 0; @Override public T apply(final Pair<String, Boolean> input) { if (input != null) { return mainParamInitializer.apply( toURLFriendlyString(input.getLeft()), input.getRight(), field, i++, totalSize, instance); } else { return null; } } }); } else { return Collections.singletonList(parameterInitializer.apply(field, parameter, instance)); } }
Example #21
Source File: ParameterRestField.java From geowave with Apache License 2.0 | 4 votes |
public ParameterRestField(final Field field, final Parameter parameter) { this.field = field; this.parameter = parameter; }
Example #22
Source File: GeoWaveOperationServiceWrapper.java From geowave with Apache License 2.0 | 4 votes |
/** * Reads Parameter fields of the current instance, and populates them with values from the * request. * * <p> This uses an analogous approach to JCommander. Ideally, it could reuse the same * implementation, but ParametersDelegate makes this a bit trickier, since those aren't * initialized right away. Follow the behavior as best as possible, and perform validation. * * @param form The form to fetch parameters from, or the query if form is null. * @throws IllegalAccessException * @throws InstantiationException */ private void injectParameters(final RequestParameters requestParameters, final Object instance) throws MissingArgumentException, InstantiationException, IllegalAccessException { final List<RestFieldValue<?>> fields = RestFieldFactory.createRestFieldValues(instance); for (final RestFieldValue f : fields) { Object objValue = null; final Class<?> type = f.getType(); final Field field = f.getField(); final String strValue = requestParameters.getString(f.getName()); if (field.isAnnotationPresent(Parameter.class)) { final Class<? extends IStringConverter<?>> converter = field.getAnnotation(Parameter.class).converter(); if (converter != null) { if ((converter != NoConverter.class) && (strValue != null)) { try { objValue = converter.newInstance().convert(strValue); } catch (final InstantiationException e) { LOGGER.warn( "Cannot convert parameter since converter does not have zero argument constructor"); } } } } if (objValue == null) { if (List.class.isAssignableFrom(type)) { objValue = requestParameters.getList(f.getName()); } else if (type.isArray()) { objValue = requestParameters.getArray(f.getName()); if (objValue != null) { objValue = Arrays.copyOf((Object[]) objValue, ((Object[]) objValue).length, f.getType()); } } else { if (strValue != null) { if (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) { objValue = Long.valueOf(strValue); } else if (Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) { objValue = Integer.valueOf(strValue); } else if (Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) { objValue = Short.valueOf(strValue); } else if (Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) { objValue = Byte.valueOf(strValue); } else if (Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) { objValue = Double.valueOf(strValue); } else if (Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) { objValue = Float.valueOf(strValue); } else if (Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type)) { objValue = Boolean.valueOf(strValue); } else if (String.class.isAssignableFrom(type)) { objValue = strValue; } else if (Enum.class.isAssignableFrom(type)) { objValue = Enum.valueOf((Class<Enum>) type, strValue.toUpperCase()); } else { throw new RuntimeException("Unsupported format on field " + f.getType()); } } } } if (objValue != null) { f.setValue(objValue); } else if (f.isRequired()) { throw new MissingArgumentException(f.getName()); } } }
Example #23
Source File: NestableCommand.java From halyard with Apache License 2.0 | 4 votes |
@Parameter( names = {"-a", "--alpha"}, description = "Enable alpha halyard features.") public void setAlpha(boolean alpha) { GlobalOptions.getGlobalOptions().setAlpha(alpha); }
Example #24
Source File: NestableCommand.java From halyard with Apache License 2.0 | 4 votes |
@Parameter( names = {"-d", "--debug"}, description = "Show detailed network traffic with halyard daemon.") public void setDebug(boolean debug) { GlobalOptions.getGlobalOptions().setDebug(debug); }
Example #25
Source File: CommandSupport.java From updatebot with Apache License 2.0 | 4 votes |
/** * Appends any command specific parameters */ protected void appendPullRequestCommentArguments(StringBuilder builder) { List<Field> fields = findFieldsAnnotatedWith(getClass(), Parameter.class); appendPullRequestsCommentArguments(builder, fields, true); appendPullRequestsCommentArguments(builder, fields, false); }
Example #26
Source File: ReadmeUtils.java From rdf2x with Apache License 2.0 | 4 votes |
private static void printConfig(Class configClass) throws IllegalAccessException, InstantiationException { Field[] fields = configClass.getDeclaredFields(); System.out.println(); System.out.println("### " + configClass.getSimpleName()); System.out.println(); Object defaultConfig = configClass.newInstance(); System.out.println("|Name|Default|Description|"); System.out.println("|---|---|---|"); try { for (Field field : fields) { field.setAccessible(true); StringBuilder sb = new StringBuilder(); sb.append("|"); Parameter param = field.getDeclaredAnnotation(Parameter.class); if (param != null) { String names = Stream.of(param.names()) .collect(Collectors.joining(", ")); // name sb.append(names).append("|"); // default sb.append(param.required() ? "**required**" : field.get(defaultConfig) + " ").append("|"); // description sb.append(param.description()).append("|"); System.out.println(sb.toString()); } ParametersDelegate delegate = field.getDeclaredAnnotation(ParametersDelegate.class); if (delegate != null) { printConfig(field.getType()); } } } catch (IllegalAccessException e) { e.printStackTrace(); } }
Example #27
Source File: JCommanderRunner.java From metanome-algorithms with Apache License 2.0 | 4 votes |
private static boolean isHelpParameter(Parameter parameter) { return parameter.help(); }
Example #28
Source File: JCommanderRunner.java From metanome-algorithms with Apache License 2.0 | 4 votes |
private static boolean isHelpField(AnnotatedElement annotatedElement) { return ReflectionUtils.getAnnotationIfPresent(annotatedElement, Parameter.class) .map(JCommanderRunner::isHelpParameter) .orElse(Boolean.FALSE).booleanValue(); }
Example #29
Source File: RestFieldFactory.java From geowave with Apache License 2.0 | votes |
public T apply(Field field, Parameter parameter, Object instance);