001    // Copyright 2007, 2009, 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    
015    package org.apache.tapestry5.ioc.internal.services;
016    
017    import org.apache.tapestry5.ioc.*;
018    import org.apache.tapestry5.ioc.annotations.PreventServiceDecoration;
019    import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
020    import org.apache.tapestry5.ioc.services.MasterObjectProvider;
021    import org.apache.tapestry5.plastic.PlasticUtils;
022    
023    import java.util.List;
024    
025    @PreventServiceDecoration
026    public class MasterObjectProviderImpl implements MasterObjectProvider
027    {
028        private final List<ObjectProvider> configuration;
029    
030        private final OperationTracker tracker;
031    
032        public MasterObjectProviderImpl(List<ObjectProvider> configuration, OperationTracker tracker)
033        {
034            this.configuration = CollectionFactory.newList(configuration);
035            this.tracker = tracker;
036    
037            // Add this special case to the front of the list.
038            this.configuration.add(0, new StaticObjectProvider(OperationTracker.class, tracker));
039        }
040    
041        public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
042                             final ObjectLocator locator,
043                             final boolean required)
044        {
045            return tracker.invoke(String.format("Resolving object of type %s using MasterObjectProvider",
046                    PlasticUtils.toTypeName(objectType)), new Invokable<T>()
047            {
048                public T invoke()
049                {
050                    for (ObjectProvider provider : configuration)
051                    {
052                        T result = provider.provide(objectType, annotationProvider, locator);
053    
054                        if (result != null) return result;
055                    }
056    
057                    // If required, then we must obtain it the hard way, by
058                    // seeing if there's a single service that implements the interface.
059    
060                    if (required) return locator.getService(objectType);
061    
062                    return null;
063                }
064            });
065        }
066    }