/**
 * Copyright (c) 2003-2004 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;//7.2.0 ST0242 追加

import jp.co.sint.basic.SILoginSession;
import jp.co.sint.config.SIConfig;//7.2.0 ST0242 追加
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDeleteRec;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.database.SIModifyRec;
import jp.co.sint.database.SISpcType;
import jp.co.sint.database.SITableCondition;
import jp.co.sint.tools.SIHTMLUtil;
import jp.co.sint.tools.SIStringUtil;
import jp.co.sint.tools.SIURLMap;
import jp.co.sint.tools.SIUtil;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

 /**
  * 共通サーブレットクラス
  * @version $Id: SIServlet.java,v 1.0 2003/06/23 jwchen Exp $
  * @author  Jinwang Chen
  */

public class SIServlet extends HttpServlet {
  
  //全ての共通の定義
  protected static final String CONTENT_TYPE = "text/html;charset=MS932"; // 7.4.0 ST2060 修正
  
  protected HashMap servletMapping=new HashMap();
  protected ServletContext context;
  private String globalError="/top.jsp";
  
  /**グローバル変数の初期化*/
  public void init(ServletConfig config) throws ServletException {
    try {
      super.init(config);
      context=config.getServletContext();
      Enumeration lEnum=config.getInitParameterNames();
      String lKey;
      while (lEnum.hasMoreElements()){
        lKey=(String)lEnum.nextElement();
        servletMapping.put(lKey,config.getInitParameter(lKey));
      }
      servletMapping.put("globalError",globalError);
    }catch(Exception e){
      e.printStackTrace();
    }
  }
  
  public void destroy() {}
  
  /**
   * <b>doGet</b>
   * Getのmethodの処理
   * @param request クライアントからリクエスト
   * @param response クライアントまでのresponse
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
  }
  
  /**
   * <b>doPost</b>
   * Postのmethodの処理
   * @param request クライアントからリクエスト
   * @param response クライアントまでのresponse
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();// DBへのコネクションの作成
    try{
      Connection lConnection = databaseConnection.getConnection();
      String sid = SILoginSession.getSessionId(request);
      // 1時間以内であればアクセス日時更新
      SIModifyRec lRec = new SIModifyRec("LOGINSESSIONTBL");
      lRec.addCondition("sessionid", sid);
      lRec.addCondition(new SITableCondition(" AND accessdate >= now() + '-1 hour' "));
      lRec.addCondition("delflg", 0);
      lRec.add("accessdate", new SISpcType("TO_CHAR(now(),'YYYY/MM/DD HH24:MI:SS')::timestamp"));
      try {
        lRec.execute(lConnection);
        lConnection.commit();
      } catch (SIDuplicateKeyException e) {
        e.printStackTrace();
        lConnection.rollback();
      } catch (SIDBAccessException e) {
        e.printStackTrace();
        lConnection.rollback();
      }
      doUpdate(request,response);
    }catch(Exception e){
      e.printStackTrace();
      request.setAttribute("servletError",e);
      //7.0.1 修正 ここから
      if (SIURLMap.isIMode(request)){
        forwardKey(request, response, "webshop.jsp.util.iservlet.error");
      }else if (SIURLMap.isAU(request)){
        forwardKey(request, response, "webshop.jsp.util.aservlet.error");
      }else if (SIURLMap.isVod(request)){
        forwardKey(request, response, "webshop.jsp.util.vservlet.error");
      }else{
        forwardKey(request, response, "webshop.jsp.util.servlet.error");
      }
      //7.0.1 修正 ここまで
    }finally{
      databaseConnection.close();
    }
  }
  
  /**
   * <b>doUpdate</b>
   * GetとPostの共通処理
   * @param request クライアントからリクエスト
   * @param response クライアントまでのresponse
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
  
  /**
   * <b>getParameter</b>
   * パラメータのデータを取得する
   * @param lUrlParam
   * @param parameterName パラメータ名
   * @return パラメータのデータ
   * @throws なし
   */
  //7.1.1 ST0236 修正 ここから
  public String getParameter(SIURLParameter lUrlParam,String lParameterName){
    return SIUtil.changeToJIS((String)lUrlParam.getParam(lParameterName));
  }
  //7.1.1 ST0236 修正 ここまで
  
  /**
   * <b>getParameterValues</b>
   * パラメータのデータ配列を取得する
   * @param request クライアントからリクエスト
   * @param parameterName パラメータ名
   * @return パラメータのデータ配列
   * @throws なし
   */
  public String[] getParameterValues(HttpServletRequest request,String lParameterName){
    String[] lParameterValues=request.getParameterValues(lParameterName);
    for(int ii=0;ii<lParameterValues.length;ii++){
      lParameterValues[ii]=SIUtil.changeToJIS(lParameterValues[ii]);
    }
    return lParameterValues;
  }
  
