01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */package org.apache.openejb.jee.jpa;
17:
18: import org.xml.sax.SAXException;
19: import org.xml.sax.InputSource;
20:
21: import javax.xml.bind.JAXBException;
22: import javax.xml.bind.JAXBContext;
23: import javax.xml.bind.Marshaller;
24: import javax.xml.bind.Unmarshaller;
25: import javax.xml.bind.ValidationEventHandler;
26: import javax.xml.bind.ValidationEvent;
27: import javax.xml.parsers.ParserConfigurationException;
28: import javax.xml.parsers.SAXParserFactory;
29: import javax.xml.parsers.SAXParser;
30: import java.io.ByteArrayOutputStream;
31: import java.io.InputStream;
32:
33: /**
34: * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 $
35: */
36: public class JpaJaxbUtil {
37:
38: public static <T> String marshal(Class<T> type, Object object)
39: throws JAXBException {
40: JAXBContext ctx2 = JAXBContext.newInstance(type);
41: Marshaller marshaller = ctx2.createMarshaller();
42:
43: marshaller.setProperty("jaxb.formatted.output", true);
44:
45: ByteArrayOutputStream baos = new ByteArrayOutputStream();
46: marshaller.marshal(object, baos);
47:
48: return new String(baos.toByteArray());
49: }
50:
51: public static <T> Object unmarshal(Class<T> type, InputStream in)
52: throws ParserConfigurationException, SAXException,
53: JAXBException {
54: InputSource inputSource = new InputSource(in);
55:
56: SAXParserFactory factory = SAXParserFactory.newInstance();
57: factory.setNamespaceAware(true);
58: factory.setValidating(false);
59:
60: JAXBContext ctx = JAXBContext.newInstance(type);
61: Unmarshaller unmarshaller = ctx.createUnmarshaller();
62: unmarshaller.setEventHandler(new ValidationEventHandler() {
63: public boolean handleEvent(ValidationEvent validationEvent) {
64: System.out.println(validationEvent);
65: return false;
66: }
67: });
68:
69: return unmarshaller.unmarshal(inputSource);
70: }
71: }
|