/*
 * 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.interceptor;

import java.lang.reflect.InvocationTargetException;
import java.util.Locale;

import jp.ossc.nimbus.core.ServiceBase;
import jp.ossc.nimbus.core.ServiceManagerFactory;
import jp.ossc.nimbus.core.ServiceName;
import jp.ossc.nimbus.core.ServiceNotFoundException;
import jp.ossc.nimbus.service.journal.Journal;
import jp.ossc.nimbus.service.log.Logger;
import jp.ossc.nimbus.service.aop.InvocationContext;
import jp.ossc.nimbus.service.aop.MethodInvocationContext;

/**
 * デフォルト例外ハンドラサービス。<p>
 * 以下の例外処理機能を持っている。<br>
 * <ul>
 *     <li>例外をジャーナルに出力する。</li>
 *     <li>ログを出力する。</li>
 *     <li>例外をthrowする、またはthrowしない。</li>
 * </ul>
 *
 * @author M.Takata
 */
public class DefaultExceptionHandlerService extends ServiceBase
 implements DefaultExceptionHandlerServiceMBean, ExceptionHandler{
    
    private static final long serialVersionUID = 8033521240074993145L;
    
    protected ServiceName journalServiceName;
    protected Journal journal;
    protected String logMessageCode;
    protected String[] logMessageArguments;
    protected boolean isOutputStackTraceLog = true;
    protected String exceptionJournalKey = DEFAULT_EXCEPTION_JOURNAL_KEY;
    protected boolean isThrowException;
    protected Object returnValue;
    
    private Throwable throwable;
    private Class<?> throwableClass;
    private String throwableMessage;
    private String throwableMessageKey;
    private Locale throwableMessageLocale;
    private Object[] throwableMessageArgs;
    private boolean isWrapThrowable = true;
    
    public void setJournalServiceName(ServiceName name){
        journalServiceName = name;
    }
    public ServiceName getJournalServiceName(){
        return journalServiceName;
    }
    
    public void setLogMessageCode(String code){
        logMessageCode = code;
    }
    public String getLogMessageCode(){
        return logMessageCode;
    }
    
    public void setLogMessageArguments(String[] args){
        logMessageArguments = args;
    }
    public String[] getLogMessageArguments(){
        return logMessageArguments;
    }
    
    public void setOutputStackTraceLog(boolean isOutput){
        isOutputStackTraceLog = isOutput;
    }
    public boolean isOutputStackTraceLog(){
        return isOutputStackTraceLog;
    }
    
    public void setExceptionJournalKey(String key){
        exceptionJournalKey = key;
    }
    public String getExceptionJournalKey(){
        return exceptionJournalKey;
    }
    
    public void setThrowException(boolean isThrow){
        isThrowException = isThrow;
    }
    public boolean isThrowException(){
        return isThrowException;
    }
    
    public void setReturnValue(Object value){
        returnValue = value;
    }
    public Object getReturnValue(){
        return returnValue;
    }
    
    public void setThrowable(Throwable th){
        this.throwable = th;
    }
    public Throwable getThrowable(){
        return throwable;
    }
    
    public void setThrowableClass(Class<?> clazz){
        this.throwableClass = clazz;
    }
    public Class<?> getThrowableClass(){
        return throwableClass;
    }
    
    public void setThrowableMessage(String message){
        this.throwableMessage = message;
    }
    public String getThrowableMessage(){
        return throwableMessage;
    }
    
    public void setThrowableMessageKey(String key){
        this.throwableMessageKey = key;
    }
    public String getThrowableMessageKey(){
        return throwableMessageKey;
    }
    
    public void setThrowableMessageLocale(Locale locale){
        this.throwableMessageLocale = locale;
    }
    public Locale getThrowableMessageLocale(){
        return throwableMessageLocale;
    }
    
    public void setThrowableMessageArgs(Object[] args){
        this.throwableMessageArgs = args;
    }
    public Object[] getThrowableMessageArgs(){
        return throwableMessageArgs;
    }
    
    public void setWrapThrowable(boolean isWrap){
        this.isWrapThrowable = isWrap;
    }
    public boolean isWrapThrowable(){
        return isWrapThrowable;
    }
    
    public void startService() throws Exception{
        if(journalServiceName != null){
            journal = ServiceManagerFactory
                .getServiceObject(journalServiceName);
        }
    }
    
    public Object handleException(
        Throwable th,
        InvocationContext context
    ) throws Throwable {
        if(logMessageCode != null){
            final Logger log = getLogger();
            if(isOutputStackTraceLog){
                log.write(logMessageCode, th, (Object[])logMessageArguments);
            }else{
                log.write(logMessageCode, (Object[])logMessageArguments);
            }
        }
        if(journal != null){
            journal.addInfo(
                exceptionJournalKey,
                th
            );
        }
        if(isThrowException){
            if(getThrowable() == null || getThrowableClass() == null){
                throw th;
            }else{
                throw createThrowable(th);
            }
        }
        if(returnValue instanceof ServiceName){
            Class<?> retType = null;
            if(context instanceof MethodInvocationContext){
                retType = ((MethodInvocationContext)context).getTargetMethod().getReturnType();
            }else{
                retType = context.getTargetObject() == null ? null : context.getTargetObject().getClass();
            }
            if(Void.TYPE.equals(retType)){
                return null;
            }
            if(retType != null && !ServiceName.class.equals(retType)){
                try{
                    returnValue = ServiceManagerFactory
                        .getServiceObject((ServiceName)returnValue);
                }catch(ServiceNotFoundException e){
                }
            }
        }
        return returnValue;
    }
    
    protected Throwable createThrowable(Throwable cause){
        if(getThrowable() != null){
            return getThrowable();
        }
        if(getThrowableClass() == null){
            return cause;
        }
        Throwable ret = cause;
        if(getThrowableMessage() == null && getThrowableMessageKey() == null){
            if(isWrapThrowable()){
                try{
                    ret = (Throwable)getThrowableClass()
                        .getConstructor(Throwable.class).newInstance(cause);
                }catch(IllegalArgumentException e){
                }catch(SecurityException e){
                }catch(InstantiationException e){
                }catch(IllegalAccessException e){
                }catch(InvocationTargetException e){
                }catch(NoSuchMethodException e){
                }
            }else{
                try{
                    ret = (Throwable)getThrowableClass().newInstance();
                }catch(InstantiationException e){
                }catch(IllegalAccessException e){
                }
            }
        }else{
            String msg = getThrowableMessage();
            if(getThrowableMessageKey() != null){
                msg = getMessageRecordFactory().findMessage(
                    getThrowableMessageKey(),
                    getThrowableMessageLocale(),
                    getThrowableMessageArgs()
                );
            }
            if(isWrapThrowable()){
                try{
                    ret = (Throwable)getThrowableClass()
                        .getConstructor(String.class, Throwable.class)
                        .newInstance(msg, cause);
                }catch(IllegalArgumentException e){
                }catch(SecurityException e){
                }catch(InstantiationException e){
                }catch(IllegalAccessException e){
                }catch(InvocationTargetException e){
                }catch(NoSuchMethodException e){
                }
            }else{
                try{
                    ret = (Throwable)getThrowableClass()
                        .getConstructor(String.class).newInstance(msg);
                }catch(IllegalArgumentException e){
                }catch(SecurityException e){
                }catch(InstantiationException e){
                }catch(IllegalAccessException e){
                }catch(InvocationTargetException e){
                }catch(NoSuchMethodException e){
                }
            }
        }
        return ret;
    }
}
