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