Skip to content
lefou edited this page Dec 2, 2014 · 4 revisions

Welcome to the CmdOption wiki!

For an official introductory read, please refer to the projects Readme document (absolute link).

In this wiki you find further information, documentation and examples. Feel free to edit this wiki to provide more information, examples or corrections.

Examples and Solutions

Using a CmdOption Config Object in a Spring Application Context

The following example is in Scala, but it works with Java too.

This example uses the Java-based configuration mechanism introduced in Spring Framework 3.0 instead of a XML-based configuration.

It shows to commandline-based configuration of a datasource, and how this configuration can be injected into the Spring Application Context to make it available for further use.

The Config Class
class Config {
  @CmdOption(names = Array("--db-driver"), args = Array("CLASSNAME"), description = "The class name of the JDBC driver")
  var driverClassName: String = classOf[org.h2.Driver].getName

  @CmdOption(names = Array("--db-url"), args = Array("URL"), description = "The Database URL", minCount = 1)
  var dbUrl: String = _

  @CmdOption(names = Array("--db-username"), args = Array("NAME"), description = "Database connection username")
  var dbUsername: String = _

  @CmdOption(names = Array("--db-password"), args = Array("PASSWORD", description = "Database connection password")
  var dbPassword: String = _
}
The Spring Configuration
@Configuration
class MySpringConfig {
  @Autowired var config: Config = _

  @Bean(destroyMethod = "close") def dataSource: DataSource = {
    val dataSource = new BasicDataSource()
    dataSource.setDriverClassName(config.driverClassName)
    dataSource.setUrl(config.dbUrl)
    if(config.dbUsername != null) {
      dataSource.setUsername(config.dbUsername)
      dataSource.setPassword(config.dbPassword)
    }
    dataSource
  }

  @Bean def myService: MyService = new MyServiceImpl(dataSource)
}
The Application
object MyApplication {
  def main(args: Array[String]) {
    val generalOpts = new {
      @CmdOption(names = Array("-h", "--help"), isHelp = true, description = "Show this help") var help = false
    }
    val config = new Config()
    val cp = new CmdlineParser(config, generalOpts)
    cp.parse(args: _*)

    if(generalOpts.help) {
      cp.usage
      System.exit(0)
    }

    new MyApplication(config).run
  }
}

class MyApplication(config: Config) {
  private val springContext = {
    val staticContext = new StaticApplicationContext()
    staticContext.getBeanFactory.registerSingleton("config", config)
    staticContext.refresh

    val springContext = new AnnotationConfigApplicationContext()
    springContext.register(classOf[MySpringConfig])
    springContext.setParent(staticContext)
    springContext.refresh
    springContext
  }

  def run {
    val myService = springContext.getBean(classOf[MyService])
    myService.doSomethingWithDatabase
  }
}

Annotated Methods Example

This example shows, how to annotation methods (instead of fields) to control what should happen, if CmdOption parses a given option.

public class Config {
  private int logLevel = 0;
  private final Map<String, String> options = new LinkedHashMap<String, String>();
  private final List<String> names = new LinkedList<String>();

  // With each "-v" option increase the log level.
  @CmdOption(names = {"--verbose", "-v"}, maxCount = -1, description = "Be verbose, more verbose, ... (can be used multiple times)")
  public add incrementLogLevel() {
    ++logLevel;
  }

  @CmdOption(names = {"--options", "-o"}, args = {"name", "value"}, maxCount = -1, description = "Additional options when processing names")
  public void addToOptions(String name, String value) {
    options.put(key, value);
  }

  @CmdOption(args = {"file"}, description = "Names to process", minCount = 1, maxCount = -1)
  public void addToNames(String file) {
    names.add(file);
  }
}

Simple Scala Example

This simple example shows, that it is easy to use CmdOption in Scala.

import de.tototec.cmdoption.CmdlineParser
import de.tototec.cmdoption.CmdOption

class Config {
  @CmdOption(names = Array("--verbose", "-v"), description = "Be verbose when running.")
  var verbose = false
}

object MyApp {
  def main(args: Array[String]) {

    val config = new Config()
    val cp = new CmdlineParser(config)
    cp.parse(args: _*)

    if(config.verbose) println("Starting...")

    // ...
  }
}