001// Copyright 2008, 2010, 2011 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 org.apache.tapestry5.internal.plastic.PlasticInternalUtils; 018import org.apache.tapestry5.ioc.annotations.PostInjection; 019import org.apache.tapestry5.ioc.internal.util.CollectionFactory; 020import org.apache.tapestry5.ioc.services.PlasticProxyFactory; 021import org.apache.tapestry5.ioc.services.TypeCoercer; 022import org.apache.tapestry5.services.ComponentClasses; 023import org.apache.tapestry5.services.ComponentLayer; 024import org.apache.tapestry5.services.InvalidationEventHub; 025import org.apache.tapestry5.services.InvalidationListener; 026 027import javax.annotation.PostConstruct; 028import java.util.Map; 029 030public class ComponentClassCacheImpl implements ComponentClassCache 031{ 032 private final Map<String, Class> cache = CollectionFactory.newConcurrentMap(); 033 034 private final PlasticProxyFactory plasticFactory; 035 036 private final TypeCoercer typeCoercer; 037 038 public ComponentClassCacheImpl(@ComponentLayer 039 PlasticProxyFactory plasticFactory, TypeCoercer typeCoercer) 040 { 041 this.plasticFactory = plasticFactory; 042 this.typeCoercer = typeCoercer; 043 } 044 045 @PostInjection 046 public void setupInvalidation(@ComponentClasses InvalidationEventHub hub) { 047 hub.clearOnInvalidation(cache); 048 } 049 050 @SuppressWarnings("unchecked") 051 public Object defaultValueForType(String className) 052 { 053 Class clazz = forName(className); 054 055 if (!clazz.isPrimitive()) 056 return null; 057 058 // Remembering that 0 coerces to boolean false, this covers all the primitive 059 // types (boolean, int, short, etc.) 060 return typeCoercer.coerce(0, clazz); 061 } 062 063 public Class forName(String className) 064 { 065 Class result = cache.get(className); 066 067 if (result == null) 068 { 069 result = lookupClassForType(className); 070 071 cache.put(className, result); 072 } 073 074 return result; 075 } 076 077 private Class lookupClassForType(String className) 078 { 079 ClassLoader componentLoader = plasticFactory.getClassLoader(); 080 try 081 { 082 return PlasticInternalUtils.toClass(componentLoader, className); 083 } 084 catch (ClassNotFoundException ex) 085 { 086 throw new RuntimeException(ex); 087 } 088 } 089}