View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.ibeans.config;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.context.MuleContextAware;
11  import org.mule.api.registry.InjectProcessor;
12  import org.mule.module.ibeans.spi.MuleIBeansPlugin;
13  import org.mule.util.annotation.AnnotationMetaData;
14  import org.mule.util.annotation.AnnotationUtils;
15  
16  import java.lang.reflect.Field;
17  import java.lang.reflect.InvocationHandler;
18  import java.lang.reflect.Proxy;
19  import java.util.List;
20  
21  import org.ibeans.annotation.MockIntegrationBean;
22  import org.ibeans.impl.test.MockIBean;
23  import org.ibeans.impl.test.MockIntegrationBeanInvocationHandler;
24  import org.mockito.Mockito;
25  
26  /**
27   * Will process any fields on an object with the {@link org.ibeans.annotation.MockIntegrationBean} annotation, inserting
28   * a Mockito Mock object.  This is only used for testing.
29   */
30  public class MockIntegrationBeansAnnotationProcessor implements InjectProcessor, MuleContextAware
31  {
32      public static final String NAME = "_mockIntegrationBeanProcessor";
33  
34      private MuleIBeansPlugin plugin;
35  
36      public MockIntegrationBeansAnnotationProcessor()
37      {
38      }
39  
40      public void setMuleContext(MuleContext muleContext)
41      {
42          this.plugin = new MuleIBeansPlugin(muleContext);
43      }
44  
45      public Object process(Object object)
46      {
47          List<AnnotationMetaData> annos = AnnotationUtils.getFieldAnnotations(object.getClass(), MockIntegrationBean.class);
48  
49          if (annos.size() > 0)
50          {
51              for (AnnotationMetaData data : annos)
52              {
53                  Field field = (Field) data.getMember();
54                  field.setAccessible(true);
55                  Object mockito = Mockito.mock(field.getType(), field.getName());
56                  try
57                  {
58                      //InvocationHandler handler = new MockIBeanHandler(field.getType(), muleContext, mockito);
59                      InvocationHandler handler = new MockIntegrationBeanInvocationHandler(field.getType(), plugin, mockito);
60  
61                      Object mock = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{field.getType(), MockIBean.class}, handler);
62  
63                      field.set(object, mock);
64                  }
65                  catch (Exception e)
66                  {
67                      throw new RuntimeException(e);
68                  }
69              }
70          }
71          return object;
72      }
73  }