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.xml.transformer.jaxb;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.config.transformer.AbstractAnnotatedTransformerArgumentResolver;
11  
12  import javax.xml.bind.JAXBContext;
13  import javax.xml.bind.JAXBException;
14  
15  /**
16   * This resolver is used by the transform engine to inject a JAXBContext into a method that requires it.
17   * A shared JAXB context can be created for the application and stored in the registry, this will get injected
18   * into any transform methods that add {@link javax.xml.bind.JAXBContext} to the method signature.
19   * <p/>
20   * IF there is no shared JAXB context one will be created. First this resolver will attempt to create the context from
21   * the package of the the annotated class, for this to work either a jaxb.index file must be present or an {@link javax.naming.spi.ObjectFactory}
22   * must be in the package.  This allows for JAXB generated classes to be used easily.  If this method fails a context will
23   * be created using just the annotated class to initialise the context.
24   *
25   * @since 3.0
26   */
27  public class JAXBContextResolver extends AbstractAnnotatedTransformerArgumentResolver
28  {
29      protected Class getArgumentClass()
30         {
31             return JAXBContext.class;
32         }
33  
34      protected Object createArgument(Class annotatedType, MuleContext muleContext) throws Exception
35      {
36         try
37          {
38              return JAXBContext.newInstance(annotatedType);
39          }
40          catch (JAXBException e)
41          {
42              //Fallback to just adding the annotated class to the context
43              logger.warn(e.getMessage() + ". Initializing context using JAXB annotated class: " + annotatedType);
44              return JAXBContext.newInstance(annotatedType);
45          }
46      }
47  
48     protected String getAnnotationsPackageName()
49     {
50         return "javax.xml.bind.annotation";
51     }
52  
53  }