| 1 | --- |
| 2 | layout: docs |
| 3 | title: Type conversion |
| 4 | prev_section: parametrized-properties |
| 5 | next_section: variables-expansion |
| 6 | permalink: /docs/type-conversion/ |
| 7 | --- |
| 8 | |
| 9 | OWER API supports properties conversion for primitive types and enums. |
| 10 | When you define the *mapping interface* you can use a wide set of return types, |
| 11 | and they will be automatically converted from `String` to the primitive types |
| 12 | and enums: |
| 13 | |
| 14 | ```java |
| 15 | // conversion happens from the value specified in the |
| 16 | // properties files (if available). |
| 17 | int maxThreads(); |
| 18 | |
| 19 | // conversion happens also from @DefaultValue |
| 20 | @DefaultValue("3.1415") |
| 21 | double pi(); |
| 22 | |
| 23 | // enum values are case sensitive! |
| 24 | // java.util.concurrent.TimeUnit is an enum |
| 25 | @DefaultValue("NANOSECONDS"); |
| 26 | TimeUnit timeUnit(); |
| 27 | ``` |
| 28 | |
| 29 | It is possible to have configuration interfaces to declare business objects as return types, many are compatible and |
| 30 | you can also define your own objects: |
| 31 | |
| 32 | The easiest way is to define your business object with a public constructor |
| 33 | taking a single parameter of type `java.lang.String`: |
| 34 | |
| 35 | ```java |
| 36 | public class CustomType { |
| 37 | private final String text; |
| 38 | |
| 39 | public CustomType(String text) { |
| 40 | this.text = text; |
| 41 | } |
| 42 | |
| 43 | public String getText() { |
| 44 | return text; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | public interface SpecialTypes extends Config { |
| 49 | @DefaultValue("foobar.txt") |
| 50 | File sampleFile(); |
| 51 | |
| 52 | @DefaultValue("http://owner.aeonbits.org") |
| 53 | URL sampleURL(); |
| 54 | |
| 55 | @DefaultValue("example") |
| 56 | CustomType customType(); |
| 57 | |
| 58 | @DefaultValue("Hello %s!") |
| 59 | CustomType salutation(String name); |
| 60 | } |
| 61 | ``` |
| 62 | |
| 63 | OWNER API will take the value "example" and pass it to the CustomType |
| 64 | constructor then return it. |
| 65 | |
| 66 | Arrays and Collections |
| 67 | ---------------------- |
| 68 | |
| 69 | OWNER have first class support for Java Arrays and Collections. |
| 70 | |
| 71 | So now you can define properties like: |
| 72 | |
| 73 | ```java |
| 74 | public class MyConfig extends Config { |
| 75 | |
| 76 | @DefaultValue("apple, pear, orange") |
| 77 | public String[] fruit(); |
| 78 | |
| 79 | @Separator(";") |
| 80 | @DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55") |
| 81 | public int[] fibonacci(); |
| 82 | |
| 83 | @DefaultValue("1, 2, 3, 4") |
| 84 | List<Integer> ints(); |
| 85 | |
| 86 | @DefaultValue( |
| 87 | "http://aeonbits.org, http://github.com, http://google.com") |
| 88 | MyOwnCollection<URL> myBookmarks(); |
| 89 | |
| 90 | // Concrete class are allowed (in this case java.util.Stack) |
| 91 | // when type is not specified <String> is assumed as default |
| 92 | @DefaultValue( |
| 93 | "The Lord of the Rings,The Little Prince,The Da Vinci Code") |
| 94 | Stack books(); |
| 95 | |
| 96 | } |
| 97 | ``` |
| 98 | |
| 99 | You can use array of objects or primitive Java types, as well as Java |
| 100 | collections, as specified by interfaces [`Collection`][Collection], |
| 101 | [`List`][List], [`Set`][Set], [`SortedSet`][SortedSet] or concrete |
| 102 | implementations like [`Vector`][Vector], [`Stack`][Stack], |
| 103 | [`LinkedList`][LinkedList] etc. or your own concrete implementation of the Java |
| 104 | Collections Framework interfaces, as long as your implementation class defines |
| 105 | a default no-arg constructor. |
| 106 | |
| 107 | [Collection]: http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html |
| 108 | [List]: http://docs.oracle.com/javase/7/docs/api/java/util/List.html |
| 109 | [Set]: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html |
| 110 | [SortedSet]: http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html |
| 111 | [Vector]: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html |
| 112 | [Stack]: http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html |
| 113 | [LinkedList]: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html |
| 114 | |
| 115 | The [`Map`][Map] interface and sub-interfaces are not supported. |
| 116 | |
| 117 | [Map]: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html |
| 118 | |
| 119 | By default OWNER uses the comma `","` character to tokenize values for the |
| 120 | arrays and collections, but you can specify different characters (and regexp) |
| 121 | with the [`@Separator`][separator] annotation or, if your property format has a |
| 122 | more complex split logic, you can define your own tokenizer class via the |
| 123 | [`@TokenizerClass`][tokenizerclass] annotation plus [`Tokenizer`][tokenizer] |
| 124 | interface. |
| 125 | |
| 126 | [separator]: http://owner.aeonbits.org/apidocs/latest/org/aeonbits/owner/Config.Separator.html |
| 127 | [tokenizerclass]: http://owner.aeonbits.org/apidocs/latest/org/aeonbits/owner/Config.TokenizerClass.html |
| 128 | [tokenizer]: http://owner.aeonbits.org/apidocs/latest/org/aeonbits/owner/Config.Tokenizer.html |
| 129 | |
| 130 | Example: |
| 131 | |
| 132 | ```java |
| 133 | public class MyConfig extends Config { |
| 134 | |
| 135 | @Separator(";") |
| 136 | @DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55") |
| 137 | public int[] fibonacci(); |
| 138 | |
| 139 | @TokenizerClass(CustomDashTokenizer.class) |
| 140 | @DefaultValue("foo-bar-baz") |
| 141 | public String[] withSeparatorClass(); |
| 142 | |
| 143 | } |
| 144 | |
| 145 | public class CustomDashTokenizer implements Tokenizer { |
| 146 | |
| 147 | // this logic can be as much complex as you need |
| 148 | @Override |
| 149 | public String[] tokens(String values) { |
| 150 | return values.split("-", -1); |
| 151 | } |
| 152 | } |
| 153 | ``` |
| 154 | |
| 155 | The [`@Separator`][separator] and [`@TokenizerClass`][tokenizerclass] |
| 156 | annotations can be specified on method level and on class level. When specified |
| 157 | on method level, the annotation will affect only that method. When specified on |
| 158 | class level, the annotation will affect the complete class. |
| 159 | |
| 160 | Annotations specified on method level override the setting specified on the |
| 161 | class level: |
| 162 | |
| 163 | ```java |
| 164 | @Separator(";") |
| 165 | public interface ArrayExample extends Config { |
| 166 | |
| 167 | // takes the class level @Separator |
| 168 | @DefaultValue("1; 2; 3; 4") |
| 169 | public int[] semicolonSeparated(); |
| 170 | |
| 171 | // overrides the class-level @Separator(";") |
| 172 | @Separator(",") |
| 173 | @DefaultValue("1, 2, 3, 4") |
| 174 | public int[] commaSeparated(); |
| 175 | |
| 176 | // overrides the class level @Separator(";") |
| 177 | @TokenizerClass(CustomDashTokenizer.class) |
| 178 | @DefaultValue("1-2-3-4") |
| 179 | public int[] dashSeparated(); |
| 180 | } |
| 181 | ``` |
| 182 | |
| 183 | <div class="note warning"> |
| 184 | <h5>@Separator and @TokenizerClass don't go together!</h5> |
| 185 | Notice that it is invalid to specify together on the same level both |
| 186 | <code>@Separator</code> and <code>@TokenizerClass</code> annotations: |
| 187 | you cannot specify two different ways to do the same thing! |
| 188 | </div> |
| 189 | |
| 190 | So in following cases you'll get a [`UnsupportedOperationException`][unsupported-ex]: |
| 191 | |
| 192 | ```java |
| 193 | |
| 194 | // @Separator and @TokenizerClass cannot be used together |
| 195 | // on class level. |
| 196 | @TokenizerClass(CustomCommaTokenizer.class) |
| 197 | @Separator(",") |
| 198 | public interface Wrong extends Config { |
| 199 | |
| 200 | // will throw UnsupportedOperationException! |
| 201 | @DefaultValue("1, 2, 3, 4") |
| 202 | public int[] commaSeparated(); |
| 203 | |
| 204 | } |
| 205 | |
| 206 | public interface AlsoWrong extends Config { |
| 207 | |
| 208 | // will throw UnsupportedOperationException! |
| 209 | // @Separator and @TokenizerClass cannot be |
| 210 | // used together on method level. |
| 211 | @Separator(";") |
| 212 | @TokenizerClass(CustomDashTokenizer.class) |
| 213 | @DefaultValue("0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55") |
| 214 | public int[] conflictingAnnotationsOnMethodLevel(); |
| 215 | |
| 216 | } |
| 217 | ``` |
| 218 | |
| 219 | [unsupported-ex]: http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html |
| 220 | |
| 221 | But even though the following example contains a conflict on class level |
| 222 | (and should be considered a bug in the example), OWNER is able to resolve things |
| 223 | correctly on method level: |
| 224 | |
| 225 | ```java |
| 226 | |
| 227 | // @Separator and @TokenizerClass cannot be used together |
| 228 | // on class level. |
| 229 | @Separator(";") |
| 230 | @TokenizerClass(CustomDashTokenizer.class) |
| 231 | public interface WrongButItWorks extends Config { |
| 232 | |
| 233 | // but this overrides the class level annotations |
| 234 | // hence it will work! |
| 235 | @Separator(";") |
| 236 | @DefaultValue("1, 2, 3, 4") |
| 237 | public int[] commaSeparated(); |
| 238 | |
| 239 | } |
| 240 | ``` |
| 241 | |
| 242 | It is not recommended to have above wrong annotations setup: it is considered a bug in the code, and even if this setup |
| 243 | works at the moment, we may change this behavior in future. |
| 244 | |
| 245 | |
| 246 | The @ConverterClass annotation |
| 247 | ------------------------------ |
| 248 | |
| 249 | OWNER provides the |
| 250 | [`@ConverterClass`](http://owner.aeonbits.org/apidocs/latest/org/aeonbits/owner/Config.ConverterClass.html) |
| 251 | annotation that allows the user to specify a customized conversion logic implementing the |
| 252 | [`Converter`](http://owner.aeonbits.org/apidocs/latest/org/aeonbits/owner/Converter.html) interface. |
| 253 | |
| 254 | ```java |
| 255 | interface MyConfig extends Config { |
| 256 | @DefaultValue("foobar.com:8080") |
| 257 | @ConverterClass(ServerConverter.class) |
| 258 | Server server(); |
| 259 | |
| 260 | @DefaultValue( |
| 261 | "google.com, yahoo.com:8080, owner.aeonbits.org:4000") |
| 262 | @ConverterClass(ServerConverter.class) |
| 263 | Server[] servers(); |
| 264 | } |
| 265 | |
| 266 | class Server { |
| 267 | private final String name; |
| 268 | private final Integer port; |
| 269 | |
| 270 | public Server(String name, Integer port) { |
| 271 | this.name = name; |
| 272 | this.port = port; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | public class ServerConverter implements Converter<Server> { |
| 277 | public Server convert(Method targetMethod, String text) { |
| 278 | String[] split = text.split(":", -1); |
| 279 | String name = split[0]; |
| 280 | Integer port = 80; |
| 281 | if (split.length >= 2) |
| 282 | port = Integer.valueOf(split[1]); |
| 283 | return new Server(name, port); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | MyConfig cfg = ConfigFactory.create(MyConfig.class); |
| 288 | Server s = cfg.server(); // will return a single server |
| 289 | Server[] ss = cfg.servers(); // it works also with collections |
| 290 | ``` |
| 291 | |
| 292 | In the above example, when calling the method `servers()` that returns an array of Server objects, the ServerConverter |
| 293 | will be used several times to convert every single element. In any case the ServerConverter in the above example always |
| 294 | works with a single element. |
| 295 | |
| 296 | To see the complete test cases supported by owner see [ConverterClassTest] on GitHub. |
| 297 | |
| 298 | [ConverterClassTest]: https://github.com/lviggiano/owner/blob/master/owner/src/test/java/org/aeonbits/owner/typeconversion/ConverterClassTest.java |
| 299 | |
| 300 | All the types supported by OWNER |
| 301 | -------------------------------- |
| 302 | |
| 303 | But there is more. OWNER API supports automatic conversion for: |
| 304 | |
| 305 | 1. Primitive types: boolean, byte, short, integer, long, float, double. |
| 306 | 2. Enums (notice that the conversion is case sensitive, so FOO != foo or Foo). |
| 307 | 3. java.lang.String, of course (no conversion is needed). |
| 308 | 4. java.net.URL, java.net.URI. |
| 309 | 5. java.io.File (the character `~` will be expanded to `user.home` System Property). |
| 310 | 6. java.lang.Class (this can be useful, for instance, if you want to load the jdbc driver, or similar cases). |
| 311 | 7. Any instantiable class declaring a public constructor with a single argument of type `java.lang.String`. |
| 312 | 8. Any instantiable class declaring a public constructor with a single argument of type `java.lang.Object`. |
| 313 | 9. Any class declaring a public *static* method `valueOf(java.lang.String)` that returns an instance of itself. |
| 314 | 10. Any class for which you can register a [`PropertyEditor`][propedit] via |
| 315 | [`PropertyEditorManager.registerEditor()`][propeditmanager]. |
| 316 | (See [PropertyEditorTest] as an example). |
| 317 | 11. Any array having above types as elements. |
| 318 | 12. Any object that can be instantiated via `@ConverterClass` annotation explained before. |
| 319 | 13. Any Java Collections of all above types: Set, List, SortedSet or concrete implementations like LinkedHashSet or user |
| 320 | defined collections having a default no-arg constructor. [`Map`][Map] and sub-interfaces are not supported. |
| 321 | |
| 322 | If OWNER API cannot find any way to map your business object, you'll receive a [`UnsupportedOperationException`][unsupported-ex] |
| 323 | with some meaningful description to identify the problem as quickly as possible. |
| 324 | |
| 325 | You can also register your custom [`PropertyEditor`][propedit] to convert text properties into your business objects |
| 326 | using the static method [`PropertyEditorManager.registerEditor()`][propeditmanager]. |
| 327 | See also [`PropertyEditorSupport`][propeditsupport], it may be useful if you want to implement a `PropertyEditor`. |
| 328 | |
| 329 | [propeditmanager]: http://docs.oracle.com/javase/7/docs/api/java/beans/PropertyEditorManager.html#registerEditor |
| 330 | [propedit]: http://docs.oracle.com/javase/7/docs/api/java/beans/PropertyEditor.html |
| 331 | [propeditsupport]:http://docs.oracle.com/javase/7/docs/api/java/beans/PropertyEditorSupport.html |
| 332 | [PropertyEditorTest]:https://github.com/lviggiano/owner/blob/master/src/test/java/org/aeonbits/owner/editor/PropertyEditorTest.java |
| 333 | |
| 334 | Converter classes shipped with OWNER |
| 335 | ------------------------------------ |
| 336 | |
| 337 | Since specifying duration and byte size values in configuration files is very common, |
| 338 | OWNER ships with converter classes for these as well as some classes for the types themselves. |
| 339 | The code relies on Java 8 features and therefore, these classes are a part of the `owner-java8-extras` |
| 340 | module. Also, you have to specify the `@ConverterClass` annotation explicitly for these converters, they are not |
| 341 | applied automatically as is the case for the primitive (and more) types as described above. |
| 342 | |
| 343 | ### Duration |
| 344 | |
| 345 | For duration, the `DurationConverter` class is provided which converts configuration strings to |
| 346 | [`java.time.Duration`][duration]. |
| 347 | |
| 348 | [duration]: https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html |
| 349 | |
| 350 | Example: |
| 351 | |
| 352 | ```java |
| 353 | public class DurationConfig extends Config { |
| 354 | |
| 355 | @ConverterClass(DurationConverter.class) |
| 356 | @DefaultValue("10 ms") |
| 357 | Duration getTenMilliseconds(); |
| 358 | |
| 359 | |
| 360 | @ConverterClass(DurationConverter.class) |
| 361 | @DefaultValue("10d") |
| 362 | Duration getTenDays(); |
| 363 | |
| 364 | // The DurationConverter class also supports |
| 365 | // ISO 8601 time format as described in the |
| 366 | // JavaDoc for java.time.Duration. |
| 367 | @ConverterClass(DurationConverter.class) |
| 368 | @DefaultValue("PT15M") |
| 369 | Duration iso8601FifteenMinutes(); |
| 370 | } |
| 371 | ``` |
| 372 | |
| 373 | The suffixes supported by DurationConverter are: |
| 374 | |
| 375 | - `ns`, `nano`, `nanos`, `nanosecond`, `nanoseconds` |
| 376 | - `us`, `µs`, `micro`, `micros`, `microsecond`, `microseconds` |
| 377 | - `ms`, `milli`, `millis`, `millisecond`, `milliseconds` |
| 378 | - `s`, `second`, `seconds` |
| 379 | - `m`, `minute`, `minutes` |
| 380 | - `h`, `hour`, `hours` |
| 381 | - `d`, `day`, `days` |
| 382 | |
| 383 | ### Byte Size |
| 384 | |
| 385 | The Java API does not provide any classes to represent data sizes. Therefore, |
| 386 | OWNER provides this functionality with a set of classes in the |
| 387 | `org.aeonbits.owner.util.bytesize` package: `ByteSize` and `ByteSizeUnit`. |
| 388 | |
| 389 | The usage of these classes is best explained with an example: |
| 390 | |
| 391 | ```java |
| 392 | import org.aeonbits.owner.util.bytesize.*; |
| 393 | |
| 394 | [...] |
| 395 | |
| 396 | ByteSize oneByte = new ByteSize(1, ByteSizeUnit.BYTES); |
| 397 | ByteSize oneMegaByte = new ByteSize(1, ByteSizeUnit.MEGABYTES); |
| 398 | |
| 399 | // Units can be converted |
| 400 | ByteSize mbAsGb = oneMegaByte.convertTo(ByteSizeUnit.GIGABYTES); |
| 401 | |
| 402 | // Both IEC and SI units are supported |
| 403 | ByteSize mbAsGiB = oneMegaByte.convertTo(ByteSizeUnit.GIBIBYTES); |
| 404 | |
| 405 | // Get the number of bytes a ByteSize represents as a long |
| 406 | long oneMegaByteAsLong = oneMegaByte.getBytesAsLong(); |
| 407 | ``` |
| 408 | |
| 409 | For converting configuration strings into the `ByteSize` type, the |
| 410 | `ByteSizeConverter` class is provided. |
| 411 | |
| 412 | Example: |
| 413 | |
| 414 | ```java |
| 415 | public interface ByteSizeConfig extends Config { |
| 416 | @ConverterClass(ByteSizeConverter.class) |
| 417 | @DefaultValue("10 byte") |
| 418 | ByteSize singular10byteWithSpace(); |
| 419 | |
| 420 | @ConverterClass(ByteSizeConverter.class) |
| 421 | @DefaultValue("10byte") |
| 422 | ByteSize singular10byteWithoutSpace(); |
| 423 | |
| 424 | @ConverterClass(ByteSizeConverter.class) |
| 425 | @DefaultValue("10 bytes") |
| 426 | ByteSize plural10byte(); |
| 427 | |
| 428 | @ConverterClass(ByteSizeConverter.class) |
| 429 | @DefaultValue("10m") |
| 430 | ByteSize short10mebibytes(); |
| 431 | |
| 432 | @ConverterClass(ByteSizeConverter.class) |
| 433 | @DefaultValue("10mi") |
| 434 | ByteSize medium10mebibytes(); |
| 435 | |
| 436 | @ConverterClass(ByteSizeConverter.class) |
| 437 | @DefaultValue("10mib") |
| 438 | ByteSize long10mebibytes(); |
| 439 | |
| 440 | @ConverterClass(ByteSizeConverter.class) |
| 441 | @DefaultValue("10 megabytes") |
| 442 | ByteSize full10megabytes(); |
| 443 | } |
| 444 | ``` |
| 445 | |
| 446 | The suffixes supported by ByteSizeConverter are: |
| 447 | |
| 448 | - `byte`, `bytes`, `b` |
| 449 | - `kilobyte`, `kilobytes`, `k`, `ki`, `kib` |
| 450 | - `kibibyte`, `kibibytes`, `kb` |
| 451 | - `megabyte`, `megabytes`, `m`, `mi`, `mib` |
| 452 | - `mebibyte`, `mebibytes`, `mb` |
| 453 | - `gigabyte`, `gigabytes`, `g`, `gi`, `gib` |
| 454 | - `gibibyte`, `gibibytes`, `gb` |
| 455 | - `terabyte`, `terabytes`, `t`, `ti`, `tib` |
| 456 | - `tebibyte`, `tebibytes`, `tb` |
| 457 | - `petabyte`, `petabytes`, `p`, `pi`, `pib` |
| 458 | - `pebibyte`, `pebibytes`, `pb` |
| 459 | - `exabyte`, `exabytes`, `e`, `ei`, `eib` |
| 460 | - `exbibyte`, `exbibytes`, `eb` |
| 461 | - `zettabyte`, `zettabytes`, `z`, `zi`, `zib` |
| 462 | - `zebibyte`, `zebibytes`, `zb` |
| 463 | - `yottabyte`, `yottabytes`, `y`, `yi`, `yib` |
| 464 | - `yobibyte`, `yobibytes`, `yb` |