| /******************************************************************************* |
| * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 |
| * which accompanies this distribution. |
| * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html |
| * and the Eclipse Distribution License is available at |
| * http://www.eclipse.org/org/documents/edl-v10.php. |
| * |
| * Contributors: |
| * Oracle - initial impl |
| ******************************************************************************/ |
| package example; |
| |
| import java.io.ByteArrayInputStream; |
| import java.io.ByteArrayOutputStream; |
| import java.io.StringReader; |
| import java.io.StringWriter; |
| |
| import javax.xml.bind.JAXBContext; |
| import javax.xml.bind.JAXBException; |
| import javax.xml.bind.Marshaller; |
| import javax.xml.bind.Unmarshaller; |
| |
| import model.Order; |
| |
| /** |
| * Uses JAXB to convert an object to XML. |
| * @author James Sutherland |
| */ |
| public class XMLSerializer implements Serializer { |
| JAXBContext context; |
| Marshaller marshaller; |
| Unmarshaller unmarshaller; |
| |
| public XMLSerializer() { |
| try { |
| this.context = JAXBContext.newInstance(Order.class); |
| this.marshaller = context.createMarshaller(); |
| this.marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); |
| this.unmarshaller = context.createUnmarshaller(); |
| } catch (JAXBException exception) { |
| throw new RuntimeException(exception); |
| } |
| } |
| |
| public byte[] serialize(Object object) { |
| try { |
| ByteArrayOutputStream stream = new ByteArrayOutputStream(); |
| //StringWriter writer = new StringWriter(); |
| marshaller.marshal(object, stream); |
| return stream.toByteArray(); |
| } catch (JAXBException exception) { |
| throw new RuntimeException(exception); |
| } |
| } |
| |
| public Object deserialize(byte[] bytes) { |
| try { |
| ByteArrayInputStream stream = new ByteArrayInputStream(bytes); |
| //StringReader reader = new StringReader(new String(bytes)); |
| return unmarshaller.unmarshal(stream); |
| } catch (JAXBException exception) { |
| throw new RuntimeException(exception); |
| } |
| } |
| |
| public String toString() { |
| return getClass().getSimpleName(); |
| } |
| } |