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

import java.io.Serializable;
import java.util.*;
import javax.servlet.ServletRequest;

import jp.ossc.nimbus.service.journal.EditorFinder;

/**
 * ServletRequestオブジェクトをMapフォーマットするエディタ。<p>
 * このエディタによって編集されたMapは、以下の構造を持つ。<br>
 * <table broder="1">
 *   <tr bgcolor="#CCCCFF"><th colspan="2">キー</th><th colspan="5">値</th></tr>
 *   <tr bgcolor="#CCCCFF"><th>型</th><th>内容</th><th>型</th><th colspan="4">内容</th></tr>
 *   <tr><td rowspan="3">java.lang.String</td><td rowspan="3">{@link #ATTRIBUTES_KEY}</td><td rowspan="3">java.util.Map</td><td colspan="4">属性のマップ</td></tr>
 *   <tr bgcolor="#CCCCFF"><th>型</th><th>内容</th><th>型</th><th>内容</th></tr>
 *   <tr><td>java.lang.String</td><td>属性名</td><td>java.lang.Object</td><td>属性値</td></tr>
 *   <tr><td rowspan="3">java.lang.String</td><td rowspan="3">{@link #PARAMETERS_KEY}</td><td rowspan="3">java.util.Map</td><td colspan="4">パラメータのマップ</td></tr>
 *   <tr bgcolor="#CCCCFF"><th>型</th><th>内容</th><th>型</th><th>内容</th></tr>
 *   <tr><td>java.lang.String</td><td>パラメータ名</td><td>java.lang.Object</td><td>パラメータ値</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #CHARACTER_ENCODING_KEY}</td><td>java.lang.String</td><td colspan="4">文字エンコーディング名</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #CONTENT_LENGTH_KEY}</td><td>java.lang.Integer</td><td colspan="4">コンテント長</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #CONTENT_TYPE_KEY}</td><td>java.lang.String</td><td colspan="4">コンテント種別</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #REMOTE_ADDRESS_KEY}</td><td>java.lang.String</td><td colspan="4">リクエスト元のクライアントのIPアドレス。又は、最後に通ったプロキシのIPアドレス。</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #REMOTE_PORT_KEY}</td><td>java.lang.Integer</td><td colspan="4">リクエスト元のクライアントのポート番号。又は、最後に通ったプロキシのポート番号。</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #REMOTE_HOST_KEY}</td><td>java.lang.String</td><td colspan="4">リクエスト元のクライアントの完全限定名。又は、最後に通ったプロキシの完全限定名。</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #LOCAL_ADDRESS_KEY}</td><td>java.lang.String</td><td colspan="4">リクエストを受け取ったサーバのIPアドレス</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #LOCAL_PORT_KEY}</td><td>java.lang.Integer</td><td colspan="4">リクエストを受け取ったサーバのポート番号</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #LOCAL_NAME_KEY}</td><td>java.lang.String</td><td colspan="4">リクエストを受け取ったサーバの完全限定名</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #SERVER_NAME_KEY}</td><td>java.lang.String</td><td colspan="4">リクエストの送り先のサーバのホスト名</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #SERVER_PORT_KEY}</td><td>java.lang.Integer</td><td colspan="4">リクエストの送り先のサーバのポート番号</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #PROTPCOL_KEY}</td><td>java.lang.String</td><td colspan="4">プロトコル名</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #SCHEME_KEY}</td><td>java.lang.String</td><td colspan="4">スキーマ名</td></tr>
 *   <tr><td>java.lang.String</td><td>{@link #LOCALE_KEY}</td><td>java.util.Locale</td><td colspan="4">ロケール</td></tr>
 * </table>
 * 但し、出力しないように設定されているものや、元のServletRequestに含まれていなかった情報、J2EEのバージョンによって取得できない情報は含まれない。<br>
 * 
 * @author M.Takata
 */
