001 // Copyright 2006, 2007 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
015 package org.apache.tapestry5.internal.services;
016
017 import org.apache.tapestry5.ioc.AnnotationProvider;
018 import org.apache.tapestry5.ioc.ObjectLocator;
019 import org.apache.tapestry5.ioc.ObjectProvider;
020 import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
021 import org.apache.tapestry5.services.Alias;
022 import org.apache.tapestry5.services.AliasManager;
023
024 import java.util.Map;
025
026 public class AliasImpl implements Alias, ObjectProvider
027 {
028 // Derived from the managers when first needed
029
030 private final Map<Class, Object> properties = CollectionFactory.newMap();
031
032 private final String mode;
033
034 private boolean initialized = false;
035
036 private AliasManager masterManager;
037
038 private AliasManager overridesManager;
039
040 public AliasImpl(AliasManager masterManager, String mode, AliasManager overridesManager)
041 {
042 this.masterManager = masterManager;
043 this.mode = mode;
044 this.overridesManager = overridesManager;
045 }
046
047 public ObjectProvider getObjectProvider()
048 {
049 return this;
050 }
051
052 private synchronized void initialize()
053 {
054 if (initialized) return;
055
056 properties.putAll(masterManager.getAliasesForMode(mode));
057 properties.putAll(overridesManager.getAliasesForMode(mode));
058
059 masterManager = null;
060 overridesManager = null;
061
062 initialized = true;
063 }
064
065 public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
066 ObjectLocator locator)
067 {
068 initialize();
069
070 Object object = properties.get(objectType);
071
072 // Let another provider handle this (probably the default object provider)
073 if (object == null) return null;
074
075 // A ClassCastException should never occur.
076
077 return objectType.cast(object);
078 }
079 }