cbeust / jcommander

Command line parsing framework for Java
Apache License 2.0
1.96k stars 334 forks source link

Cannot use in Scala the validation feature #500

Open PavelZeger opened 4 years ago

PavelZeger commented 4 years ago

Hi. I'm trying to use "validateWith" but encountered the following error:

object java.lang.Class is not a value
    validateWith = java.lang.Class[RunningFolderValidator]

annotation argument needs to be a constant; found: java.lang.<Class: error>[com.example.utils.validators.RunningFolderValidator]
    validateWith = java.lang.Class[RunningFolderValidator]

no valid targets for annotation on variable runningFolderArg - it is discarded unused. You may specify targets with meta-annotations, e.g. @(<error> @getter)
  @Parameter(

The code is:

import com.beust.jcommander.{IParameterValidator, Parameter}
import com.undertone.utils.validators.RunningFolderValidator

object CmdArgs {

  @Parameter(
    names = Array("-m", "--model-name"),
    required = true)
  var modelNameArg: String = _

  @Parameter(
    names = Array("-e", "--environment"),
    required = true)
  var environmentArg: String = _

  @Parameter(
    names = Array("-f", "--running-folder"),
    required = true,
    validateWith = java.lang.Class[RunningFolderValidator]
  )
  var runningFolderArg: String = _

  @Parameter(
    names = Array("-v", "--vendor-name"),
    required = false)
  var vendorKeyArg: String = _

}

The validator:

import com.beust.jcommander.IParameterValidator
import scala.util.parsing.combinator.RegexParsers

class RunningFolderValidator extends IParameterValidator with RegexParsers {

  private def folderName: Parser[String] = """\d{4}_\d{2}_\d{2}_\d{2}""".r ^^ {_.toString}

  override def validate(name: String, value: String): String = {
    parseAll(folderName, value) match {
      case Success(result, _) => result
      case failure : NoSuccess => throw new RuntimeException("The running folder name isn't valid!\n" +
        "\tPlease use the following pattern: yyyy_MM_dd_HH (%Y_%M_%d_%H)!")
    }
  }
}

How can I implement the validation in Scala?

PavelZeger commented 4 years ago

I changed the code and now it runs without errors:

@Parameter(
    names = Array("-f", "--running-folder"),
    required = true,
    description = "The current folder in AWS S3 bucket in the format yyyy_MM_dd_HH (%Y_%M_%d_%H)",
    validateWith = Array(classOf[RunningFolderValidator])
  )
  var runningFolderArg: String = _

I would appreciate if you can suggest the better approach