-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Configuration.scala
589 lines (544 loc) · 17.7 KB
/
Configuration.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
package play.api
import java.io._
import com.typesafe.config._
import scala.collection.JavaConverters._
import scala.util.control.NonFatal
/**
* This object provides a set of operations to create `Configuration` values.
*
* For example, to load a `Configuration` in a running application:
* {{{
* val config = Configuration.load()
* val foo = config.getString("foo").getOrElse("boo")
* }}}
*
* The underlying implementation is provided by https://github.com/typesafehub/config.
*/
object Configuration {
private[this] lazy val dontAllowMissingConfigOptions = ConfigParseOptions.defaults().setAllowMissing(false)
private[this] lazy val dontAllowMissingConfig = ConfigFactory.load(dontAllowMissingConfigOptions)
/**
* loads `Configuration` from 'conf/application.conf' in Dev mode
* @return configuration to be used
*/
private[play] def loadDev(appPath: File, devSettings: Map[String, String]): Config = {
try {
val file = {
devSettings.get("config.file").orElse(Option(System.getProperty("config.file")))
.map(f => new File(f)).getOrElse(new File(appPath, "conf/application.conf"))
}
ConfigFactory.parseMap(devSettings.asJava).withFallback(
ConfigFactory.load(ConfigFactory.parseFileAnySyntax(file))
)
} catch {
case e: ConfigException => throw configError(e.origin, e.getMessage, Some(e))
}
}
/**
* Loads a new `Configuration` either from the classpath or from
* `conf/application.conf` depending on the application's Mode.
*
* The provided mode is used if the application is not ready
* yet, just like when calling this method from `play.api.Application`.
*
* Defaults to Mode.Dev
*
* @param mode Application mode.
* @return a `Configuration` instance
*/
def load(appPath: File, mode: Mode.Mode = Mode.Dev, devSettings: Map[String, String] = Map.empty) = {
try {
val currentMode = Play.maybeApplication.map(_.mode).getOrElse(mode)
if (currentMode == Mode.Prod) Configuration(dontAllowMissingConfig) else Configuration(loadDev(appPath, devSettings))
} catch {
case e: ConfigException => throw configError(e.origin, e.getMessage, Some(e))
case e: Throwable => throw e
}
}
/**
* Returns an empty Configuration object.
*/
def empty = Configuration(ConfigFactory.empty())
/**
* Create a ConfigFactory object from the data passed as a Map.
*/
def from(data: Map[String, Any]) = {
def asJavaRecursively[A](data: Map[A, Any]): Map[A, Any] = {
data.mapValues { value =>
value match {
case v: Map[_, _] => asJavaRecursively(v).asJava
case v: Iterable[_] => v.asJava
case v => v
}
}
}
Configuration(ConfigFactory.parseMap(asJavaRecursively[String](data).asJava))
}
private def configError(origin: ConfigOrigin, message: String, e: Option[Throwable] = None): PlayException = {
import scalax.io.JavaConverters._
new PlayException.ExceptionSource("Configuration error", message, e.orNull) {
def line = Option(origin.lineNumber: java.lang.Integer).orNull
def position = null
def input = Option(origin.url).map(_.asInput.string).orNull
def sourceName = Option(origin.filename).orNull
override def toString = "Configuration error: " + getMessage
}
}
}
/**
* A full configuration set.
*
* The underlying implementation is provided by https://github.com/typesafehub/config.
*
* @param underlying the underlying Config implementation
*/
case class Configuration(underlying: Config) {
/**
* Merge 2 configurations.
*/
def ++(other: Configuration): Configuration = {
Configuration(other.underlying.withFallback(underlying))
}
/**
* Read a value from the underlying implementation,
* catching Errors and wrapping it in an Option value.
*/
private def readValue[T](path: String, v: => T): Option[T] = {
try {
Option(v)
} catch {
case e: ConfigException.Missing => None
case NonFatal(e) => throw reportError(path, e.getMessage, Some(e))
}
}
/**
* Retrieves a configuration value as a `String`.
*
* This method supports an optional set of valid values:
* {{{
* val config = Configuration.load()
* val mode = config.getString("engine.mode", Some(Set("dev","prod")))
* }}}
*
* A configuration error will be thrown if the configuration value does not match any of the required values.
*
* @param path the configuration key, relative to configuration root key
* @param validValues valid values for this configuration
* @return a configuration value
*/
def getString(path: String, validValues: Option[Set[String]] = None): Option[String] = readValue(path, underlying.getString(path)).map { value =>
validValues match {
case Some(values) if values.contains(value) => value
case Some(values) if values.isEmpty => value
case Some(values) => throw reportError(path, "Incorrect value, one of " + (values.reduceLeft(_ + ", " + _)) + " was expected.")
case None => value
}
}
/**
* Retrieves a configuration value as an `Int`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val poolSize = configuration.getInt("engine.pool.size")
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Int`.
*
* @param path the configuration key, relative to the configuration root key
* @return a configuration value
*/
def getInt(path: String): Option[Int] = readValue(path, underlying.getInt(path))
/**
* Retrieves a configuration value as a `Boolean`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val isEnabled = configuration.getBoolean("engine.isEnabled")
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Boolean`.
* Authorized vales are `yes/no or true/false.
*
* @param path the configuration key, relative to the configuration root key
* @return a configuration value
*/
def getBoolean(path: String): Option[Boolean] = readValue(path, underlying.getBoolean(path))
/**
* Retrieves a configuration value as `Milliseconds`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val timeout = configuration.getMilliseconds("engine.timeout")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.timeout = 1 second
* }}}
*/
def getMilliseconds(path: String): Option[Long] = readValue(path, underlying.getMilliseconds(path))
/**
* Retrieves a configuration value as `Nanoseconds`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val timeout = configuration.getNanoseconds("engine.timeout")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.timeout = 1 second
* }}}
*/
def getNanoseconds(path: String): Option[Long] = readValue(path, underlying.getNanoseconds(path))
/**
* Retrieves a configuration value as `Bytes`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSize = configuration.getString("engine.maxSize")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSize = 512k
* }}}
*/
def getBytes(path: String): Option[Long] = readValue(path, underlying.getBytes(path))
/**
* Retrieves a sub-configuration, i.e. a configuration instance containing all keys starting with a given prefix.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val engineConfig = configuration.getSub("engine")
* }}}
*
* The root key of this new configuration will be ‘engine’, and you can access any sub-keys relatively.
*
* @param path the root prefix for this sub-configuration
* @return a new configuration
*/
def getConfig(path: String): Option[Configuration] = readValue(path, underlying.getConfig(path)).map(Configuration(_))
/**
* Retrieves a configuration value as a `Double`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val population = configuration.getDouble("world.population")
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Double`.
*
* @param path the configuration key, relative to the configuration root key
* @return a configuration value
*/
def getDouble(path: String): Option[Double] = readValue(path, underlying.getDouble(path))
/**
* Retrieves a configuration value as a `Long`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val duration = configuration.getLong("timeout.duration")
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Long`.
*
* @param path the configuration key, relative to the configuration root key
* @return a configuration value
*/
def getLong(path: String): Option[Long] = readValue(path, underlying.getLong(path))
/**
* Retrieves a configuration value as a `Number`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val counter = configuration.getNumber("foo.counter")
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Number`.
*
* @param path the configuration key, relative to the configuration root key
* @return a configuration value
*/
def getNumber(path: String): Option[Number] = readValue(path, underlying.getNumber(path))
/**
* Retrieves a configuration value as a List of `Boolean`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val switches = configuration.getBooleanList("board.switches")
* }}}
*
* The configuration must be provided as:
*
* {{{
* board.switches = [true, true, false]
* }}}
*
* A configuration error will be thrown if the configuration value is not a valid `Boolean`.
* Authorized vales are `yes/no or true/false.
*/
def getBooleanList(path: String): Option[java.util.List[java.lang.Boolean]] = readValue(path, underlying.getBooleanList(path))
/**
* Retrieves a configuration value as a List of `Bytes`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getBytesList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = [512k, 256k, 256k]
* }}}
*/
def getBytesList(path: String): Option[java.util.List[java.lang.Long]] = readValue(path, underlying.getBytesList(path))
/**
* Retrieves a List of sub-configurations, i.e. a configuration instance for each key that matches the path.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val engineConfigs = configuration.getConfigList("engine")
* }}}
*
* The root key of this new configuration will be "engine", and you can access any sub-keys relatively.
*/
def getConfigList(path: String): Option[java.util.List[Configuration]] = readValue[java.util.List[_ <: Config]](path, underlying.getConfigList(path)).map { configs => configs.asScala.map(Configuration(_)).asJava }
/**
* Retrieves a configuration value as a List of `Double`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getDoubleList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = [5.0, 3.34, 2.6]
* }}}
*/
def getDoubleList(path: String): Option[java.util.List[java.lang.Double]] = readValue(path, underlying.getDoubleList(path))
/**
* Retrieves a configuration value as a List of `Integer`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getIntList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = [100, 500, 2]
* }}}
*/
def getIntList(path: String): Option[java.util.List[java.lang.Integer]] = readValue(path, underlying.getIntList(path))
/**
* Gets a list value (with any element type) as a ConfigList, which implements java.util.List<ConfigValue>.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = ["foo", "bar"]
* }}}
*/
def getList(path: String): Option[ConfigList] = readValue(path, underlying.getList(path))
/**
* Retrieves a configuration value as a List of `Long`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getLongList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = [10000000000000, 500, 2000]
* }}}
*/
def getLongList(path: String): Option[java.util.List[java.lang.Long]] = readValue(path, underlying.getLongList(path))
/**
* Retrieves a configuration value as List of `Milliseconds`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val timeouts = configuration.getMillisecondsList("engine.timeouts")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.timeouts = [1 second, 1 second]
* }}}
*/
def getMillisecondsList(path: String): Option[java.util.List[java.lang.Long]] = readValue(path, underlying.getMillisecondsList(path))
/**
* Retrieves a configuration value as List of `Nanoseconds`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val timeouts = configuration.getNanosecondsList("engine.timeouts")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.timeouts = [1 second, 1 second]
* }}}
*/
def getNanosecondsList(path: String): Option[java.util.List[java.lang.Long]] = readValue(path, underlying.getNanosecondsList(path))
/**
* Retrieves a configuration value as a List of `Number`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val maxSizes = configuration.getNumberList("engine.maxSizes")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.maxSizes = [50, 500, 5000]
* }}}
*/
def getNumberList(path: String): Option[java.util.List[java.lang.Number]] = readValue(path, underlying.getNumberList(path))
/**
* Retrieves a configuration value as a List of `ConfigObject`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val engineProperties = configuration.getObjectList("engine.properties")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.properties = [{id: 5, power: 3}, {id: 6, power: 20}]
* }}}
*/
def getObjectList(path: String): Option[java.util.List[_ <: ConfigObject]] = readValue[java.util.List[_ <: ConfigObject]](path, underlying.getObjectList(path))
/**
* Retrieves a configuration value as a List of `String`.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val names = configuration.getStringList("names")
* }}}
*
* The configuration must be provided as:
*
* {{{
* names = ["Jim", "Bob", "Steve"]
* }}}
*/
def getStringList(path: String): Option[java.util.List[java.lang.String]] = readValue(path, underlying.getStringList(path))
/**
* Retrieves a ConfigObject for this path, which implements Map<String,ConfigValue>
*
* For example:
* {{{
* val configuration = Configuration.load()
* val engineProperties = configuration.getObject("engine.properties")
* }}}
*
* The configuration must be provided as:
*
* {{{
* engine.properties = {id: 1, power: 5}
* }}}
*/
def getObject(path: String): Option[ConfigObject] = readValue(path, underlying.getObject(path))
/**
* Returns available keys.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val keys = configuration.keys
* }}}
*
* @return the set of keys available in this configuration
*/
def keys: Set[String] = underlying.entrySet.asScala.map(_.getKey).toSet
/**
* Returns sub-keys.
*
* For example:
* {{{
* val configuration = Configuration.load()
* val subKeys = configuration.subKeys
* }}}
* @return the set of direct sub-keys available in this configuration
*/
def subKeys: Set[String] = underlying.root().keySet().asScala.toSet
/**
* Returns every path as a set of key to value pairs, by recursively iterating through the
* config objects.
*/
def entrySet: Set[(String, ConfigValue)] = underlying.entrySet().asScala.map(e => e.getKey -> e.getValue).toSet
/**
* Creates a configuration error for a specific configuration key.
*
* For example:
* {{{
* val configuration = Configuration.load()
* throw configuration.reportError("engine.connectionUrl", "Cannot connect!")
* }}}
*
* @param path the configuration key, related to this error
* @param message the error message
* @param e the related exception
* @return a configuration exception
*/
def reportError(path: String, message: String, e: Option[Throwable] = None): PlayException = {
Configuration.configError(if (underlying.hasPath(path)) underlying.getValue(path).origin else underlying.root.origin, message, e)
}
/**
* Creates a configuration error for this configuration.
*
* For example:
* {{{
* val configuration = Configuration.load()
* throw configuration.globalError("Missing configuration key: [yop.url]")
* }}}
*
* @param message the error message
* @param e the related exception
* @return a configuration exception
*/
def globalError(message: String, e: Option[Throwable] = None): PlayException = {
Configuration.configError(underlying.root.origin, message, e)
}
}