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.ioc.annotations.PostInjection; 021import org.apache.tapestry5.ioc.internal.util.CollectionFactory; 022import org.apache.tapestry5.ioc.util.StrategyRegistry; 023import org.apache.tapestry5.services.*; 024 025@SuppressWarnings("all") 026public class ValueEncoderSourceImpl implements ValueEncoderSource, Runnable 027{ 028 private final StrategyRegistry<ValueEncoderFactory> registry; 029 030 private final Map<Class, ValueEncoder> cache = CollectionFactory.newConcurrentMap(); 031 032 public ValueEncoderSourceImpl(Map<Class, ValueEncoderFactory> configuration) 033 { 034 registry = StrategyRegistry.newInstance(ValueEncoderFactory.class, configuration); 035 } 036 037 @PostInjection 038 public void setupInvalidation(@ComponentClasses InvalidationEventHub hub) { 039 hub.addInvalidationCallback(this); 040 } 041 042 @SuppressWarnings({"unchecked"}) 043 public <T> ValueEncoder<T> getValueEncoder(Class<T> type) 044 { 045 assert type != null; 046 ValueEncoder<T> result = cache.get(type); 047 048 if (result == null) 049 { 050 ValueEncoderFactory<T> factory = registry.get(type); 051 052 result = factory.create(type); 053 054 cache.put(type, result); 055 } 056 057 return result; 058 } 059 060 public void run() 061 { 062 registry.clearCache(); 063 cache.clear(); 064 } 065}