1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package br.com.arsmachina.tapestrycrud.services.impl;
16
17 import java.io.Serializable;
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import org.apache.tapestry5.PrimaryKeyEncoder;
22 import org.apache.tapestry5.ioc.util.StrategyRegistry;
23
24 import br.com.arsmachina.tapestrycrud.factory.PrimaryKeyEncoderFactory;
25 import br.com.arsmachina.tapestrycrud.services.EncoderSource;
26 import br.com.arsmachina.tapestrycrud.services.PrimaryKeyEncoderSource;
27
28
29
30
31
32
33 public class PrimaryKeyEncoderSourceImpl implements PrimaryKeyEncoderSource {
34
35 @SuppressWarnings("unchecked")
36 final private StrategyRegistry<PrimaryKeyEncoder> registry;
37
38 final private EncoderSource encoderSource;
39
40 final private PrimaryKeyEncoderFactory primaryKeyEncoderFactory;
41
42 @SuppressWarnings("unchecked")
43 final private Map<Class, PrimaryKeyEncoder> additionalEncoders = new HashMap<Class, PrimaryKeyEncoder>();
44
45
46
47
48
49
50
51
52 @SuppressWarnings("unchecked")
53 public PrimaryKeyEncoderSourceImpl(Map<Class, PrimaryKeyEncoder> registrations,
54 EncoderSource encoderSource, PrimaryKeyEncoderFactory primaryKeyEncoderFactory) {
55
56 if (registrations == null) {
57 throw new IllegalArgumentException("Parameter registrations cannot be null");
58 }
59
60 if (encoderSource == null) {
61 throw new IllegalArgumentException("Parameter encoderSource cannot be null");
62 }
63
64 if (primaryKeyEncoderFactory == null) {
65 throw new IllegalArgumentException("Parameter primaryKeyEncoderFactory cannot be null");
66 }
67
68 registry = StrategyRegistry.newInstance(PrimaryKeyEncoder.class, registrations, true);
69
70 this.encoderSource = encoderSource;
71 this.primaryKeyEncoderFactory = primaryKeyEncoderFactory;
72
73 }
74
75
76
77
78 @SuppressWarnings("unchecked")
79 public <T, K extends Serializable> PrimaryKeyEncoder<K, T> get(Class<T> clasz) {
80
81 PrimaryKeyEncoder<K, T> encoder = registry.get(clasz);
82
83 if (encoder == null) {
84 encoder = encoderSource.get(clasz);
85 }
86
87 if (encoder == null) {
88
89 encoder = additionalEncoders.get(clasz);
90
91 if (encoder == null) {
92
93 encoder = primaryKeyEncoderFactory.build(clasz);
94
95 if (encoder != null) {
96 additionalEncoders.put(clasz, encoder);
97 }
98
99 }
100
101 }
102
103 if (encoder == null) {
104 throw new IllegalArgumentException(
105 "There is no PrimaryKeyEncoder configured for class " + clasz.getName());
106 }
107
108 return encoder;
109
110 }
111
112
113 }