/* * BidirectionalMapper.java 26.09.2008 * * Copyright 2008 Stefan Jäger * */ package ch.stefanjaeger.jibx; import java.util.ArrayList; import java.util.List; import org.jibx.runtime.IAliasable; import org.jibx.runtime.IMarshaller; import org.jibx.runtime.IMarshallingContext; import org.jibx.runtime.IUnmarshaller; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.jibx.runtime.impl.MarshallingContext; import org.jibx.runtime.impl.UnmarshallingContext; public class BidirectionalMapper implements IMarshaller, IUnmarshaller, IAliasable { private static final String XML_NAMESPACE = "http://stefanjaeger.ch/CustomerSchema"; private String getXMLElement() { return "person"; } public final boolean isPresent(IUnmarshallingContext ctx) throws JiBXException { // verfify, if the Unmarshaller is at the right element return ctx.isAt(XML_NAMESPACE, getXMLElement()); } public final Object unmarshal(Object obj, IUnmarshallingContext ictx) throws JiBXException { // create UnmarshallingContext if (!(ictx instanceof UnmarshallingContext)) { throw new JiBXException("Invalid object type for unmarshaller"); } UnmarshallingContext ctx = (UnmarshallingContext) ictx; // make sure we're at the appropriate start tag (like isPresent) if (!isPresent(ictx)) { ctx.throwStartTagNameError(XML_NAMESPACE, getXMLElement()); } Person person = null; if (ctx.isAt(XML_NAMESPACE, getXMLElement())) { // use existing mapping Object unmarshalledObject = ctx.unmarshalElement(); try { person = (Person) unmarshalledObject; } catch (ClassCastException e) { throw new JiBXException( "ClassCastException while unmarshalling, expected object was of instance " + unmarshalledObject.getClass().getName(), e); } // define the bidirectional mapping Object parent = ctx.getStackObject(0); try { person.setCustomer((Customer) parent); } catch (ClassCastException e) { throw new JiBXException( "ClassCastException while unmarshalling, expected root element was " + Customer.class + ", but received " + parent.getClass().getName(), e); } } return person; } public boolean isExtension(int index) { return false; } public final void marshal(Object obj, IMarshallingContext ictx) throws JiBXException { if (!(obj instanceof Person)) { throw new JiBXException("Invalid object type for marshaller"); } if (!(ictx instanceof MarshallingContext)) { throw new JiBXException("Invalid object type for marshaller"); } try { List listOfElements = new ArrayList(); listOfElements.add((Person) obj); MarshallingContext ctx = (MarshallingContext) ictx; ctx.marshalCollection(listOfElements); } catch (ClassCastException e) { throw new JiBXException( "ClassCastException while marshalling, received object was of instance " + obj.getClass().getName(), e); } } }