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