44import java .io .Serializable ;
55import java .io .StringReader ;
66import java .io .StringWriter ;
7+ import java .util .HashMap ;
78
89import javax .xml .bind .JAXBContext ;
910import javax .xml .bind .JAXBElement ;
2324public final class XmlUtility {
2425 private static Log logger = LogFactory .getLog (XmlUtility .class );
2526 private static final String XmlHeader = "<?xml version=\" 1.0\" encoding=\" UTF-8\" standalone=\" yes\" ?>" ;
27+ private static JAXBContext request_ctx = null ;
28+ private static JAXBContext response_ctx = null ;
29+ private static HashMap <String , JAXBContext > jaxbContext = new HashMap <String , JAXBContext >();
2630
2731 /**
2832 * Default C'tor, cannot be instantiated
@@ -38,15 +42,23 @@ private XmlUtility() {
3842 * @throws IOException if errors during serialization
3943 * @throws JAXBException if errors during serialization
4044 */
41- public static <T extends Serializable > String getXml (T entity ) throws IOException , JAXBException
45+ public static synchronized <T extends Serializable > String getXml (T entity ) throws IOException , JAXBException
4246 {
4347 StringWriter sw = new StringWriter ();
4448
4549 if ( null != entity )
4650 {
47- JAXBContext ctx = JAXBContext .newInstance (entity .getClass ());
51+ if (!jaxbContext .containsKey (entity .getClass ().toString ()))
52+ {
53+ request_ctx = JAXBContext .newInstance (entity .getClass ());
54+ jaxbContext .put (entity .getClass ().toString (), request_ctx );
55+ }
56+ else
57+ {
58+ request_ctx = jaxbContext .get (entity .getClass ().toString ());
59+ }
4860
49- Marshaller m = ctx .createMarshaller ();
61+ Marshaller m = request_ctx .createMarshaller ();
5062 m .setProperty (Marshaller .JAXB_FORMATTED_OUTPUT , true );
5163
5264 m .marshal (entity , sw );
@@ -66,14 +78,23 @@ public static <T extends Serializable> String getXml(T entity) throws IOExceptio
6678 * @throws JAXBException if errors during de-serialization
6779 */
6880 @ SuppressWarnings ("unchecked" )
69- public static <T extends Serializable > T create (String xml , Class <T > classType ) throws JAXBException
81+ public static synchronized <T extends Serializable > T create (String xml , Class <T > classType ) throws JAXBException
7082 {
7183 T entity = null ;
7284 //make sure we have not null and not-empty string to de-serialize
7385 if ( null != xml && !xml .trim ().isEmpty ())
7486 {
75- JAXBContext ctx = JAXBContext .newInstance (classType );
76- Unmarshaller um = ctx .createUnmarshaller ();
87+ if (!jaxbContext .containsKey (classType .toString ()))
88+ {
89+ response_ctx = JAXBContext .newInstance (classType );
90+ jaxbContext .put (classType .toString (), response_ctx );
91+ }
92+ else
93+ {
94+ response_ctx = jaxbContext .get (classType .toString ());
95+ }
96+
97+ Unmarshaller um = response_ctx .createUnmarshaller ();
7798 try {
7899 Object unmarshaled = um .unmarshal (new StringReader (xml ));
79100 if ( null != unmarshaled )
0 commit comments