1 package org.nuiton.eugene.models.extension.tagvalue.provider;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import com.google.common.base.Optional;
26 import com.google.common.collect.ImmutableSet;
27 import org.nuiton.eugene.models.extension.tagvalue.MismatchTagValueTargetException;
28 import org.nuiton.eugene.models.extension.tagvalue.TagValueMetadata;
29 import org.nuiton.eugene.models.extension.tagvalue.TagValueNotFoundException;
30 import org.nuiton.eugene.models.extension.tagvalue.matcher.EqualsTagValueNameMatcher;
31 import org.nuiton.eugene.models.extension.tagvalue.matcher.StartsWithTagNameMatcher;
32 import org.nuiton.eugene.models.extension.tagvalue.matcher.TagValueDefinitionMatcher;
33
34 import java.util.LinkedHashSet;
35 import java.util.Set;
36
37
38
39
40
41
42 public abstract class DefaultTagValueMetadatasProvider implements TagValueMetadatasProvider {
43
44 protected final Set<TagValueMetadata> tagValues;
45 protected final Set<TagValueDefinitionMatcher> matcher;
46
47 public DefaultTagValueMetadatasProvider(TagValueMetadata... tagValues) {
48 this.tagValues = ImmutableSet.copyOf(tagValues);
49 this.matcher = ImmutableSet.of(
50 new EqualsTagValueNameMatcher(getDefinitionForMatcher(EqualsTagValueNameMatcher.class)),
51 new StartsWithTagNameMatcher(getDefinitionForMatcher(StartsWithTagNameMatcher.class)));
52 }
53
54 @Override
55 public Set<TagValueMetadata> getTagValues() {
56 return tagValues;
57 }
58
59 @Override
60 public void validate(String tagValueName, Class<?> type) throws TagValueNotFoundException, MismatchTagValueTargetException {
61 Optional<TagValueMetadata> def = getTagValue(tagValueName);
62
63 if (!def.isPresent()) {
64 throw new TagValueNotFoundException();
65 }
66
67 boolean valid = false;
68
69 for (Class<?> target : def.get().getTargets()) {
70 if (target.equals(type) || target.isAssignableFrom(type)) {
71
72
73 valid = true;
74 break;
75 }
76 }
77
78 if (!valid) {
79 throw new MismatchTagValueTargetException();
80 }
81 }
82
83 @Override
84 public Optional<TagValueMetadata> getTagValue(String tagValueName) {
85 for (TagValueDefinitionMatcher tagValueDefinitionMatcher : matcher) {
86 TagValueMetadata def = tagValueDefinitionMatcher.match(tagValueName);
87 if (def != null)
88 return Optional.of(def);
89 }
90 return Optional.absent();
91 }
92
93 protected <M extends TagValueDefinitionMatcher> Set<TagValueMetadata> getDefinitionForMatcher(Class<M> matcherType) {
94 Set<TagValueMetadata> result = new LinkedHashSet<>();
95 for (TagValueMetadata entry : getTagValues()) {
96 if (matcherType.equals(entry.getMatcherClass())) {
97 result.add(entry);
98 }
99 }
100 return result;
101 }
102
103 }