01: /*
02: * Copyright (C) 2004, 2005, 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007, 2008 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 07. March 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.core;
13:
14: import com.thoughtworks.xstream.alias.ClassMapper;
15: import com.thoughtworks.xstream.converters.ConversionException;
16: import com.thoughtworks.xstream.converters.Converter;
17: import com.thoughtworks.xstream.converters.ConverterLookup;
18: import com.thoughtworks.xstream.converters.ConverterRegistry;
19: import com.thoughtworks.xstream.core.util.PrioritizedList;
20: import com.thoughtworks.xstream.mapper.Mapper;
21:
22: import java.util.Collections;
23: import java.util.HashMap;
24: import java.util.Iterator;
25: import java.util.Map;
26:
27: /**
28: * The default implementation of converters lookup.
29: *
30: * @author Joe Walnes
31: * @author Jörg Schaible
32: * @author Guilherme Silveira
33: */
34: public class DefaultConverterLookup implements ConverterLookup,
35: ConverterRegistry {
36:
37: private final PrioritizedList converters = new PrioritizedList();
38: private transient Map typeToConverterMap = Collections
39: .synchronizedMap(new HashMap());
40:
41: public DefaultConverterLookup() {
42: }
43:
44: /**
45: * @deprecated since 1.3, use {@link #DefaultConverterLookup()}
46: */
47: public DefaultConverterLookup(Mapper mapper) {
48: }
49:
50: /**
51: * @deprecated since 1.2, use {@link #DefaultConverterLookup(Mapper)}
52: */
53: public DefaultConverterLookup(ClassMapper classMapper) {
54: }
55:
56: public Converter lookupConverterForType(Class type) {
57: Converter cachedConverter = (Converter) typeToConverterMap
58: .get(type);
59: if (cachedConverter != null)
60: return cachedConverter;
61: Iterator iterator = converters.iterator();
62: while (iterator.hasNext()) {
63: Converter converter = (Converter) iterator.next();
64: if (converter.canConvert(type)) {
65: typeToConverterMap.put(type, converter);
66: return converter;
67: }
68: }
69: throw new ConversionException("No converter specified for "
70: + type);
71: }
72:
73: public void registerConverter(Converter converter, int priority) {
74: converters.add(converter, priority);
75: for (Iterator iter = this .typeToConverterMap.keySet()
76: .iterator(); iter.hasNext();) {
77: Class type = (Class) iter.next();
78: if (converter.canConvert(type)) {
79: iter.remove();
80: }
81: }
82: }
83:
84: private Object readResolve() {
85: typeToConverterMap = Collections.synchronizedMap(new HashMap());
86: return this;
87: }
88:
89: }
|