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