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.util.Map;
18
19
20 import org.apache.tapestry5.ioc.util.StrategyRegistry;
21
22 import br.com.arsmachina.tapestrycrud.encoder.LabelEncoder;
23 import br.com.arsmachina.tapestrycrud.services.EncoderSource;
24 import br.com.arsmachina.tapestrycrud.services.LabelEncoderSource;
25
26
27
28
29
30
31 public class LabelEncoderSourceImpl implements LabelEncoderSource {
32
33 final private static LabelEncoder<Object> DEFAULT_ENCODER = new ToStringEncoder();
34
35 @SuppressWarnings("unchecked")
36 final private StrategyRegistry<LabelEncoder> registry;
37
38 final private EncoderSource encoderSource;
39
40
41
42
43
44
45 @SuppressWarnings("unchecked")
46 public LabelEncoderSourceImpl(Map<Class, LabelEncoder> registrations,
47 EncoderSource encoderSource) {
48
49 if (registrations == null) {
50 throw new IllegalArgumentException("Parameter registrations cannot be null");
51 }
52
53 if (encoderSource == null) {
54 throw new IllegalArgumentException("Parameter encoderSource cannot be null");
55 }
56
57 registry = StrategyRegistry.newInstance(LabelEncoder.class, registrations, true);
58
59 this.encoderSource = encoderSource;
60
61 }
62
63
64
65
66 @SuppressWarnings("unchecked")
67 public <T> LabelEncoder<T> get(Class<T> clasz) {
68
69 LabelEncoder<T> encoder = registry.get(clasz);
70
71 if (encoder == null) {
72 encoder = encoderSource.get(clasz);
73 }
74
75 if (encoder == null) {
76 encoder = (LabelEncoder<T>) DEFAULT_ENCODER;
77 }
78
79 return encoder;
80
81 }
82
83 final private static class ToStringEncoder implements LabelEncoder<Object> {
84
85 public String toLabel(Object object) {
86 return object.toString();
87 }
88
89 }
90
91 }