001// Copyright 2007, 2008, 2010, 2012 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.services;
016
017import java.util.Map;
018
019import org.apache.tapestry5.ValueEncoder;
020import org.apache.tapestry5.beanmodel.services.*;
021import org.apache.tapestry5.commons.services.InvalidationEventHub;
022import org.apache.tapestry5.commons.util.CollectionFactory;
023import org.apache.tapestry5.commons.util.StrategyRegistry;
024import org.apache.tapestry5.ioc.annotations.ComponentClasses;
025import org.apache.tapestry5.ioc.annotations.PostInjection;
026import org.apache.tapestry5.services.ValueEncoderFactory;
027import org.apache.tapestry5.services.ValueEncoderSource;
028
029@SuppressWarnings("all")
030public class ValueEncoderSourceImpl implements ValueEncoderSource, Runnable
031{
032    private final StrategyRegistry<ValueEncoderFactory> registry;
033
034    private final Map<Class, ValueEncoder> cache = CollectionFactory.newConcurrentMap();
035
036    public ValueEncoderSourceImpl(Map<Class, ValueEncoderFactory> configuration)
037    {
038        registry = StrategyRegistry.newInstance(ValueEncoderFactory.class, configuration);
039    }
040
041    @PostInjection
042    public void setupInvalidation(@ComponentClasses InvalidationEventHub hub) {
043        hub.addInvalidationCallback(this);
044    }
045
046    @SuppressWarnings({"unchecked"})
047    public <T> ValueEncoder<T> getValueEncoder(Class<T> type)
048    {
049        assert type != null;
050        ValueEncoder<T> result = cache.get(type);
051
052        if (result == null)
053        {
054            ValueEncoderFactory<T> factory = registry.get(type);
055
056            result = factory.create(type);
057
058            cache.put(type, result);
059        }
060
061        return result;
062    }
063
064    public void run()
065    {
066        registry.clearCache();
067        cache.clear();
068    }
069}