001// Copyright 2006, 2007, 2011, 2012 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.ioc.internal.util.CollectionFactory;
018import org.apache.tapestry5.ioc.services.PlasticProxyFactory;
019import org.apache.tapestry5.plastic.*;
020import org.slf4j.Logger;
021
022import java.util.Iterator;
023import java.util.List;
024
025/**
026 * Used by the {@link org.apache.tapestry5.ioc.internal.services.PipelineBuilderImpl} to create bridge classes and to
027 * create instances of bridge classes. A bridge class implements the <em>service</em> interface. Within the chain,
028 * bridge 1 is passed to filter 1. Invoking methods on bridge 1 will invoke methods on filter 2.
029 */
030public class BridgeBuilder<S, F>
031{
032    private final Logger logger;
033
034    private final Class<S> serviceInterface;
035
036    private final Class<F> filterInterface;
037
038    private final FilterMethodAnalyzer filterMethodAnalyzer;
039
040    private final PlasticProxyFactory proxyFactory;
041
042    private ClassInstantiator<S> instantiator;
043
044    public BridgeBuilder(Logger logger, Class<S> serviceInterface, Class<F> filterInterface, PlasticProxyFactory proxyFactory)
045    {
046        this.logger = logger;
047        this.serviceInterface = serviceInterface;
048        this.filterInterface = filterInterface;
049
050        this.proxyFactory = proxyFactory;
051
052        filterMethodAnalyzer = new FilterMethodAnalyzer(serviceInterface);
053    }
054
055    /**
056     * Instantiates a bridge object.
057     *
058     * @param nextBridge
059     *         the next Bridge object in the pipeline, or the terminator service
060     * @param filter
061     *         the filter object for this step of the pipeline
062     */
063    public S instantiateBridge(S nextBridge, F filter)
064    {
065        if (instantiator == null)
066            createInstantiator();
067
068        return instantiator.with(filterInterface, filter).with(serviceInterface, nextBridge).newInstance();
069    }
070
071    private void createInstantiator()
072    {
073        instantiator = proxyFactory.createProxy(serviceInterface, new PlasticClassTransformer()
074        {
075            public void transform(PlasticClass plasticClass)
076            {
077                PlasticField filterField = plasticClass.introduceField(filterInterface, "filter")
078                        .injectFromInstanceContext();
079                PlasticField nextField = plasticClass.introduceField(serviceInterface, "next")
080                        .injectFromInstanceContext();
081
082                processMethods(plasticClass, filterField, nextField);
083
084                plasticClass.addToString(String.format("<PipelineBridge from %s to %s>", serviceInterface.getName(),
085                        filterInterface.getName()));
086            }
087        });
088    }
089
090    private void processMethods(PlasticClass plasticClass, PlasticField filterField, PlasticField nextField)
091    {
092        List<MethodSignature> serviceMethods = CollectionFactory.newList();
093        List<MethodSignature> filterMethods = CollectionFactory.newList();
094
095        MethodIterator mi = new MethodIterator(serviceInterface);
096
097        while (mi.hasNext())
098        {
099            serviceMethods.add(mi.next());
100        }
101
102        mi = new MethodIterator(filterInterface);
103
104        while (mi.hasNext())
105        {
106            filterMethods.add(mi.next());
107        }
108
109        while (!serviceMethods.isEmpty())
110        {
111            MethodSignature ms = serviceMethods.remove(0);
112
113            addBridgeMethod(plasticClass, filterField, nextField, ms, filterMethods);
114        }
115
116        reportExtraFilterMethods(filterMethods);
117    }
118
119    private void reportExtraFilterMethods(List filterMethods)
120    {
121        Iterator i = filterMethods.iterator();
122
123        while (i.hasNext())
124        {
125            MethodSignature ms = (MethodSignature) i.next();
126
127            logger.error(String.format("Method %s of filter interface %s does not have a matching method in %s.", ms, filterInterface.getName(), serviceInterface.getName()));
128        }
129    }
130
131    /**
132     * Finds a matching method in filterMethods for the given service method. A matching method has the same signature
133     * as the service interface method, but with an additional parameter matching the service interface itself.
134     * <p/>
135     * The matching method signature from the list of filterMethods is removed and code generation strategies for making
136     * the two methods call each other are added.
137     */
138    private void addBridgeMethod(PlasticClass plasticClass, PlasticField filterField, PlasticField nextField,
139                                 final MethodSignature ms, List filterMethods)
140    {
141        PlasticMethod method = plasticClass.introduceMethod(ms.getMethod());
142
143        Iterator i = filterMethods.iterator();
144
145        while (i.hasNext())
146        {
147            MethodSignature fms = (MethodSignature) i.next();
148
149            int position = filterMethodAnalyzer.findServiceInterfacePosition(ms, fms);
150
151            if (position >= 0)
152            {
153                bridgeServiceMethodToFilterMethod(method, filterField, nextField, position, ms, fms);
154                i.remove();
155                return;
156            }
157        }
158
159        method.changeImplementation(new InstructionBuilderCallback()
160        {
161            public void doBuild(InstructionBuilder builder)
162            {
163                String message = String.format("Method %s has no match in filter interface %s.", ms, filterInterface.getName());
164
165                logger.error(message);
166
167                builder.throwException(RuntimeException.class, message);
168            }
169        });
170    }
171
172    private void bridgeServiceMethodToFilterMethod(PlasticMethod method, final PlasticField filterField,
173                                                   final PlasticField nextField, final int position, MethodSignature ms, final MethodSignature fms)
174    {
175        method.changeImplementation(new InstructionBuilderCallback()
176        {
177            public void doBuild(InstructionBuilder builder)
178            {
179                builder.loadThis().getField(filterField);
180
181                int argumentIndex = 0;
182
183                for (int i = 0; i < fms.getParameterTypes().length; i++)
184                {
185                    if (i == position)
186                    {
187                        builder.loadThis().getField(nextField);
188                    } else
189                    {
190                        builder.loadArgument(argumentIndex++);
191                    }
192                }
193
194                builder.invoke(fms.getMethod()).returnResult();
195            }
196        });
197    }
198
199}