All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.core.env.SimpleCommandLineArgsParser Maven / Gradle / Ivy

There is a newer version: 6.1.6
Show newest version
/*
 * Copyright 2002-2011 the original author or authors.
 *
 * Licensed 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
 *
 *      https://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.springframework.core.env;

/**
 * Parses a {@code String[]} of command line arguments in order to populate a
 * {@link CommandLineArgs} object.
 *
 * 

Working with option arguments

* Option arguments must adhere to the exact syntax: *
--optName[=optValue]
* That is, options must be prefixed with "{@code --}", and may or may not specify a value. * If a value is specified, the name and value must be separated without spaces * by an equals sign ("="). * *

Valid examples of option arguments

*
 * --foo
 * --foo=bar
 * --foo="bar then baz"
 * --foo=bar,baz,biz
* *

Invalid examples of option arguments

*
 * -foo
 * --foo bar
 * --foo = bar
 * --foo=bar --foo=baz --foo=biz
* *

Working with non-option arguments

* Any and all arguments specified at the command line without the "{@code --}" option * prefix will be considered as "non-option arguments" and made available through the * {@link CommandLineArgs#getNonOptionArgs()} method. * * @author Chris Beams * @since 3.1 */ class SimpleCommandLineArgsParser { /** * Parse the given {@code String} array based on the rules described {@linkplain * SimpleCommandLineArgsParser above}, returning a fully-populated * {@link CommandLineArgs} object. * @param args command line arguments, typically from a {@code main()} method */ public CommandLineArgs parse(String... args) { CommandLineArgs commandLineArgs = new CommandLineArgs(); for (String arg : args) { if (arg.startsWith("--")) { String optionText = arg.substring(2, arg.length()); String optionName; String optionValue = null; if (optionText.contains("=")) { optionName = optionText.substring(0, optionText.indexOf('=')); optionValue = optionText.substring(optionText.indexOf('=')+1, optionText.length()); } else { optionName = optionText; } if (optionName.isEmpty() || (optionValue != null && optionValue.isEmpty())) { throw new IllegalArgumentException("Invalid argument syntax: " + arg); } commandLineArgs.addOptionArg(optionName, optionValue); } else { commandLineArgs.addNonOptionArg(arg); } } return commandLineArgs; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy