1
|
/**
|
2
|
* Copyright (C) 2009 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
package eu.etaxonomy.cdm.persistence.dao.initializer;
|
10
|
|
11
|
import java.beans.PropertyDescriptor;
|
12
|
import java.lang.reflect.InvocationTargetException;
|
13
|
import java.lang.reflect.Method;
|
14
|
import java.lang.reflect.ParameterizedType;
|
15
|
import java.lang.reflect.Type;
|
16
|
import java.util.Collection;
|
17
|
import java.util.Collections;
|
18
|
import java.util.HashSet;
|
19
|
import java.util.List;
|
20
|
import java.util.Map;
|
21
|
import java.util.Set;
|
22
|
|
23
|
import javax.persistence.Transient;
|
24
|
|
25
|
import org.apache.commons.beanutils.PropertyUtils;
|
26
|
import org.apache.commons.lang.StringUtils;
|
27
|
import org.apache.log4j.Logger;
|
28
|
import org.springframework.beans.factory.annotation.Autowired;
|
29
|
|
30
|
import eu.etaxonomy.cdm.model.common.CdmBase;
|
31
|
import eu.etaxonomy.cdm.persistence.dao.IMethodCache;
|
32
|
|
33
|
/**
|
34
|
* @author a.kohlbecker
|
35
|
* @since 26.03.2009
|
36
|
*
|
37
|
*/
|
38
|
public abstract class AbstractBeanInitializer<CDM extends CdmBase> implements IBeanInitializer{
|
39
|
|
40
|
public static final Logger logger = Logger.getLogger(AbstractBeanInitializer.class);
|
41
|
|
42
|
@Autowired
|
43
|
private IMethodCache methodCache;
|
44
|
|
45
|
private Map<Class<CDM>, AutoPropertyInitializer<CDM>> beanAutoInitializers = null;
|
46
|
|
47
|
/**
|
48
|
* @param beanAutoInitializers the beanAutoInitializers to set
|
49
|
*/
|
50
|
public void setBeanAutoInitializers(Map<Class<CDM>, AutoPropertyInitializer<CDM>> beanAutoInitializers) {
|
51
|
this.beanAutoInitializers = beanAutoInitializers;
|
52
|
}
|
53
|
|
54
|
/**
|
55
|
* @return the beanAutoInitializers
|
56
|
*/
|
57
|
public Map<Class<CDM>, AutoPropertyInitializer<CDM>> getBeanAutoInitializers() {
|
58
|
return beanAutoInitializers;
|
59
|
}
|
60
|
|
61
|
@Override
|
62
|
public abstract Object initializeInstance(Object proxy);
|
63
|
|
64
|
@Override
|
65
|
public void load(Object bean) {
|
66
|
initializeBean(bean, true, false);
|
67
|
}
|
68
|
|
69
|
@Override
|
70
|
public void loadFully(Object bean) {
|
71
|
initializeBean(bean, true, true);
|
72
|
}
|
73
|
|
74
|
/**
|
75
|
* Initializes all *toOne relations of the given bean and all *toMany
|
76
|
* relations, depending on the state of the boolean parameters
|
77
|
* <code>cdmEntities</code> and <code>collections</code>
|
78
|
*
|
79
|
* @param bean
|
80
|
* the bean to initialize
|
81
|
* @param cdmEntities
|
82
|
* initialize all *toOne relations to cdm entities
|
83
|
* @param collections
|
84
|
* initialize all *toMany relations
|
85
|
*/
|
86
|
public void initializeBean(Object bean, boolean cdmEntities, boolean collections){
|
87
|
|
88
|
if(logger.isDebugEnabled()){logger.debug(">> starting wildcard initializeBean() of " + bean + " ;class:" + bean.getClass().getSimpleName()); }
|
89
|
Set<Class<?>> restrictions = new HashSet<>();
|
90
|
if(cdmEntities){
|
91
|
restrictions.add(CdmBase.class);
|
92
|
}
|
93
|
if(collections){
|
94
|
restrictions.add(Collection.class);
|
95
|
}
|
96
|
Set<PropertyDescriptor> props = getProperties(bean, restrictions);
|
97
|
for(PropertyDescriptor propertyDescriptor : props){
|
98
|
try {
|
99
|
|
100
|
invokeInitialization(bean, propertyDescriptor);
|
101
|
|
102
|
} catch (IllegalAccessException e) {
|
103
|
logger.error("Illegal access on property " + propertyDescriptor.getName());
|
104
|
} catch (InvocationTargetException e) {
|
105
|
logger.info("Cannot invoke property " + propertyDescriptor.getName() + " not found");
|
106
|
} catch (NoSuchMethodException e) {
|
107
|
logger.info("Property " + propertyDescriptor.getName() + " not found");
|
108
|
}
|
109
|
}
|
110
|
if(logger.isDebugEnabled()){
|
111
|
logger.debug(" completed initializeBean() of " + bean);
|
112
|
}
|
113
|
}
|
114
|
|
115
|
//TODO optimize algorithm ..
|
116
|
@Override
|
117
|
public void initialize(Object bean, List<String> propertyPaths) {
|
118
|
|
119
|
invokePropertyAutoInitializers(bean);
|
120
|
|
121
|
if(propertyPaths == null){
|
122
|
return;
|
123
|
}
|
124
|
|
125
|
Collections.sort(propertyPaths);
|
126
|
//long startTime1 = System.nanoTime();
|
127
|
if(logger.isDebugEnabled()){
|
128
|
logger.debug(">> starting to initialize " + bean + " ;class:" + bean.getClass().getSimpleName());
|
129
|
}
|
130
|
for(String propPath : propertyPaths){
|
131
|
initializePropertyPath(bean, propPath);
|
132
|
}
|
133
|
//long estimatedTime1 = System.nanoTime() - startTime1;
|
134
|
//System.err.println(".");
|
135
|
//long startTime2 = System.nanoTime();
|
136
|
//for(String propPath : propertyPaths){
|
137
|
// initializePropertyPath(bean, propPath);
|
138
|
//}
|
139
|
//long estimatedTime2 = System.nanoTime() - startTime2;
|
140
|
//System.err.println("first pas: "+estimatedTime1+" ns; second pas: "+estimatedTime2+ " ns");
|
141
|
if(logger.isDebugEnabled()){
|
142
|
logger.debug(" Completed initialization of " + bean);
|
143
|
}
|
144
|
|
145
|
}
|
146
|
|
147
|
@Override
|
148
|
public <C extends Collection<?>> C initializeAll(C beanList, List<String> propertyPaths) {
|
149
|
if(propertyPaths != null){
|
150
|
for(Object bean : beanList){
|
151
|
initialize(bean, propertyPaths);
|
152
|
}
|
153
|
}
|
154
|
return beanList;
|
155
|
}
|
156
|
|
157
|
/**
|
158
|
* Initializes the given single <code>propPath</code> String.
|
159
|
*
|
160
|
* @param bean
|
161
|
* @param propPath
|
162
|
*/
|
163
|
//changed form private to protected (AM)
|
164
|
protected void initializePropertyPath(Object bean, String propPath) {
|
165
|
if(logger.isDebugEnabled()){
|
166
|
logger.debug("processing " + propPath);
|
167
|
}
|
168
|
|
169
|
|
170
|
// [1]
|
171
|
// if propPath only contains a wildcard (* or $)
|
172
|
// => do a batch initialization of *toOne or *toMany relations
|
173
|
if(propPath.equals(LOAD_2ONE_WILDCARD)){
|
174
|
if(Collection.class.isAssignableFrom(bean.getClass())){
|
175
|
initializeAllEntries((Collection)bean, true, false);
|
176
|
} else if(Map.class.isAssignableFrom(bean.getClass())) {
|
177
|
initializeAllEntries(((Map)bean).values(), true, false);
|
178
|
} else{
|
179
|
initializeBean(bean, true, false);
|
180
|
}
|
181
|
} else if(propPath.equals(LOAD_2ONE_2MANY_WILDCARD)){
|
182
|
if(Collection.class.isAssignableFrom(bean.getClass())){
|
183
|
initializeAllEntries((Collection)bean, true, true);
|
184
|
} else if(Map.class.isAssignableFrom(bean.getClass())) {
|
185
|
initializeAllEntries(((Map)bean).values(), true, true);
|
186
|
} else {
|
187
|
initializeBean(bean, true, true);
|
188
|
}
|
189
|
} else {
|
190
|
// [2]
|
191
|
// propPath contains either a single field or a nested path
|
192
|
|
193
|
// split next path token off and keep the remaining as nestedPath
|
194
|
String property;
|
195
|
String nestedPath = null;
|
196
|
int pos;
|
197
|
if((pos = propPath.indexOf('.')) > 0){
|
198
|
nestedPath = propPath.substring(pos + 1);
|
199
|
property = propPath.substring(0, pos);
|
200
|
} else {
|
201
|
property = propPath;
|
202
|
}
|
203
|
|
204
|
// is the property indexed?
|
205
|
Integer index = null;
|
206
|
if((pos = property.indexOf('[')) > 0){
|
207
|
String indexString = property.substring(pos + 1, property.indexOf(']'));
|
208
|
index = Integer.valueOf(indexString);
|
209
|
property = property.substring(0, pos);
|
210
|
}
|
211
|
|
212
|
try {
|
213
|
//Class targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(bean); // used for debugging
|
214
|
|
215
|
// [2.a] initialize the bean named by property
|
216
|
|
217
|
PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean, property);
|
218
|
Object unwrappedPropertyBean = invokeInitialization(bean, propertyDescriptor);
|
219
|
|
220
|
// [2.b]
|
221
|
// recurse into nested properties
|
222
|
if(unwrappedPropertyBean != null && nestedPath != null){
|
223
|
if (Collection.class.isAssignableFrom(unwrappedPropertyBean.getClass())) {
|
224
|
// nested collection
|
225
|
int i = 0;
|
226
|
for (Object entrybean : (Collection<?>) unwrappedPropertyBean) {
|
227
|
if(index == null){
|
228
|
initializePropertyPath(entrybean, nestedPath);
|
229
|
} else if(index.equals(i)){
|
230
|
initializePropertyPath(entrybean, nestedPath);
|
231
|
break;
|
232
|
}
|
233
|
i++;
|
234
|
}
|
235
|
} else if(Map.class.isAssignableFrom(unwrappedPropertyBean.getClass())) {
|
236
|
// nested map
|
237
|
int i = 0;
|
238
|
for (Object entrybean : ((Map) unwrappedPropertyBean).values()) {
|
239
|
if(index == null){
|
240
|
initializePropertyPath(entrybean, nestedPath);
|
241
|
} else if(index.equals(i)){
|
242
|
initializePropertyPath(entrybean, nestedPath);
|
243
|
break;
|
244
|
}
|
245
|
i++;
|
246
|
}
|
247
|
}else {
|
248
|
// nested bean
|
249
|
initializePropertyPath(unwrappedPropertyBean, nestedPath);
|
250
|
setProperty(bean, property, unwrappedPropertyBean);
|
251
|
}
|
252
|
}
|
253
|
|
254
|
} catch (IllegalAccessException e) {
|
255
|
logger.error("Illegal access on property " + property);
|
256
|
} catch (InvocationTargetException e) {
|
257
|
logger.error("Cannot invoke property " + property + " not found");
|
258
|
} catch (NoSuchMethodException e) {
|
259
|
logger.info("Property " + property + " not found");
|
260
|
}
|
261
|
}
|
262
|
}
|
263
|
|
264
|
/**
|
265
|
* Initializes the property of the given bean and returns the bean which is returned be that property.
|
266
|
*
|
267
|
* @param bean
|
268
|
* @param propertyDescriptor
|
269
|
* @return
|
270
|
* @throws IllegalAccessException
|
271
|
* @throws InvocationTargetException
|
272
|
* @throws NoSuchMethodException
|
273
|
*/
|
274
|
protected Object invokeInitialization(Object bean, PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
|
275
|
|
276
|
if(propertyDescriptor == null || bean == null){
|
277
|
return null;
|
278
|
}
|
279
|
|
280
|
// (1)
|
281
|
// initialialization of the bean
|
282
|
//
|
283
|
Object propertyProxy = PropertyUtils.getProperty( bean, propertyDescriptor.getName());
|
284
|
Object propertyBean = initializeInstance(propertyProxy);
|
285
|
|
286
|
if(propertyBean != null){
|
287
|
// (2)
|
288
|
// auto initialialization of sub properties
|
289
|
//
|
290
|
if(CdmBase.class.isAssignableFrom(propertyBean.getClass())){
|
291
|
|
292
|
// initialization of a single bean
|
293
|
CdmBase cdmBaseBean = (CdmBase)propertyBean;
|
294
|
invokePropertyAutoInitializers(cdmBaseBean);
|
295
|
|
296
|
} else if(Collection.class.isAssignableFrom(propertyBean.getClass()) ||
|
297
|
Map.class.isAssignableFrom(propertyBean.getClass()) ) {
|
298
|
|
299
|
// it is a collection or map
|
300
|
Method readMethod = propertyDescriptor.getReadMethod();
|
301
|
Type genericReturnType = readMethod.getGenericReturnType();
|
302
|
|
303
|
if(genericReturnType instanceof ParameterizedType){
|
304
|
ParameterizedType type = (ParameterizedType) genericReturnType;
|
305
|
Type[] typeArguments = type.getActualTypeArguments();
|
306
|
|
307
|
if(typeArguments.length > 0
|
308
|
&& typeArguments[0] instanceof Class<?>
|
309
|
&& CdmBase.class.isAssignableFrom((Class<?>) typeArguments[0])){
|
310
|
|
311
|
if(Collection.class.isAssignableFrom((Class<?>) type.getRawType())){
|
312
|
for(CdmBase entry : ((Collection<CdmBase>)propertyBean)){
|
313
|
invokePropertyAutoInitializers(entry);
|
314
|
}
|
315
|
}
|
316
|
}
|
317
|
|
318
|
}
|
319
|
}
|
320
|
}
|
321
|
|
322
|
return propertyBean;
|
323
|
}
|
324
|
|
325
|
/**
|
326
|
* @param beanClass
|
327
|
* @param bean
|
328
|
* @return
|
329
|
*/
|
330
|
protected final void invokePropertyAutoInitializers(Object bean) {
|
331
|
|
332
|
if(beanAutoInitializers == null || bean == null){
|
333
|
return;
|
334
|
}
|
335
|
if(!CdmBase.class.isAssignableFrom(bean.getClass())){
|
336
|
return;
|
337
|
}
|
338
|
CdmBase cdmBaseBean = (CdmBase)bean;
|
339
|
for(Class<? extends CdmBase> superClass : beanAutoInitializers.keySet()){
|
340
|
if(superClass.isAssignableFrom(bean.getClass())){
|
341
|
beanAutoInitializers.get(superClass).initialize((CDM)cdmBaseBean);
|
342
|
}
|
343
|
}
|
344
|
}
|
345
|
|
346
|
protected void setProperty(Object object, String property, Object value){
|
347
|
Method method = methodCache.getMethod(object.getClass(), "set" + StringUtils.capitalize(property), value.getClass());
|
348
|
if(method != null){
|
349
|
try {
|
350
|
method.invoke(object, value);
|
351
|
} catch (IllegalArgumentException e) {
|
352
|
// TODO Auto-generated catch block
|
353
|
e.printStackTrace();
|
354
|
} catch (IllegalAccessException e) {
|
355
|
// TODO Auto-generated catch block
|
356
|
e.printStackTrace();
|
357
|
} catch (InvocationTargetException e) {
|
358
|
// TODO Auto-generated catch block
|
359
|
e.printStackTrace();
|
360
|
}
|
361
|
}
|
362
|
}
|
363
|
|
364
|
/**
|
365
|
* @param collection of which all entities are to be initialized
|
366
|
* @param cdmEntities initialize all *toOne relations to cdm entities
|
367
|
* @param collections initialize all *toMany relations
|
368
|
*/
|
369
|
protected void initializeAllEntries(Collection collection, boolean cdmEntities, boolean collections) {
|
370
|
for(Object bean : collection){
|
371
|
initializeBean(bean, cdmEntities, collections);
|
372
|
}
|
373
|
}
|
374
|
|
375
|
/**
|
376
|
* Return all public bean properties exclusive those whose return type
|
377
|
* match any class defined in the parameter <code>typeRestrictions</code>
|
378
|
* or which are transient properties.
|
379
|
*
|
380
|
*
|
381
|
* @param bean
|
382
|
* @param typeRestrictions
|
383
|
* @return
|
384
|
*/
|
385
|
public static Set<PropertyDescriptor> getProperties(Object bean, Set<Class<?>> typeRestrictions) {
|
386
|
|
387
|
Set<PropertyDescriptor> properties = new HashSet<>();
|
388
|
PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(bean);
|
389
|
|
390
|
for (PropertyDescriptor prop : props) {
|
391
|
//String propName = prop[i].getName();
|
392
|
|
393
|
// only read methods & skip transient getters
|
394
|
if( prop.getReadMethod() != null ){
|
395
|
try{
|
396
|
@SuppressWarnings("unchecked")
|
397
|
Class<Transient> transientClass = (Class<Transient>)Class.forName( "javax.persistence.Transient" );
|
398
|
if( prop.getReadMethod().getAnnotation( transientClass ) != null ){
|
399
|
continue;
|
400
|
}
|
401
|
}catch( ClassNotFoundException cnfe ){
|
402
|
// ignore
|
403
|
}
|
404
|
if(typeRestrictions != null){
|
405
|
for(Class<?> restrictedType : typeRestrictions){
|
406
|
if(restrictedType.isAssignableFrom(prop.getPropertyType())){
|
407
|
properties.add(prop);
|
408
|
}
|
409
|
}
|
410
|
} else {
|
411
|
properties.add(prop);
|
412
|
}
|
413
|
}
|
414
|
}
|
415
|
return properties;
|
416
|
}
|
417
|
|
418
|
}
|