Include name of missing option in exception
[rhynodge.git] / src / main / java / net / pterodactylus / util / envopt / Parser.java
1 package net.pterodactylus.util.envopt;
2
3 import java.lang.reflect.Field;
4 import java.util.Optional;
5 import java.util.function.Supplier;
6
7 /**
8  * Parses values from an {@link Environment} into {@link Option}-annotated fields of an object.
9  *
10  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
11  */
12 public class Parser {
13
14         private final Environment environment;
15
16         public Parser(Environment environment) {
17                 this.environment = environment;
18         }
19
20         public <T> T parseEnvironment(Supplier<T> optionsObjectSupplier) {
21                 T optionsObject = optionsObjectSupplier.get();
22                 Class<?> optionsClass = optionsObject.getClass();
23                 for (Field field : optionsClass.getDeclaredFields()) {
24                         Option[] options = field.getAnnotationsByType(Option.class);
25                         if (options.length == 0) {
26                                 continue;
27                         }
28                         for (Option option : options) {
29                                 String variableName = option.name();
30                                 Optional<String> value = environment.getValue(variableName);
31                                 if (option.required() && !value.isPresent()) {
32                                         throw new RequiredOptionIsMissing(option.name());
33                                 }
34                                 field.setAccessible(true);
35                                 try {
36                                         field.set(optionsObject, value.orElse(null));
37                                 } catch (IllegalAccessException iae1) {
38                                         /* swallow. */
39                                 }
40                         }
41                 }
42                 return optionsObject;
43         }
44
45         public static Parser fromSystemEnvironment() {
46                 return new Parser(new SystemEnvironment());
47         }
48
49         public static class RequiredOptionIsMissing extends RuntimeException {
50
51                 public RequiredOptionIsMissing(String message) {
52                         super(message);
53                 }
54
55         }
56
57 }