001    // Copyright 2006, 2007, 2008, 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;
016    
017    import java.lang.reflect.Method;
018    import java.util.Map;
019    
020    import org.apache.tapestry5.ioc.ModuleBuilderSource;
021    import org.apache.tapestry5.ioc.ServiceDecorator;
022    import org.apache.tapestry5.ioc.ServiceResources;
023    import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
024    import org.apache.tapestry5.ioc.internal.util.InjectionResources;
025    import org.apache.tapestry5.ioc.internal.util.MapInjectionResources;
026    import org.apache.tapestry5.ioc.services.PlasticProxyFactory;
027    
028    /**
029     * A wrapper around a decorator method.
030     */
031    public class ServiceDecoratorImpl extends AbstractMethodInvokingInstrumenter implements ServiceDecorator
032    {
033    
034        public ServiceDecoratorImpl(Method method, ModuleBuilderSource moduleSource, ServiceResources resources,
035                PlasticProxyFactory proxyFactory)
036        {
037            super(moduleSource, method, resources, proxyFactory);
038        }
039    
040        public Object createInterceptor(Object delegate)
041        {
042            // Create a copy of the parameters map so that Object.class points to the delegate instance.
043    
044            Map<Class, Object> resources = CollectionFactory.newMap(this.resourcesDefaults);
045    
046            resources.put(Object.class, delegate);
047            resources.put(serviceInterface, delegate);
048    
049            InjectionResources injectionResources = new MapInjectionResources(resources);
050    
051            Object result = invoke(injectionResources);
052    
053            if (result != null && !serviceInterface.isInstance(result)) { throw new RuntimeException(
054                    IOCMessages.decoratorReturnedWrongType(method, serviceId, result, serviceInterface)); }
055    
056            return result;
057        }
058    
059    }