1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jadira.bindings.core.spring;
17
18 import java.lang.annotation.Annotation;
19 import java.util.HashSet;
20 import java.util.Set;
21
22 import org.jadira.bindings.core.annotation.BindingScope;
23 import org.jadira.bindings.core.annotation.DefaultBinding;
24 import org.jadira.bindings.core.binder.BasicBinder;
25 import org.jadira.bindings.core.binder.ConverterKey;
26 import org.springframework.core.convert.TypeDescriptor;
27 import org.springframework.core.convert.converter.ConditionalGenericConverter;
28
29
30
31
32
33 public class BindingConverter implements ConditionalGenericConverter {
34
35 private static final BasicBinder BINDING = new BasicBinder();
36
37
38
39
40
41 public Set<ConvertiblePair> getConvertibleTypes() {
42
43 Set<ConvertiblePair> result = new HashSet<ConvertiblePair>();
44
45 Iterable<ConverterKey<?,?>> entries = BINDING.getConverterEntries();
46 for (ConverterKey<?,?> next : entries) {
47 result.add(new ConvertiblePair(next.getInputClass(), next.getOutputClass()));
48 }
49
50 return result;
51 }
52
53
54
55
56
57 public Object convert(Object object, TypeDescriptor sourceType, TypeDescriptor targetType) {
58
59 final Object result;
60 result = BINDING.convertTo(object.getClass(), targetType.getObjectType(), object, matchAnnotationToScope(targetType.getAnnotations()));
61 return result;
62 }
63
64
65
66
67 public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
68
69 try {
70 BINDING.findConverter(sourceType.getObjectType(), targetType.getObjectType(), matchAnnotationToScope(targetType.getAnnotations()));
71 return true;
72 } catch (IllegalStateException e) {
73 return false;
74 }
75 }
76
77
78
79
80
81
82 private <T> Class<? extends Annotation> matchAnnotationToScope(Annotation[] annotations) {
83
84 for (Annotation next : annotations) {
85 Class<? extends Annotation> nextType = next.annotationType();
86 if (nextType.getAnnotation(BindingScope.class) != null) {
87 return nextType;
88 }
89 }
90 return DefaultBinding.class;
91 }
92 }