7c28edac7657f7ac7db7fc711f921a33ddc36715
[dcaegen2/collectors/hv-ves.git] /
1 package org.onap.dcae.collectors.veshv.main.config
2
3 import org.apache.commons.cli.Option
4 import org.apache.commons.cli.Options
5 import org.apache.commons.cli.DefaultParser
6 import org.apache.commons.cli.CommandLine
7 import org.apache.commons.cli.HelpFormatter
8
9
10 internal object DefaultValues {
11     const val MESSAGES_AMOUNT = 1
12 }
13
14 /**
15  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
16  * @since June 2018
17  */
18 internal object ArgBasedClientConfiguration {
19
20     private val OPT_VES_PORT = Option.builder("p")
21             .longOpt("port")
22             .required()
23             .hasArg()
24             .desc("VesHvCollector port")
25             .build()
26
27     private val OPT_VES_HOST = Option.builder("h")
28             .longOpt("host")
29             .required()
30             .hasArg()
31             .desc("VesHvCollector host")
32             .build()
33
34     private val OPT_MESSAGES_AMOUNT = Option.builder("m")
35             .longOpt("messages")
36             .hasArg()
37             .desc("Amount of messages to send")
38             .build()
39
40     private val options by lazy {
41         val options = Options()
42         options.addOption(OPT_VES_PORT)
43         options.addOption(OPT_VES_HOST)
44         options.addOption(OPT_MESSAGES_AMOUNT)
45         options
46     }
47
48     fun parse(args: Array<out String>): ClientConfiguration {
49         val parser = DefaultParser()
50
51         try {
52             parser.parse(options, args).run {
53                 return ClientConfiguration(
54                         stringValue(OPT_VES_HOST),
55                         intValue(OPT_VES_PORT),
56                         intValueOrDefault(OPT_MESSAGES_AMOUNT, DefaultValues.MESSAGES_AMOUNT))
57             }
58         } catch (ex: Exception) {
59             throw WrongArgumentException(ex)
60         }
61     }
62
63     private fun CommandLine.intValueOrDefault(option: Option, default: Int) =
64             getOptionValue(option.opt)?.toInt() ?: default
65
66     private fun CommandLine.intValue(option: Option) =
67             getOptionValue(option.opt).toInt()
68
69     private fun CommandLine.stringValue(option: Option) =
70             getOptionValue(option.opt)
71
72
73     class WrongArgumentException(parent: Exception) : Exception(parent.message, parent) {
74         fun printMessage() {
75             println(message)
76         }
77
78         fun printHelp(programName: String) {
79             val formatter = HelpFormatter()
80             formatter.printHelp(programName, options)
81         }
82     }
83 }