001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: package com.sun.xml.bind.v2.runtime.property;
038:
039: import java.io.IOException;
040: import java.util.HashMap;
041: import java.util.LinkedHashMap;
042: import java.util.Map;
043: import java.util.TreeMap;
044: import java.util.Collection;
045: import java.util.Collections;
046: import java.util.Arrays;
047: import java.util.Set;
048:
049: import javax.xml.stream.XMLStreamException;
050: import javax.xml.namespace.QName;
051:
052: import com.sun.xml.bind.api.AccessorException;
053: import com.sun.xml.bind.v2.ClassFactory;
054: import com.sun.xml.bind.v2.util.QNameMap;
055: import com.sun.xml.bind.v2.model.core.PropertyKind;
056: import com.sun.xml.bind.v2.model.nav.ReflectionNavigator;
057: import com.sun.xml.bind.v2.model.runtime.RuntimeMapPropertyInfo;
058: import com.sun.xml.bind.v2.runtime.JAXBContextImpl;
059: import com.sun.xml.bind.v2.runtime.JaxBeanInfo;
060: import com.sun.xml.bind.v2.runtime.Name;
061: import com.sun.xml.bind.v2.runtime.XMLSerializer;
062: import com.sun.xml.bind.v2.runtime.reflect.Accessor;
063: import com.sun.xml.bind.v2.runtime.unmarshaller.ChildLoader;
064: import com.sun.xml.bind.v2.runtime.unmarshaller.TagName;
065: import com.sun.xml.bind.v2.runtime.unmarshaller.Loader;
066: import com.sun.xml.bind.v2.runtime.unmarshaller.Receiver;
067: import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;
068:
069: import org.xml.sax.SAXException;
070:
071: /**
072: * @author Kohsuke Kawaguchi
073: */
074: final class SingleMapNodeProperty<BeanT, ValueT extends Map> extends
075: PropertyImpl<BeanT> {
076:
077: private final Accessor<BeanT, ValueT> acc;
078: /**
079: * The tag name that surrounds the whole property.
080: */
081: private final Name tagName;
082: /**
083: * The tag name that corresponds to the 'entry' element.
084: */
085: private final Name entryTag;
086: private final Name keyTag;
087: private final Name valueTag;
088:
089: private final boolean nillable;
090:
091: private JaxBeanInfo keyBeanInfo;
092: private JaxBeanInfo valueBeanInfo;
093:
094: /**
095: * The implementation class for this property.
096: * If the property is null, we create an instance of this class.
097: */
098: private final Class<? extends ValueT> mapImplClass;
099:
100: public SingleMapNodeProperty(JAXBContextImpl context,
101: RuntimeMapPropertyInfo prop) {
102: super (context, prop);
103: acc = prop.getAccessor().optimize(context);
104: this .tagName = context.nameBuilder.createElementName(prop
105: .getXmlName());
106: this .entryTag = context.nameBuilder.createElementName("",
107: "entry");
108: this .keyTag = context.nameBuilder.createElementName("", "key");
109: this .valueTag = context.nameBuilder.createElementName("",
110: "value");
111: this .nillable = prop.isCollectionNillable();
112: this .keyBeanInfo = context.getOrCreate(prop.getKeyType());
113: this .valueBeanInfo = context.getOrCreate(prop.getValueType());
114:
115: // infer the implementation class
116: Class<ValueT> sig = ReflectionNavigator.REFLECTION.erasure(prop
117: .getRawType());
118: mapImplClass = ClassFactory.inferImplClass(sig,
119: knownImplClasses);
120: // TODO: error check for mapImplClass==null
121: // what is the error reporting path for this part of the code?
122: }
123:
124: private static final Class[] knownImplClasses = { HashMap.class,
125: TreeMap.class, LinkedHashMap.class };
126:
127: public void reset(BeanT bean) throws AccessorException {
128: acc.set(bean, null);
129: }
130:
131: /**
132: * A Map property can never be ID.
133: */
134: public String getIdValue(BeanT bean) {
135: return null;
136: }
137:
138: public PropertyKind getKind() {
139: return PropertyKind.MAP;
140: }
141:
142: public void buildChildElementUnmarshallers(UnmarshallerChain chain,
143: QNameMap<ChildLoader> handlers) {
144: keyLoader = keyBeanInfo.getLoader(chain.context, true);
145: valueLoader = valueBeanInfo.getLoader(chain.context, true);
146: handlers.put(tagName, new ChildLoader(itemsLoader, null));
147: }
148:
149: private Loader keyLoader;
150: private Loader valueLoader;
151:
152: /**
153: * Handles <items> and </items>.
154: *
155: * The target will be set to a {@link Map}.
156: */
157: private final Loader itemsLoader = new Loader(false) {
158: @Override
159: public void startElement(UnmarshallingContext.State state,
160: TagName ea) throws SAXException {
161: // create or obtain the Map object
162: try {
163: BeanT target = (BeanT) state.prev.target;
164: ValueT map = acc.get(target);
165: if (map == null) {
166: map = ClassFactory.create(mapImplClass);
167: acc.set(target, map);
168: }
169: map.clear();
170: state.target = map;
171: } catch (AccessorException e) {
172: // recover from error by setting a dummy Map that receives and discards the values
173: handleGenericException(e, true);
174: state.target = new HashMap();
175: }
176: }
177:
178: @Override
179: public void childElement(UnmarshallingContext.State state,
180: TagName ea) throws SAXException {
181: if (ea.matches(entryTag)) {
182: state.loader = entryLoader;
183: } else {
184: super .childElement(state, ea);
185: }
186: }
187:
188: @Override
189: public Collection<QName> getExpectedChildElements() {
190: return Collections.singleton(entryTag.toQName());
191: }
192: };
193:
194: /**
195: * Handles <entry> and </entry>.
196: *
197: * The target will be set to a {@link Map}.
198: */
199: private final Loader entryLoader = new Loader(false) {
200: @Override
201: public void startElement(UnmarshallingContext.State state,
202: TagName ea) {
203: state.target = new Object[2]; // this is inefficient
204: }
205:
206: @Override
207: public void leaveElement(UnmarshallingContext.State state,
208: TagName ea) {
209: Object[] keyValue = (Object[]) state.target;
210: Map map = (Map) state.prev.target;
211: map.put(keyValue[0], keyValue[1]);
212: }
213:
214: @Override
215: public void childElement(UnmarshallingContext.State state,
216: TagName ea) throws SAXException {
217: if (ea.matches(keyTag)) {
218: state.loader = keyLoader;
219: state.receiver = keyReceiver;
220: return;
221: }
222: if (ea.matches(valueTag)) {
223: state.loader = valueLoader;
224: state.receiver = valueReceiver;
225: return;
226: }
227: super .childElement(state, ea);
228: }
229:
230: @Override
231: public Collection<QName> getExpectedChildElements() {
232: return Arrays.asList(keyTag.toQName(), valueTag.toQName());
233: }
234: };
235:
236: private static final class ReceiverImpl implements Receiver {
237: private final int index;
238:
239: public ReceiverImpl(int index) {
240: this .index = index;
241: }
242:
243: public void receive(UnmarshallingContext.State state, Object o) {
244: ((Object[]) state.target)[index] = o;
245: }
246: }
247:
248: private static final Receiver keyReceiver = new ReceiverImpl(0);
249: private static final Receiver valueReceiver = new ReceiverImpl(1);
250:
251: public void serializeBody(BeanT o, XMLSerializer w, Object outerPeer)
252: throws SAXException, AccessorException, IOException,
253: XMLStreamException {
254: ValueT v = acc.get(o);
255: if (v != null) {
256: bareStartTag(w, tagName, v);
257: for (Map.Entry e : (Set<Map.Entry>) v.entrySet()) {
258: bareStartTag(w, entryTag, null);
259:
260: Object key = e.getKey();
261: if (key != null) {
262: w.startElement(keyTag, key);
263: w.childAsXsiType(key, fieldName, keyBeanInfo);
264: w.endElement();
265: }
266:
267: Object value = e.getValue();
268: if (value != null) {
269: w.startElement(valueTag, value);
270: w.childAsXsiType(value, fieldName, valueBeanInfo);
271: w.endElement();
272: }
273:
274: w.endElement();
275: }
276: w.endElement();
277: } else if (nillable) {
278: w.startElement(tagName, null);
279: w.writeXsiNilTrue();
280: w.endElement();
281: }
282: }
283:
284: private void bareStartTag(XMLSerializer w, Name tagName, Object peer)
285: throws IOException, XMLStreamException, SAXException {
286: w.startElement(tagName, peer);
287: w.endNamespaceDecls(peer);
288: w.endAttributes();
289: }
290:
291: @Override
292: public Accessor getElementPropertyAccessor(String nsUri,
293: String localName) {
294: if (tagName.equals(nsUri, localName))
295: return acc;
296: return null;
297: }
298: }
|