  /**
   * <b>forward</b>
   * 次のページへ転送するために、共通methodです。
   * @param lForwardUrl 転送先
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void forward(HttpServletRequest request, HttpServletResponse response,String lForwardUrl)throws ServletException, IOException{
    RequestDispatcher rd =getServletContext().getRequestDispatcher(lForwardUrl);//7.1.1 ST0149 修正
    rd.forward(request, response);
  }
  
  /**
   * <b>forwardKey</b>
   * 次のページへ転送するために、共通methodです。
   * @param lForwardKey 転送先のキーワード
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void forwardKey(HttpServletRequest request, HttpServletResponse response, String lForwardKey)throws ServletException, IOException{
    String lUrl = SIURLMap.getUrl(lForwardKey);
    // EDBTG005-00 nagayoshi add start
    if (SIURLMap.isSmartPhone(request)) {
      lUrl = SIURLMap.convertSmartPhoneUrl(request, lForwardKey, lUrl);
    }
    // EDBTG005-00 nagayoshi add end
    if (lUrl.trim().startsWith("/")) forward(request,response,lUrl.trim());
    else forward(request,response,"/"+lUrl.trim());
  }
  
  /**
   * <b>redirect</b>
   * 次のページへ転送するために、共通methodです。
   * @param lForwardKey 転送先のキーワード
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void redirect(HttpServletRequest request,HttpServletResponse response,String lForwardUrl)throws IOException{
    response.sendRedirect(response.encodeURL(SIHTMLUtil.consURL(request,SIHTMLUtil.getRootPath(request)+lForwardUrl)));
  }
  
  public void redirectOutside(HttpServletRequest request,HttpServletResponse response,String lForwardUrl)throws IOException{
    response.sendRedirect(response.encodeURL(lForwardUrl));
  }
  /**
   * <b>redirects</b>
   * 次のページへ転送するために、共通methodです。
   * @param lForwardKey 転送先のキーワード
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void redirectHttps(HttpServletRequest request,HttpServletResponse response,String lForwardUrl)throws IOException{
    //7.2.0 ST0242 修正 ここから
    String lUrl="";
    //8.1.6 ST2366 修正 ここから
    //if ((SIURLMap.isVod(request)||SIURLMap.isAU(request))&&SIConfig.SISSL_FLAG_CURRENT ==SIConfig.SISSL_FLAG_ENABLE){
    if ((SIURLMap.isVod(request)||SIURLMap.isAU(request)||SIURLMap.isIMode(request))&&SIConfig.SISSL_FLAG_CURRENT ==SIConfig.SISSL_FLAG_ENABLE){
    //8.1.6 ST2366 修正 ここまで
      lUrl=SIHTMLUtil.consURL(request,SIHTMLUtil.getRootPath(request)+lForwardUrl,true);
      HttpSession session=request.getSession(true);//セッションの取得
      if (lUrl.indexOf(";jsessionid=")==-1){
        int ii=lUrl.indexOf("?");
        if (ii>0)lUrl=lUrl.substring(0,ii)+";jsessionid="+session.getId()+lUrl.substring(ii);
        else lUrl=lUrl+";jsessionid="+session.getId();
      }
    }else{
      lUrl=response.encodeURL(SIHTMLUtil.consURL(request,SIHTMLUtil.getRootPath(request)+lForwardUrl,true));
    }
    response.sendRedirect(lUrl);
    //7.2.0 ST0242 修正 ここまで
  }
  
  public void redirectKey(HttpServletRequest request,HttpServletResponse response,String lForwardKey)throws IOException{
    String lUrl=SIURLMap.getUrl(lForwardKey);
    if (lUrl.trim().startsWith("/")) redirect(request,response,lUrl.trim());
    else redirect(request,response,"/"+lUrl.trim());
  }
  
  public void redirectHttpsKey(HttpServletRequest request,HttpServletResponse response,String lForwardKey)throws IOException{
    String lUrl=SIURLMap.getUrl(lForwardKey);
    if (lUrl.trim().startsWith("/")) redirectHttps(request,response,lUrl.trim());
    else redirectHttps(request,response,"/"+lUrl.trim());
  }
  /**
   * <b>getMapping</b>
   * マッピングパラメータを取得します。
   * @param lKey マッピングのキー
   * @return マッピングのキーに対するデータ
   * @throws
   */
  public String getMapping(String lKey){
    Object lResult=servletMapping.get(lKey);
    if (lResult==null) return "" ;
    if (lResult instanceof String) return (String)lResult;
    else return "";
  }
  
  /**
   * <b>getActionName</b>
   * 画面からのアクションを取得します。
   * @param lUrlParam
   * @return アクション
   * @throws
   */
  //7.1.1 ST0236 修正 ここから
  public String getActionName(SIURLParameter lUrlParam){
    String lActionName=this.getParameter(lUrlParam,"actionNameTxt");
    if (SIUtil.isNull(lActionName))return SIStringUtil.null2Space(this.getParameter(lUrlParam,"a"));
    else return lActionName;
  }
  //7.1.1 ST0236 修正 ここまで
  
  /**
   * <b>getEditMode</b>
   * DBへの編集モードを取得します。
   * @param lUrlParam
   * @return 編集モード
   * @throws
   */
  //7.1.1 ST0236 修正 ここから
  public String getEditMode(SIURLParameter lUrlParam){
    String lEditMode=this.getParameter(lUrlParam,"editModeTxt");
    if (SIUtil.isNull(lEditMode)) return "";
    else return lEditMode;
  }
  //7.1.1 ST0236 修正 ここまで
  
  public String getServletPath(HttpServletRequest request){
    return request.getServletPath();
  }
}