1 package org.simantics.databoard.serialization;
\r
3 import java.util.HashMap;
\r
4 import java.util.Map;
\r
6 import org.simantics.databoard.binding.Binding;
\r
11 * @author Toni Kalajainen
\r
13 public abstract class SerializerFactory implements SerializerScheme {
\r
16 * Map of failed constructions.
\r
18 protected Map<Binding, SerializerConstructionException> failures = new HashMap<Binding, SerializerConstructionException>();
\r
21 * Repository where serializers are placed.
\r
23 Map<Binding, Serializer> repository;
\r
26 * Map that contains in incomplete constructions.
\r
28 Map<Binding, Serializer> inprogress = new HashMap<Binding, Serializer>();
\r
31 * Construct a new serializer.
\r
33 public SerializerFactory() {
\r
34 this.repository = new HashMap<Binding, Serializer>();
\r
38 * Construct a new serializer factory that places constructed serializers
\r
39 * into user given repository.
\r
43 public SerializerFactory(Map<Binding, Serializer> repository) {
\r
44 this.repository = repository;
\r
47 public Map<Binding, Serializer> getRepository() {
\r
52 * Constructs a serilizer for a binding. Implement this.
\r
53 * It should use the inprogress -map for construction of
\r
54 * serializers that have component types.
\r
57 * inprogress.put(binding, notCompletelyConstructedSerializer);
\r
58 * Serializer componentSerializer = construct( componentBinding );
\r
59 * notCompletelyConstructedSerializer.setComponent( componentSerializer );
\r
60 * inprogress.remove(binding);
\r
62 * try-finally is not needed.
\r
66 * @throws SerializerConstructionException
\r
68 protected abstract Serializer doConstruct(Binding request) throws SerializerConstructionException;
\r
70 public Serializer construct(Binding request) throws SerializerConstructionException
\r
72 // Optimization: if binding provides a cached serializer, just return it.
\r
73 { Serializer ser = request.cachedSerializer(); if (ser != null) return ser; }
\r
74 { Serializer ser = repository.get(request); if(ser != null) return ser; }
\r
75 { Serializer ser = inprogress.get(request); if(ser != null) return ser; }
\r
76 { SerializerConstructionException e = failures.get(request); if(e != null) throw e; }
\r
78 // Start construction
\r
80 Serializer binding = doConstruct(request);
\r
81 repository.put(request, binding);
\r
82 request.cacheSerializer(binding);
\r
84 } catch (SerializerConstructionException e) {
\r
85 inprogress.remove( request );
\r
86 failures.put(request, e);
\r
92 public Serializer getSerializer(Binding binding)
\r
93 throws SerializerConstructionException {
\r
94 return construct(binding);
\r
97 public Serializer getSerializerUnchecked(Binding binding)
\r
98 throws RuntimeSerializerConstructionException {
\r
100 return construct(binding);
\r
101 } catch (SerializerConstructionException e) {
\r
102 throw new RuntimeSerializerConstructionException(e);
\r