01: /*
02: * Copyright 2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.springframework.oxm.jaxb;
17:
18: import javax.xml.bind.JAXBException;
19: import javax.xml.bind.MarshalException;
20: import javax.xml.bind.UnmarshalException;
21: import javax.xml.bind.ValidationException;
22:
23: import org.springframework.oxm.XmlMappingException;
24: import org.springframework.util.ClassUtils;
25:
26: /**
27: * Generic utility methods for working with JAXB. Mainly for internal use within the framework.
28: *
29: * @author Arjen Poutsma
30: * @since 1.0.0
31: */
32: public abstract class JaxbUtils {
33:
34: public static final int JAXB_1 = 0;
35:
36: public static final int JAXB_2 = 1;
37:
38: private static final String JAXB_2_CLASS_NAME = "javax.xml.bind.Binder";
39:
40: private static int jaxbVersion = JAXB_1;
41:
42: static {
43: try {
44: ClassUtils.forName(JAXB_2_CLASS_NAME);
45: jaxbVersion = JAXB_2;
46: } catch (ClassNotFoundException ex1) {
47: // leave JAXB 1 as default
48: }
49: }
50:
51: /**
52: * Gets the major JAXB version. This means we can do things like if <code>(getJaxbVersion() <= JAXB_2)</code>.
53: *
54: * @return a code comparable to the JAXP_XX codes in this class
55: * @see #JAXB_1
56: * @see #JAXB_2
57: */
58: public static int getJaxbVersion() {
59: return jaxbVersion;
60: }
61:
62: /**
63: * Converts the given <code>JAXBException</code> to an appropriate exception from the
64: * <code>org.springframework.oxm</code> hierarchy.
65: *
66: * @param ex <code>JAXBException</code> that occured
67: * @return the corresponding <code>XmlMappingException</code>
68: */
69: public static XmlMappingException convertJaxbException(
70: JAXBException ex) {
71: if (ex instanceof MarshalException) {
72: return new JaxbMarshallingFailureException(
73: (MarshalException) ex);
74: } else if (ex instanceof UnmarshalException) {
75: return new JaxbUnmarshallingFailureException(
76: (UnmarshalException) ex);
77: } else if (ex instanceof ValidationException) {
78: return new JaxbValidationFailureException(
79: (ValidationException) ex);
80: }
81: // fallback
82: return new JaxbSystemException(ex);
83: }
84:
85: }
|