1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.commons.core;
17
18 import org.openehealth.ipf.commons.core.config.TypeConverter;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 import javax.xml.bind.annotation.XmlTransient;
23 import java.util.HashMap;
24 import java.util.Map;
25
26
27
28
29
30 @XmlTransient
31 public class ContentMap {
32 private static transient Logger LOG = LoggerFactory.getLogger(ContentMap.class);
33
34
35 private transient final Map<Class<?>, Object> map = new HashMap<>();
36
37 private static transient TypeConverter conversionService;
38
39
40
41
42
43
44
45
46
47
48
49
50
51 @SuppressWarnings("unchecked")
52 public <T> T getContent(Class<T> targetType) {
53 T result = (T) map.get(targetType);
54 if (result != null) {
55 LOG.debug("Return existing content of type " + targetType);
56 return result;
57 }
58
59 if (conversionService == null) {
60 LOG.debug("Conversion service not configured");
61 return null;
62 }
63
64 synchronized (map) {
65
66 for (Class<?> sourceType : map.keySet()) {
67 if (conversionService.canConvert(sourceType, targetType)) {
68 result = conversionService.convert(map.get(sourceType), targetType);
69 if (result != null) {
70 LOG.debug("Successfully generated " + targetType + " from " + sourceType);
71 setContent(targetType, result);
72 return result;
73 }
74 }
75 }
76 }
77
78 LOG.debug("Could not find appropriate converter for the target type " + targetType);
79 return null;
80 }
81
82
83
84
85
86
87
88
89
90
91
92
93 @SuppressWarnings("unchecked")
94 public <T> T setContent(Class<T> key, T content) {
95 if (key == null) throw new IllegalArgumentException("content type must be provided");
96 if (content == null) throw new IllegalArgumentException("null content is not allowed");
97 synchronized (map) {
98 return (T) map.put(key, content);
99 }
100 }
101
102
103
104
105
106
107
108
109
110
111
112
113 @SuppressWarnings("unchecked")
114 public <T> T removeContent(Class<T> key) {
115 synchronized (map) {
116 return (T) map.remove(key);
117 }
118 }
119
120
121
122
123
124
125 public boolean hasContent(Class<?> key) {
126 return map.containsKey(key);
127 }
128
129
130
131
132
133 public int getContentsCount() {
134 return map.size();
135 }
136
137
138
139
140
141 public static TypeConverter getConversionService() {
142 return conversionService;
143 }
144
145
146
147
148
149 public static void setConversionService(TypeConverter conversionService) {
150 ContentMap.conversionService = conversionService;
151 }
152
153 }