/*
 * 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 jp.ossc.nimbus.core.*;
import jp.ossc.nimbus.service.aop.*;
import jp.ossc.nimbus.service.distribute.KeepAliveListener;
import jp.ossc.nimbus.service.jndi.*;
import jp.ossc.nimbus.service.proxy.ProxyServerInvoker;
import jp.ossc.nimbus.service.repository.Repository;

/**
 * プロキシサーバ呼び出しInvoker。<p>
 * リモートサーバ上のサービスを呼び出すためのInvokerである。<br>
 * リモートのJNDIサーバに、{@link ProxyServerInvoker}インタフェースを実装したリモートオブジェクトがバインドされていなければならない。<br>
 *
 * @author M.Takata
 */
public class ProxyServerCallInvokerService extends ServiceBase
 implements Invoker, KeepAliveCheckInvoker, java.io.Serializable,
            ProxyServerCallInvokerServiceMBean{
    
    private static final long serialVersionUID = -4617039048036524665L;
    
    private ServiceName jndiFinderServiceName;
    private JndiFinder jndiFinder;
    private ServiceName jndiRepositoryServiceName;
    private Repository jndiRepository;
    private String jndiName;
    private ServiceName remoteServiceName;
    
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public void setJndiFinderServiceName(ServiceName name){
        jndiFinderServiceName = name;
    }
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public ServiceName getJndiFinderServiceName(){
        return jndiFinderServiceName;
    }
    
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    public void setJndiRepositoryServiceName(ServiceName name){
        jndiRepositoryServiceName = name;
    }
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    public ServiceName getJndiRepositoryServiceName(){
        return jndiRepositoryServiceName;
    }
    
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public void setProxyServerJndiName(String name){
        jndiName = name;
    }
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public String getProxyServerJndiName(){
        return jndiName;
    }
    
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public void setRemoteServiceName(ServiceName name){
        remoteServiceName = name;
    }
    // ProxyServerCallInvokerServiceMBeanのJavaDoc
    @Override
    public ServiceName getRemoteServiceName(){
        return remoteServiceName;
    }
    
    /**
     * {@link jp.ossc.nimbus.service.proxy.ProxyServerInvoker ProxyServerInvoker}インタフェースを実装したRMIオブジェクトをlookupする{@link jp.ossc.nimbus.service.jndi.JndiFinder JndiFinder}サービスを設定する。<p>
     *
     * @param jndiFinder JndiFinderサービス
     */
    public void setJndiFinder(JndiFinder jndiFinder) {
        this.jndiFinder = jndiFinder;
    }
    
    /**
     * {@link jp.ossc.nimbus.service.proxy.ProxyServerInvoker ProxyServerInvoker}インタフェースを実装したRMIオブジェクトをlookupする{@link jp.ossc.nimbus.service.repository.Repository Repository}サービスを設定する。<p>
     *
     * @param jndiRepository Repositoryサービス
     */
    public void setJndiRepository(Repository jndiRepository) {
        this.jndiRepository = jndiRepository;
    }
    
    /**
     * サービスの開始処理を行う。<p>
     *
     * @exception Exception サービスの開始処理に失敗した場合
     */
    @Override
    public void startService() throws Exception{
        if(jndiFinderServiceName != null){
            jndiFinder = ServiceManagerFactory
                .getServiceObject(jndiFinderServiceName);
        }
        if(jndiRepositoryServiceName != null){
            jndiRepository = ServiceManagerFactory
                .getServiceObject(jndiRepositoryServiceName);
        }
        if(jndiFinder == null && jndiRepository == null) {
            throw new IllegalArgumentException(
                "JndiFinder or JndiRepository must be specified."
            );
        }
    }
    
    /**
     * {@link ProxyServerInvoker}インタフェースを実装したリモートオブジェクトを呼び出す。<p>
     * 
     * @param context 呼び出しのコンテキスト情報
     * @return 呼び出し結果の戻り値
     * @exception Throwable 呼び出し先で例外が発生した場合
     */
    @Override
    public Object invoke(InvocationContext context) throws Throwable{
        final MethodInvocationContext methodContext
             = (MethodInvocationContext)context;
        try{
            ServiceName serviceName = remoteServiceName;
            if(serviceName == null){
                Object target = methodContext.getTargetObject();
                if(target != null && target instanceof ServiceName){
                    serviceName = (ServiceName)target;
                }
            }
            if(serviceName != null){
                methodContext.setTargetObject(serviceName);
            }
            return lookupProxyServerInvoker(serviceName).invoke(context);
        }catch(javax.naming.NamingException e){
            throw new InvokeException(e);
        }catch(java.rmi.RemoteException e){
            throw new InvokeException(e);
        }
    }
    
    private ProxyServerInvoker lookupProxyServerInvoker(
        ServiceName serviceName
    ) throws javax.naming.NamingException{
        
        String name = jndiName;
        if(name == null && serviceName != null){
            name = serviceName.getServiceManagerName()
                 + '/' + serviceName.getServiceName();
        }
        if(name == null){
            throw new IllegalArgumentException(
                "ProxyServerJndiName and RemoteServiceName is null."
            );
        }
        if(jndiFinder != null){
            return (ProxyServerInvoker)jndiFinder.lookup(name);
        }else{
            return (ProxyServerInvoker)jndiRepository.get(name);
        }
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public boolean isAlive(){
        try{
            return lookupProxyServerInvoker(remoteServiceName)
                .isAlive(remoteServiceName);
        }catch(Exception e){
            return false;
        }
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public void addKeepAliveListener(KeepAliveListener listener){
        throw new UnsupportedOperationException();
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public void removeKeepAliveListener(KeepAliveListener listener){
        throw new UnsupportedOperationException();
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public void clearKeepAliveListener(){
        throw new UnsupportedOperationException();
    }
    
    // KeepAliveCheckInvokerのJavaDoc
    @Override
    public <T extends Comparable<?>> T getResourceUsage(){
        try{
            return lookupProxyServerInvoker(remoteServiceName).getResourceUsage();
        }catch(Exception e){
            return null;
        }
    }
}
