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.config.transformer;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.MuleException;
11  import org.mule.api.annotations.ContainsTransformerMethods;
12  import org.mule.api.annotations.Transformer;
13  import org.mule.api.context.MuleContextAware;
14  import org.mule.api.registry.PreInitProcessor;
15  import org.mule.util.annotation.AnnotationMetaData;
16  import org.mule.util.annotation.AnnotationUtils;
17  
18  import java.lang.reflect.Method;
19  import java.util.List;
20  
21  /**
22   * Will check all method level annotations to see if there are any {@link org.mule.api.annotations.Transformer} annotations present.
23   * For each method annotated with {@link org.mule.api.annotations.Transformer} a Mule transformer will be created.  When the
24   * transformer is used, the method will get invoked
25   *
26   * @see org.mule.api.annotations.Transformer
27   */
28  public class AnnotatedTransformerObjectProcessor implements PreInitProcessor, MuleContextAware
29  {
30  
31      private MuleContext muleContext;
32  
33      public AnnotatedTransformerObjectProcessor()
34      {
35      }
36  
37      public AnnotatedTransformerObjectProcessor(MuleContext muleContext)
38      {
39          setMuleContext(muleContext);
40      }
41  
42      public void setMuleContext(MuleContext context)
43      {
44          this.muleContext = context;
45      }
46  
47      public Object process(Object object)
48      {
49          Class<? extends Object> clazz = object.getClass();
50          if (clazz.getAnnotation(ContainsTransformerMethods.class) == null)
51          {
52              return object;
53          }
54          List<AnnotationMetaData> annos = AnnotationUtils.getMethodAnnotations(clazz, Transformer.class);
55  
56          if (annos.size() == 0)
57          {
58              return object;
59          }
60          for (AnnotationMetaData data : annos)
61          {
62              try
63              {
64                  Transformer anno = (Transformer) data.getAnnotation();
65                  AnnotatedTransformerProxy trans = new AnnotatedTransformerProxy(
66                          anno.priorityWeighting(),
67                          object, (Method) data.getMember(), anno.sourceTypes(),
68                          null /*anno.sourceMimeType()*/, null /*anno.resultMimeType()*/);
69  
70                  muleContext.getRegistry().registerTransformer(trans);
71              }
72              catch (MuleException e)
73              {
74                  throw new RuntimeException(e);
75              }
76          }
77          return object;
78      }
79  }