1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.cling.invoker;
20
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Optional;
25
26 import org.apache.maven.api.services.Lookup;
27 import org.apache.maven.api.services.LookupException;
28
29 import static java.util.Objects.requireNonNull;
30
31
32
33
34 public class ProtoLookup implements Lookup {
35 private final Map<Class<?>, Object> components;
36
37 private ProtoLookup(Map<Class<?>, Object> components) {
38 this.components = components;
39 }
40
41 @Override
42 public <T> T lookup(Class<T> type) {
43 Optional<T> optional = lookupOptional(type);
44 if (optional.isPresent()) {
45 return optional.get();
46 } else {
47 throw new LookupException("No mapping for key: " + type.getName());
48 }
49 }
50
51 @Override
52 public <T> T lookup(Class<T> type, String name) {
53 return lookup(type);
54 }
55
56 @Override
57 public <T> Optional<T> lookupOptional(Class<T> type) {
58 return Optional.ofNullable(type.cast(components.get(type)));
59 }
60
61 @Override
62 public <T> Optional<T> lookupOptional(Class<T> type, String name) {
63 return lookupOptional(type);
64 }
65
66 @Override
67 public <T> List<T> lookupList(Class<T> type) {
68 return List.of();
69 }
70
71 @Override
72 public <T> Map<String, T> lookupMap(Class<T> type) {
73 return Map.of();
74 }
75
76 public static Builder builder() {
77 return new Builder();
78 }
79
80 public static class Builder {
81 private final Map<Class<?>, Object> components = new HashMap<>();
82
83 public ProtoLookup build() {
84 return new ProtoLookup(components);
85 }
86
87 public <T> Builder addMapping(Class<T> type, T component) {
88 requireNonNull(type, "type");
89 requireNonNull(component, "component");
90 if (components.put(type, component) != null) {
91 throw new IllegalStateException("Duplicate mapping for type: " + type.getName());
92 }
93 return this;
94 }
95 }
96 }