001    // Copyright 2007 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.hivemind.annotations.internal;
016    
017    import java.lang.reflect.Method;
018    
019    import org.apache.hivemind.ApplicationRuntimeException;
020    import org.apache.hivemind.Location;
021    import org.apache.hivemind.annotations.definition.Service;
022    import org.apache.hivemind.definition.ImplementationConstructionContext;
023    import org.apache.hivemind.definition.ImplementationConstructor;
024    import org.apache.hivemind.internal.AbstractServiceImplementationConstructor;
025    
026    /**
027     * Constructs a service implementation by calling a factory method defined in 
028     * an annotated module by use of the {@link Service} annotation. 
029     * 
030     * @author Achim Huegen
031     */
032    public class MethodCallImplementationConstructor extends AbstractServiceImplementationConstructor implements
033            ImplementationConstructor
034    {
035        private Method _factoryMethod;
036    
037        private ModuleInstanceProvider _moduleInstanceProvider;
038    
039        public MethodCallImplementationConstructor(Location location, Method factoryMethod,
040                ModuleInstanceProvider moduleInstanceProvider)
041        {
042            super(location);
043            _factoryMethod = factoryMethod;
044            _moduleInstanceProvider = moduleInstanceProvider;
045        }
046    
047        public Object constructCoreServiceImplementation(ImplementationConstructionContext context)
048        {
049            try
050            {
051                Object result = _factoryMethod.invoke(_moduleInstanceProvider.getModuleInstance(), (Object[]) null);
052                return result;
053            }
054            catch (Exception ex)
055            {
056                throw new ApplicationRuntimeException(ex.getMessage(), getLocation(), ex);
057            }
058        }
059    
060    }