public class ServletRequestMapJournalEditorService
 extends MapJournalEditorServiceBase
 implements ServletRequestMapJournalEditorServiceMBean, Serializable{
    
    private static final long serialVersionUID = -2626017130679402298L;
    
    protected String[] secretAttributes;
    private Set<String> secretAttributeSet;
    protected String[] secretParameters;
    private Set<String> secretParameterSet;
    protected String[] enabledAttributes;
    private Set<String> enabledAttributeSet;
    protected String[] disabledAttributes;
    private Set<String> disabledAttributeSet;
    protected String[] enabledParameters;
    private Set<String> enabledParameterSet;
    protected String[] disabledParameters;
    private Set<String> disabledParameterSet;
    
    @Override
    public void setSecretAttributes(String[] names){
        secretAttributes = names;
    }
    
    @Override
    public String[] getSecretAttributes(){
        return secretAttributes;
    }
    
    @Override
    public void setEnabledAttributes(String[] names){
        enabledAttributes = names;
    }
    
    @Override
    public String[] getEnabledAttributes(){
        return enabledAttributes;
    }
    
    @Override
    public void setDisabledAttributes(String[] names){
        disabledAttributes = names;
    }
    
    @Override
    public String[] getDisabledAttributes(){
        return disabledAttributes;
    }
    
    @Override
    public void setSecretParameters(String[] names){
        secretParameters = names;
    }
    
    @Override
    public String[] getSecretParameters(){
        return secretParameters;
    }
    
    @Override
    public void setEnabledParameters(String[] names){
        enabledParameters = names;
    }
    
    @Override
    public String[] getEnabledParameters(){
        return enabledParameters;
    }
    
    @Override
    public void setDisabledParameters(String[] names){
        disabledParameters = names;
    }
    
    @Override
    public String[] getDisabledParameters(){
        return disabledParameters;
    }
    
    @Override
    public void createService(){
        secretAttributeSet = new HashSet<String>();
        secretParameterSet = new HashSet<String>();
        enabledAttributeSet = new HashSet<String>();
        enabledParameterSet = new HashSet<String>();
        disabledAttributeSet = new HashSet<String>();
        disabledParameterSet = new HashSet<String>();
    }
    
    @Override
    public void startService(){
        if(secretAttributes != null){
            for(int i = 0; i < secretAttributes.length; i++){
                secretAttributeSet.add(secretAttributes[i]);
            }
        }
        if(enabledAttributes != null){
            for(int i = 0; i < enabledAttributes.length; i++){
                enabledAttributeSet.add(enabledAttributes[i]);
            }
        }
        if(disabledAttributes != null){
            for(int i = 0; i < disabledAttributes.length; i++){
                disabledAttributeSet.add(disabledAttributes[i]);
            }
        }
        if(secretParameters != null){
            for(int i = 0; i < secretParameters.length; i++){
                secretParameterSet.add(secretParameters[i]);
            }
        }
        if(enabledParameters != null){
            for(int i = 0; i < enabledParameters.length; i++){
                enabledParameterSet.add(enabledParameters[i]);
            }
        }
        if(disabledParameters != null){
            for(int i = 0; i < disabledParameters.length; i++){
                disabledParameterSet.add(disabledParameters[i]);
            }
        }
    }
    
    @Override
    public void stopService(){
        secretAttributeSet.clear();
        enabledAttributeSet.clear();
        disabledAttributeSet.clear();
        secretParameterSet.clear();
        enabledParameterSet.clear();
        disabledParameterSet.clear();
    }
    
    @Override
    public void destroyService(){
        secretAttributeSet = null;
        enabledAttributeSet = null;
        disabledAttributeSet = null;
        secretParameterSet = null;
        enabledParameterSet = null;
        disabledParameterSet = null;
    }
    
    /**
     * ジャーナルとして与えられたServletRequest型の情報をジャーナルとして出力するMap情報に変換する。<br>
     * 
     * @param finder 適切なJournalEditorを提供するEditorFinder
     * @param key ジャーナルのキー情報
     * @param value ジャーナル情報
     * @return ジャーナルとして出力するMap情報
     */
    @Override
    protected Map<String, Object> toMap(EditorFinder finder, String key, Object value){
        final ServletRequest request = (ServletRequest)value;
        final Map<String, Object> result = new LinkedHashMap<String, Object>();
        makeRemoteAddressFormat(finder, key, request, result);
        makeRemotePortFormat(finder, key, request, result);
        makeRemoteHostFormat(finder, key, request, result);
        makeLocalAddressFormat(finder, key, request, result);
        makeLocalPortFormat(finder, key, request, result);
        makeLocalNameFormat(finder, key, request, result);
        makeServerNameFormat(finder, key, request, result);
        makeServerPortFormat(finder, key, request, result);
        makeProtocolFormat(finder, key, request, result);
        makeSchemeFormat(finder, key, request, result);
        makeLocaleFormat(finder, key, request, result);
        makeContentTypeFormat(finder, key, request, result);
        makeContentLengthFormat(finder, key, request, result);
        makeCharacterEncodingFormat(finder, key, request, result);
        makeAttributesFormat(finder, key, request, result);
        makeParametersFormat(finder, key, request, result);
        return result;
    }
    
    @SuppressWarnings("unchecked")
    protected Map<String, Object> makeAttributesFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        if(!isOutputMapKey(ATTRIBUTES_KEY)){
            return map;
        }
        if(isSecretMapKey(ATTRIBUTES_KEY)){
            putMap(map, ATTRIBUTES_KEY, null);
            return map;
        }
        final Enumeration<String> attrNames = request.getAttributeNames();
        if(!attrNames.hasMoreElements()){
            return map;
        }
        final Map<String, Object> subMap = new LinkedHashMap<String, Object>();
        while(attrNames.hasMoreElements()){
            final String name = (String)attrNames.nextElement();
            if(!disabledAttributeSet.isEmpty()
                    && disabledAttributeSet.contains(name)){
                continue;
            }
            if(!enabledAttributeSet.isEmpty()
                 && !enabledAttributeSet.contains(name)){
                continue;
            }
            if(secretAttributeSet.contains(name)){
                subMap.put(name, getSecretString());
            }else{
                subMap.put(
                    name,
                    makeObjectFormat(
                        finder,
                        null,
                        request.getAttribute(name)
                    )
                );
            }
        }
        putMap(map, ATTRIBUTES_KEY, subMap);
        return map;
    }
    
    @SuppressWarnings("unchecked")
    protected Map<String, Object> makeParametersFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        if(!isOutputMapKey(PARAMETERS_KEY)){
            return map;
        }
        if(isSecretMapKey(PARAMETERS_KEY)){
            putMap(map, PARAMETERS_KEY, null);
            return map;
        }
        final Enumeration<String> paramNames = request.getParameterNames();
        if(!paramNames.hasMoreElements()){
            return map;
        }
        final Map<String, Object> subMap = new LinkedHashMap<String, Object>();
        while(paramNames.hasMoreElements()){
            final String name = (String)paramNames.nextElement();
            if(!disabledParameterSet.isEmpty()
                    && disabledParameterSet.contains(name)){
                continue;
            }
            if(!enabledParameterSet.isEmpty()
                 && !enabledParameterSet.contains(name)){
                continue;
            }
            if(secretParameterSet.contains(name)){
                subMap.put(name, getSecretString());
            }else{
                subMap.put(
                    name,
                    makeObjectFormat(finder, key, request.getParameterValues(name))
                );
            }
        }
        putMap(map, PARAMETERS_KEY, subMap);
        return map;
    }
    
    protected Map<String, Object> makeCharacterEncodingFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, CHARACTER_ENCODING_KEY, request.getCharacterEncoding());
        return map;
    }
    
    protected Map<String, Object> makeContentLengthFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, CONTENT_LENGTH_KEY, request.getContentLength());
        return map;
    }
    
    protected Map<String, Object> makeContentTypeFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, CONTENT_TYPE_KEY, request.getContentType());
        return map;
    }
    
    protected Map<String, Object> makeRemoteAddressFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, REMOTE_ADDRESS_KEY, request.getRemoteAddr());
        return map;
    }
    
    protected Map<String, Object> makeRemotePortFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        try{
            final int port = request.getRemotePort();
            putMap(map, REMOTE_PORT_KEY, port);
        }catch(NoSuchMethodError e){
        }
        return map;
    }
    
    protected Map<String, Object> makeRemoteHostFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, REMOTE_HOST_KEY, request.getRemoteHost());
        return map;
    }
    
    protected Map<String, Object> makeLocalAddressFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        try{
            putMap(map, LOCAL_ADDRESS_KEY, request.getLocalAddr());
        }catch(NoSuchMethodError e){
        }
        return map;
    }
    
    protected Map<String, Object> makeLocalPortFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        try{
            final int port = request.getLocalPort();
            putMap(map, LOCAL_PORT_KEY, port);
        }catch(NoSuchMethodError e){
        }
        return map;
    }
    
    protected Map<String, Object> makeLocalNameFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        try{
            putMap(map, LOCAL_NAME_KEY, request.getLocalName());
        }catch(NoSuchMethodError e){
        }
        return map;
    }
    
    protected Map<String, Object> makeServerNameFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, SERVER_NAME_KEY, request.getServerName());
        return map;
    }
    
    protected Map<String, Object> makeServerPortFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, SERVER_PORT_KEY, request.getServerPort());
        return map;
    }
    
    protected Map<String, Object> makeProtocolFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, PROTPCOL_KEY, request.getProtocol());
        return map;
    }
    
    protected Map<String, Object> makeSchemeFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, SCHEME_KEY, request.getScheme());
        return map;
    }
    
    protected Map<String, Object> makeLocaleFormat(
        EditorFinder finder,
        String key,
        ServletRequest request,
        Map<String, Object> map
    ){
        putMap(map, LOCALE_KEY, request.getLocale());
        return map;
    }
}