1
2
3
4
5
6
7 package org.mule.config.processors;
8
9 import org.mule.api.MuleContext;
10 import org.mule.api.annotations.expressions.Lookup;
11 import org.mule.api.context.MuleContextAware;
12 import org.mule.api.expression.RequiredValueException;
13 import org.mule.api.registry.InjectProcessor;
14 import org.mule.config.i18n.AnnotationsMessages;
15 import org.mule.util.StringUtils;
16
17 import java.lang.reflect.Field;
18
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21
22
23
24
25 public class LookupInjectionProcessor implements InjectProcessor, MuleContextAware
26 {
27
28
29
30 protected transient final Log logger = LogFactory.getLog(LookupInjectionProcessor.class);
31
32 private MuleContext context;
33
34 public LookupInjectionProcessor()
35 {
36 }
37
38 public LookupInjectionProcessor(MuleContext context)
39 {
40 this.context = context;
41 }
42
43 public void setMuleContext(MuleContext context)
44 {
45 this.context = context;
46 }
47
48 public Object process(Object object)
49 {
50 Field[] fields;
51 try
52 {
53 fields = object.getClass().getDeclaredFields();
54 }
55 catch (NoClassDefFoundError e)
56 {
57
58 if (logger.isDebugEnabled())
59 {
60 logger.warn(e.toString());
61 }
62 return object;
63 }
64 for (int i = 0; i < fields.length; i++)
65 {
66 Field field = fields[i];
67 if (field.isAnnotationPresent(Lookup.class))
68 {
69 try
70 {
71 field.setAccessible(true);
72 Object value;
73 String name = field.getAnnotation(Lookup.class).value();
74 boolean optional = field.getAnnotation(Lookup.class).optional();
75 if(StringUtils.isBlank(name))
76 {
77 value = context.getRegistry().lookupObject(field.getType());
78 }
79 else
80 {
81 value = context.getRegistry().lookupObject(name);
82 }
83 if (value == null && !optional)
84 {
85 throw new RequiredValueException(AnnotationsMessages.lookupNotFoundInRegistry(field.getType(), name, object.getClass()));
86 }
87
88 field.set(object, value);
89 }
90 catch (RequiredValueException e)
91 {
92 throw e;
93 }
94 catch (Exception e)
95 {
96 throw new RequiredValueException(AnnotationsMessages.lookupFailedSeePreviousException(object), e);
97 }
98 }
99 }
100 return object;
101 }
102 }