1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.validator;
23
24 import java.io.Serializable;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.Map;
28
29
30
31
32
33
34
35 public abstract class AbstractNuitonValidatorProvider implements NuitonValidatorProvider {
36
37 protected Map<ModelEntry<?>, NuitonValidatorModel<?>> models;
38
39 protected final String name;
40
41 public AbstractNuitonValidatorProvider(String name) {
42 this.name = name;
43 }
44
45 @Override
46 public <O> NuitonValidatorModel<O> getModel(Class<O> type, String context, NuitonValidatorScope... scopes) {
47 ModelEntry<O> key = ModelEntry.createModelEntry(type, context, scopes);
48
49 @SuppressWarnings({"unchecked"})
50 NuitonValidatorModel<O> model = (NuitonValidatorModel<O>) getModels().get(key);
51
52 if (model == null) {
53 model = newModel(type, context, scopes);
54 }
55 return model;
56 }
57
58 protected Map<ModelEntry<?>, NuitonValidatorModel<?>> getModels() {
59 if (models == null) {
60 models = new HashMap<ModelEntry<?>, NuitonValidatorModel<?>>();
61 }
62 return models;
63 }
64
65 protected static class ModelEntry<O> implements Serializable {
66
67 private static final long serialVersionUID = 1L;
68
69 protected final Class<O> type;
70
71 protected final String context;
72
73 protected final NuitonValidatorScope[] scopes;
74
75 public static <O> ModelEntry<O> createModelEntry(Class<O> type,
76 String context,
77 NuitonValidatorScope... scopes) {
78 return new ModelEntry<O>(type, context, scopes);
79 }
80
81 protected ModelEntry(Class<O> type,
82 String context,
83 NuitonValidatorScope... scopes) {
84 this.type = type;
85 this.context = context;
86 this.scopes = scopes == null ? NuitonValidatorScope.values() : scopes;
87 }
88
89 @Override
90 public boolean equals(Object o) {
91 if (this == o) return true;
92 if (!(o instanceof ModelEntry)) return false;
93
94 ModelEntry<?> that = (ModelEntry<?>) o;
95
96 if (context != null ? !context.equals(that.context) : that.context != null)
97 return false;
98 if (!Arrays.equals(scopes, that.scopes)) return false;
99 return type.equals(that.type);
100
101 }
102
103 @Override
104 public int hashCode() {
105 int result = type.hashCode();
106 result = 31 * result + (context != null ? context.hashCode() : 0);
107 result = 31 * result + Arrays.hashCode(scopes);
108 return result;
109 }
110 }
111
112 @Override
113 public String getName() {
114 return name;
115 }
116
117 }