/*
 * This software is distributed under following license based on modified BSD
 * style license.
 * ----------------------------------------------------------------------
 * 
 * Copyright 2009 The Nimbus2 Project. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE NIMBUS PROJECT ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL THE NIMBUS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the Nimbus2 Project.
 */
package jp.ossc.nimbus.service.aop.invoker;

import java.lang.reflect.*;

import jp.ossc.nimbus.core.*;
import jp.ossc.nimbus.service.aop.*;
import jp.ossc.nimbus.service.distribute.KeepAliveListener;

/**
 * サービスメソッドリフレクション呼び出しインボーカ。<p>
 * リフレクションAPIを使って、指定されたサービスのメソッド呼び出しを行う。<br>
 * 以下に、サービス定義例を示す。<br>
 * <pre>
 * &lt;?xml version="1.0" encoding="Shift_JIS"?&gt;
 * 
 * &lt;nimbus&gt;
 *     
 *     &lt;manager name="Sample"&gt;
 *         
 *         &lt;service name="SampleInvoker"
 *                  code="jp.ossc.nimbus.service.aop.invoker.LocalServiceCallInvokerService"&gt;
 *             &lt;attribute name="LocalServiceName"&gt;#SampleService&lt;/attribute&gt;
 *             &lt;depends&gt;SampleService&lt;/depends&gt;
 *         &lt;/service&gt;
 *         
 *         &lt;service name="SampleService"
 *                  code="sample.SampleService"/&gt;
 *         
 *     &lt;/manager&gt;
 *     
 * &lt;/nimbus&gt;
 * </pre>
 *
 * @author M.Takata
 */
public class LocalServiceCallInvokerService extends MethodReflectionCallInvokerService
 implements LocalServiceCallInvokerServiceMBean,
             KeepAliveCheckInvoker, ServiceStateListener, java.io.Serializable{
    
    private static final long serialVersionUID = -1650041776482188614L;
    
    private ServiceName localServiceName;
    private Object localService;
    
    // LocalClientMethodCallInvokerServiceMBeanのJavaDoc
    @Override
    public void setLocalServiceName(ServiceName name){
        localServiceName = name;
    }
    // LocalClientMethodCallInvokerServiceMBeanのJavaDoc
    @Override
    public ServiceName getLocalServiceName(){
        return localServiceName;
    }
    
    /**
     * 呼び出し対象となるサービスを設定する。<p>
     *
     * @param localService 呼び出し対象となるサービス
     */
    public void setLocalService(Object localService) {
        this.localService = localService;
    }
    
    /**
     * サービスの開始処理を行う。<p>
     *
     * @exception Exception サービスの開始処理に失敗した場合
     */
    @Override
    public void startService() throws Exception{
        if(localService != null && localService instanceof Service){
            ServiceManagerFactory.addServiceStateListener(
                ((Service)localService).getServiceNameObject(),
                this
            );
        }else if(localServiceName != null){
            ServiceManagerFactory.addServiceStateListener(localServiceName, this);
        }
    }
    
    /**
     * リフレクションAPIを使って、メソッド呼び出しを行う。<p>
     * 呼び出しコンテキストの{@link InvocationContext#getTargetObject()}で取得したサービス名のサービスをローカルの{@link ServiceManager}から取得して、リフレクションAPIでメソッド呼び出しを行う。<br>
     * InvocationContext.getTargetObject()でサービス名が取得できない場合は、{@link #setLocalServiceName(ServiceName)}で設定されたサービス名のサービスを取得して、メソッド呼び出しを行う。<br>
     * 
     * @param context 呼び出しのコンテキスト情報
     * @return 呼び出し結果の戻り値
     * @exception Throwable 呼び出し先で例外が発生した場合
     */
    @Override
    public Object invoke(InvocationContext context) throws Throwable{
        final MethodInvocationContext methodContext
             = (MethodInvocationContext)context;
        
        ServiceName targetName = localServiceName;
        if(targetName == null && context.getTargetObject() instanceof ServiceName){
            targetName = (ServiceName)context.getTargetObject();
        }
        Object target = localService;
        if(targetName != null) {
            try{
                target = ServiceManagerFactory.getServiceObject(targetName);
            }catch(ServiceNotFoundException e){
                throw new InvokeException(e);
            }
        }
        if(target == null) {
            throw new InvokeException(
                "Target service is not specified."
            );
        }
        
        try{
            return methodContext.getTargetMethod().invoke(
                target,
                methodContext.getParameters()
            );
        }catch(InvocationTargetException e){
            throw e.getTargetException();
        }
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public boolean isAlive(){
        if(!super.isAlive()){
            return false;
        }
        if(localServiceName != null){
            try{
                Service service = ServiceManagerFactory.getService(localServiceName);
                return service.getState() == State.STARTED;
            }catch(ServiceNotFoundException e){
                return false;
            }
        }else{
            return true;
        }
    }
    
    // ServiceStateListenerのJavaDoc
    @Override
    public boolean isEnabledState(State state){
        return state == State.STARTED || state == State.STOPPED;
    }
    
    // ServiceStateListenerのJavaDoc
    @Override
    public void stateChanged(ServiceStateChangeEvent e) throws Exception{
        if(listeners == null){
            return;
        }
        switch(e.getService().getState()){
        case STARTED:
            for(KeepAliveListener listener : listeners){
                listener.onRecover(this);
            }
            break;
        case STOPPED:
            for(KeepAliveListener listener : listeners){
                listener.onDead(this);
            }
            break;
        default:
        }
    }
}
