1 28 29 package org.jibx.extras; 30 31 import java.util.HashMap ; 32 33 import org.jibx.runtime.IAliasable; 34 import org.jibx.runtime.IMarshallable; 35 import org.jibx.runtime.IMarshaller; 36 import org.jibx.runtime.IMarshallingContext; 37 import org.jibx.runtime.IUnmarshaller; 38 import org.jibx.runtime.IUnmarshallingContext; 39 import org.jibx.runtime.JiBXException; 40 import org.jibx.runtime.impl.MarshallingContext; 41 import org.jibx.runtime.impl.UnmarshallingContext; 42 43 60 61 public abstract class IdDefRefMapperBase 62 implements IMarshaller, IUnmarshaller, IAliasable { 63 64 private String m_uri; 65 private int m_index; 66 private String m_name; 67 68 78 public IdDefRefMapperBase(String uri, int index, String name) { 79 m_uri = uri; 80 m_index = index; 81 m_name = name; 82 } 83 84 89 protected abstract String getIdValue(Object item); 90 91 95 protected String getAttributeName() { 96 return "ref"; 97 } 98 99 102 public boolean isExtension(int index) { 103 return false; 104 } 105 106 110 public void marshal(Object obj, IMarshallingContext ictx) 111 throws JiBXException { 112 113 if (obj == null) { 115 return; 116 } else if (!(ictx instanceof MarshallingContext)) { 117 throw new JiBXException("Invalid context type for marshaller"); 118 } else { 119 120 MarshallingContext ctx = (MarshallingContext)ictx; 122 HashMap map = ctx.getIdMap(); 123 String id = getIdValue(obj); 124 Object value = map.get(id); 125 if (value == null) { 126 if (obj instanceof IMarshallable) { 127 128 map.put(id, obj); 130 ((IMarshallable)obj).marshal(ctx); 131 132 } else { 133 throw new JiBXException("Object of type " + 134 obj.getClass().getName() + " is not marshallable"); 135 } 136 } else if (value.equals(obj)) { 137 138 ctx.startTagAttributes(m_index, m_name); 140 ctx.attribute(0, getAttributeName(), id); 141 ctx.closeStartEmpty(); 142 143 } else { 144 throw new JiBXException("Duplicate definition for ID " + id); 145 } 146 } 147 } 148 149 152 public boolean isPresent(IUnmarshallingContext ictx) throws JiBXException { 153 return ictx.isAt(m_uri, m_name); 154 } 155 156 160 public Object unmarshal(Object obj, IUnmarshallingContext ictx) 161 throws JiBXException { 162 163 UnmarshallingContext ctx = (UnmarshallingContext)ictx; 165 if (!ctx.isAt(m_uri, m_name)) { 166 return null; 167 } else { 168 169 String id = ctx.attributeText(null, getAttributeName(), null); 171 if (id == null) { 172 173 obj = ctx.unmarshalElement(); 175 176 } else { 177 178 obj = ctx.findID(id, 0); 180 ctx.parsePastEndTag(m_uri, m_name); 181 if (obj == null) { 182 ctx.throwStartTagException("Reference to undefined ID " + 183 id); 184 } 185 } 186 } 187 return obj; 188 } 189 } | Popular Tags |