001// Copyright 2006, 2007, 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 java.util.List;
018
019import org.apache.tapestry5.commons.services.PlasticProxyFactory;
020import org.apache.tapestry5.ioc.services.Builtin;
021import org.apache.tapestry5.ioc.services.DefaultImplementationBuilder;
022import org.apache.tapestry5.ioc.services.PipelineBuilder;
023import org.slf4j.Logger;
024
025public class PipelineBuilderImpl implements PipelineBuilder
026{
027
028    private final PlasticProxyFactory proxyFactory;
029
030    private final DefaultImplementationBuilder defaultImplementationBuilder;
031
032    public PipelineBuilderImpl(@Builtin
033    PlasticProxyFactory proxyFactory,
034
035    DefaultImplementationBuilder defaultImplementationBuilder)
036    {
037        this.proxyFactory = proxyFactory;
038        this.defaultImplementationBuilder = defaultImplementationBuilder;
039    }
040
041    @Override
042    public <S, F> S build(Logger logger, Class<S> serviceInterface, Class<F> filterInterface, List<F> filters)
043    {
044        S terminator = defaultImplementationBuilder.createDefaultImplementation(serviceInterface);
045
046        return build(logger, serviceInterface, filterInterface, filters, terminator);
047    }
048
049    @Override
050    public <S, F> S build(Logger logger, Class<S> serviceInterface, Class<F> filterInterface, List<F> filters,
051            S terminator)
052    {
053        if (filters.isEmpty())
054            return terminator;
055
056        BridgeBuilder<S, F> bb = new BridgeBuilder<S, F>(logger, serviceInterface, filterInterface, proxyFactory);
057
058        // The first bridge will point to the terminator.
059        // Like service decorators, we work deepest (last)
060        // to shallowest (first)
061
062        S next = terminator;
063        int count = filters.size();
064
065        for (int i = count - 1; i >= 0; i--)
066        {
067            F filter = filters.get(i);
068
069            next = bb.instantiateBridge(next, filter);
070        }
071
072        return next;
073    }
074
075}