001/*
002 * Copyright (c) 2009 The openGion Project.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013 * either express or implied. See the License for the specific language
014 * governing permissions and limitations under the License.
015 */
016package org.opengion.hayabusa.common;
017
018import java.io.BufferedReader;
019import java.io.File;
020import java.io.InputStream;
021import java.io.InputStreamReader;
022import java.io.PrintWriter;
023import java.io.Reader;
024import java.io.UnsupportedEncodingException;
025import java.sql.Connection;
026import java.sql.PreparedStatement;
027import java.sql.ResultSet;
028import java.sql.SQLException;
029import java.sql.Statement;
030import java.util.ArrayList;
031import java.util.List;
032import java.util.Locale;
033
034import org.opengion.fukurou.util.Closer;
035import org.opengion.fukurou.util.FileUtil;
036import org.opengion.fukurou.util.StringUtil;
037import org.opengion.fukurou.util.ZipFileUtil;
038import org.opengion.fukurou.xml.HybsXMLSave;
039import org.opengion.fukurou.db.DBUtil;
040
041/**
042 * システムの自動インストールと自動更新を行います。
043 *
044 * (1)初期インストール・自動更新(#autoInsUpd)
045 *   @初期自動インストールを行うには、起動時の環境変数にINSTALL_CONTEXTSが
046 *     設定されている必要があります。
047 *     この環境変数が設定されている場合、システムリソーステーブル(GE12)が存在しなければ、
048 *     エンジンがインストールされていないと判断し、自動インストールを行います。
049 *     INSTALL_CONTEXTSにge,gfが指定されている場合は、開発環境を含めたフルバージョンが
050 *     インストールされます。
051 *     geのみが指定されている場合は、コアモジュールであるgeのみがインストールされます。
052 *
053 *     インストールスクリプトは、
054 *      webapps/[CONTEXT]/db/[DBNAME]/xml/install                       DBID=DEFAULT
055 *      webapps/[CONTEXT]/db/[DBNAME]/xml/update                        DBID=DEFAULT
056 *     以下にあるXMLファイルが全て実行されます。
057 *     また、同時に
058 *      webapps/[CONTEXT]/db/common/xml/install                         DBID=DEFAULT
059 *      webapps/[CONTEXT]/db/common/xml/update                          DBID=DEFAULT
060 *      webapps/[CONTEXT]/db/resource/xml/install                       DBID=RESOURCE   (5.6.7.0 (2013/07/27) 追加)
061 *      webapps/[CONTEXT]/db/resource/xml/update                        DBID=RESOURCE   (5.6.7.0 (2013/07/27) 追加)
062 *     以下にあるデータロードスクリプトも全て実行されます。
063 *
064 *   A自動更新については、システムリソーステーブル(GE12)の更新と、各システムの更新の2つがあります。
065 *     GE12更新の判断基準は、システムID='**'に格納されているバージョン(同一のGE12を使用し
066 *     ているシステムの最大バージョン番号)がアップした場合です。
067 *     この場合に、エンジン内部で保持しているXMLファイルよりシステムリソースの再ロードを行います。
068 *     各システムの更新の判断基準は、システムID=各システムのバージョン番号がアップされた場合です。
069 *
070 *     更新スクリプトは、
071 *      webapps/[CONTEXT]/db/[DBNAME]/xml/update                        DBID=DEFAULT
072 *     以下にあるXMLファイルが全て実行されます。
073 *     また、同時に
074 *      webapps/[CONTEXT]/db/common/xml/update                          DBID=DEFAULT
075 *      webapps/[CONTEXT]/db/resource/xml/update                        DBID=RESOURCE   (5.6.7.0 (2013/07/27) 追加)
076 *     以下にあるデータロードスクリプトも全て実行されます。
077 *
078 * (2)インストール(#install)
079 *  自動インストールは、通常は画面からコンテキストのアーカイブを指定して行います。
080 *
081 *  アーカイブの内容としては、アーカイブの直下がコンテキスト名のフォルダとなっている必要があります。
082 *  このコンテキストフォルダをwebapps以下に展開します。
083 *
084 *  また、Tomcatのコンテキストの設定ファイル、([CONTEXT].xml)が"WEB-INFの直下を配置している必要があります。
085 *
086 *  このインストールでは、Tomcatに対するコンテキスト定義のXMLファイルの配備及び、
087 *  各種DB、データのロードを行います。
088 *
089 *  インストールスクリプトは、
090 *   webapps/[CONTEXT]/db/[DBNAME]/xml/install                          DBID=DEFAULT
091 *  以下にあるXMLファイルが全て実行されます。
092 *  また、同時に
093 *   webapps/[CONTEXT]/db/common/xml/install                            DBID=DEFAULT
094 *   webapps/[CONTEXT]/db/resource/xml/install                          DBID=RESOURCE   (5.6.7.0 (2013/07/27) 追加)
095 *  以下にあるデータロードスクリプトも全て実行されます。
096 *
097 * @og.rev 4.3.6.6 (2009/05/15) 新規作成
098 * @og.group 初期化
099 *
100 * @version  4.0
101 * @author   Hiroki Nakamura
102 * @since    JDK5.0,
103 */
104public final class SystemInstaller {
105//      private final String VERSION;                   // 5.5.4.4 (2012/07/20) VERSION は、直接 BuildNumber.ENGINE_INFO を使用。
106//      private final Connection connection;
107        private final Connection defConn;               // 5.6.7.0 (2013/07/27) DBID=DEFAULT  のコネクション
108        private final Connection rscConn;               // 5.6.7.0 (2013/07/27) DBID=RESOURCE のコネクション
109        private final PrintWriter out;                  // 5.1.9.0 (2010/08/01)
110        private final String DBNAME;                    // 5.5.4.4 (2012/07/20) 共通化 (DBID=DEFAULT のDB名)
111
112        /** エンジン共通パラメータ(SYSTEM_ID='**' KBSAKU='0')のXML ファイルの指定  {@value}        */
113        public static final String GE12_XML = "org/opengion/hayabusa/common/GE12.xml";
114
115        /** エンジン共通パラメータ(SYSTEM_ID='**' KBSAKU='0')のENGINE_INFO 読み取りクエリー {@value}        */
116        public static final String SEL_MAX_ENG = "select PARAM from GE12"
117                                                                        + " where SYSTEM_ID='**' and PARAM_ID='ENGINE_INFO'"
118                                                                        + " and FGJ='1' and KBSAKU='0'" ;
119
120        /** エンジン個別(SYSTEM_ID='個別' KBSAKU='0'  CONTXT_PATH='自身')のバージョン情報を取得するクエリーー{@value} 4.3.6.6 (2009/05/15) */
121        public static final String SEL_SYS_ENG = "select PARAM from GE12"
122                                                                        + " where SYSTEM_ID=? and PARAM_ID='ENGINE_INFO' and KBSAKU='0' and CONTXT_PATH=? and FGJ='1'";
123
124        private static final String FS                  = File.separator ;                                              // 5.5.4.4 (2012/07/20) static化
125        private static final String APP_BASE    = System.getenv( "APP_BASE" ) + FS;             // 5.5.4.4 (2012/07/20) static化
126
127
128        /**
129         * データベース処理をおこなうに当たり、処理のタイプを指定するための、enum 定義です。
130         * 文字列で扱っていた箇所を、enum と置き換えます。
131         *
132         * @og.rev 5.5.4.4 (2012/07/20) 新規追加
133         */
134        private static enum EXEC_TYPE { INSTALL , UPDATE } ;
135
136        /**
137         * システムインストール・更新クラスのコンストラクタです
138         *
139         * なお、このクラスの中の処理で、エラーが発生しても、Connection は、close 等しません。
140         * 呼び出し元で、try 〜 finally で、処理してください。
141         *
142         * @og.rev 5.5.4.4 (2012/07/20) VERSIONは、直接 BuildNumber.ENGINE_INFO を使用。
143         * @og.rev 5.6.7.0 (2013/07/27) アプリケーション登録用とリソース登録用のコネクションを分ける
144         * @og.rev 5.9.19.0 (2017/04/07) DBNAMEの取得をタイプにする
145         * @og.rev 5.9.24.1 (2017/09/08) DB名を出力する
146         *
147         * @param       defConn アプリケーション登録用コネクション
148         * @param       rscConn リソース登録用コネクション
149         * @param       out     表示用のWriter
150         */
151//      public SystemInstaller( final Connection conn, final PrintWriter out ) {
152        public SystemInstaller( final Connection defConn, final Connection rscConn, final PrintWriter out ) {
153//              connection = conn;
154                this.defConn = defConn;                 // 5.6.7.0 (2013/07/27) アプリケーション登録用
155                this.rscConn = rscConn;                 // 5.6.7.0 (2013/07/27) リソース登録用
156                this.out = out;
157
158//              VERSION = BuildNumber.ENGINE_INFO;
159
160                // 5.6.7.0 (2013/07/27) ProductName は、DBUtil 経由で取得する。
161//              String dbName ;
162//              try {
163//                      dbName = connection.getMetaData().getDatabaseProductName().toLowerCase( Locale.JAPAN );
164//              }
165//              catch( SQLException ex ) {
166//                      out.println( "        -> DatabaseProductName is NONE " + ex.getMessage() );
167//                      dbName = "none";
168//              }
169//              DBNAME = dbName;
170
171//              DBNAME = DBUtil.getProductName( defConn );              // 5.6.7.0 (2013/07/27) DBID=DEFAULT  のDB名
172//              DBNAME = DBUtil.getDBType( DBUtil.getProductName( defConn )); //5.9.19.0 (2017/04/07) DB種別で取るようにする
173                String DBPdcName = DBUtil.getProductName( defConn ); // 5.9.24.1 productNameの表示
174                out.println( "    Database Information ( " + DBPdcName + " )" ); 
175                DBNAME = DBUtil.getDBType(DBPdcName); 
176        }
177
178        /**
179         * システムの初期自動インストール・自動更新を行います。
180         *
181         * 詳細は、クラスドキュメントを参照して下さい。
182         *
183         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
184         * @og.rev 5.5.4.4 (2012/07/20) VERSIONは、直接 BuildNumber.ENGINE_INFO を使用。
185         *
186         * @param systemId システムID
187         * @param context コンテキスト名
188         * @param hostUrl ホスト文字列
189         * @throws UnsupportedEncodingException エンコード名 "UTF-8" が存在しなかった場合。
190         * @see   #dbXMLResourceInsert()
191         */
192//      public void autoInsUpd( final String systemId, final String context, final String hostUrl ) throws SQLException, UnsupportedEncodingException  {
193        public void autoInsUpd( final String systemId, final String context, final String hostUrl ) throws UnsupportedEncodingException  {
194                String oldMaxVersion = getOldMaxVersion();
195                String oldSystemVersion = getOldSystemVersion( systemId, hostUrl );
196
197                out.println( "    System Version Information ( " + systemId + " )" );
198//              out.println( "      Load Version [ " + VERSION + " ]" );
199                out.println( "      Load Version [ " + BuildNumber.ENGINE_INFO + " ]" );                // 5.5.4.4 (2012/07/20)
200                out.println( "        -> Resource Version[ " + oldMaxVersion + " ]" );
201                out.println( "        -> System   Version[ " + oldSystemVersion + " ]" );
202
203                // 初期自動インストール
204                if( "none".equalsIgnoreCase( oldMaxVersion ) ) {
205                        out.println( "      !!! openGion ENVIROMENT IS NOT INSTALLED !!!" );
206
207                        String INSTALL_CONTEXTS = System.getenv( "INSTALL_CONTEXTS" );
208                        if( INSTALL_CONTEXTS == null || INSTALL_CONTEXTS.length() == 0 ) {
209                                out.println( "        !!! \"INSTALL_CONTEXT\" IS NOT CONFIGURED\" !!!" );
210                                out.println( "        !!! \"SET ENRIVOMENT PARAMETER NAMED \"INSTALL_CONTEXT\" ON INIT_SCRIPT !!!" );
211                                return;
212                        }
213                        out.println( "      Start Initiall Enviroment Install : install type ( " + INSTALL_CONTEXTS + " )" );
214                        String[] insSys = StringUtil.csv2Array( INSTALL_CONTEXTS );
215                        for( int i=0; i<insSys.length; i++ ) {
216                                out.println( "        install    ( " + insSys[i] + " )" );
217//                              loadXMLScript( "install", insSys[i] );
218                                loadXMLScript( EXEC_TYPE.INSTALL, insSys[i] );
219//                              connection.commit();
220//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
221                                out.println( "        completed  ( " + insSys[i] + " )" );
222                        }
223
224                        out.println( "      Start SystemParameter reload" );
225                        dbXMLResourceInsert();
226//                      connection.commit();
227//                      Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
228                        out.println( "      completed" );
229                }
230                // 自動更新
231                else {
232//                      if ( oldSystemVersion == null || oldSystemVersion.compareTo( VERSION ) < 0 ){
233                        if ( oldSystemVersion == null || oldSystemVersion.compareTo( BuildNumber.ENGINE_INFO ) < 0 ){                // 5.5.4.4 (2012/07/20)
234                                out.println( "      Start Enviroment Update ( " + context + " )" );
235//                              loadXMLScript( "update", context );
236                                loadXMLScript( EXEC_TYPE.UPDATE , context );
237//                              connection.commit();
238//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
239                                out.println( "      completed               ( " + context + " )" );
240                        }
241
242//                      if( oldMaxVersion == null || oldMaxVersion.compareTo( VERSION ) < 0 ){
243                        if( oldMaxVersion == null || oldMaxVersion.compareTo( BuildNumber.ENGINE_INFO ) < 0 ){                               // 5.5.4.4 (2012/07/20)
244                                out.println( "      Start SystemParameter Reload" );
245                                dbXMLResourceInsert();
246//                              connection.commit();
247//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
248                                out.println( "      completed" );
249                        }
250                }
251        }
252
253        /**
254         * システムの自動インストールを行います。
255         *
256         * 詳細は、クラスドキュメントを参照して下さい。
257         *
258         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
259         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE を、共通に設定
260         *
261         * @param buildArchive コンテキストのアーカイブファイル
262         */
263//      public void install( final File buildArchive ) throws SQLException {
264        public void install( final File buildArchive ) {
265//              final String FS       = File.separator ;
266//              final String tempDir  = HybsSystem.sys( "REAL_PATH" ) + HybsSystem.sys( "FILE_URL" ) + String.valueOf( System.currentTimeMillis() + FS );
267                final String tempDir  = HybsSystem.sys( "REAL_PATH" ) + HybsSystem.sys( "FILE_URL" ) + System.currentTimeMillis() + FS;
268                final String ctxtXmlDir = System.getenv( "CATALINA_HOME" ) + FS + "conf" + FS + System.getenv( "ENGINE_NAME" ) + FS + "localhost" + FS;
269//              final String appBase  = System.getenv( "APP_BASE" ) + FS;               // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
270
271                out.println( "      Check Archive File and Enviroment" );
272
273                // アーカイブの存在チェック
274                if( !buildArchive.exists() ) {
275                        out.println( "        !!! Archive File does not exists File=[ " + buildArchive.getAbsolutePath() + "] !!!" );
276                        out.println( "        !!! Install Aborted !!! " );
277                        return;
278                }
279
280                // アーカイブを一時ファイルに展開します。
281                ZipFileUtil.unCompress( tempDir, buildArchive.getAbsolutePath() );
282
283                // アーカイブの内容チェック
284                File[] ctxts = new File( tempDir ).listFiles();
285                for( File ctxt : ctxts ) {
286                        // 5.1.9.0 (2010/08/01) if の条件を入れ替えます。(Avoid if (x != y) ..; else ..;)
287                        String context = ctxt.getName();
288                        if( ctxt.isDirectory() ) {
289//                              String context = ctxt.getName();
290
291                                // アーカイブ中に[CONTEXT].xmlが存在していない場合はエラー(何も処理しない)
292                                File srcCtxtXml = new File( tempDir + context + FS + "WEB-INF" + FS + context + ".xml" );
293                                if( !srcCtxtXml.exists() ) {
294                                        out.println( "        !!! Context XML Does not exists =[ " + srcCtxtXml.getAbsolutePath() + "] !!!" );
295                                        out.println( "        !!! Install Aborted !!! " );
296                                        return;
297                                }
298
299                                // [CONTEXT].xmlが既に存在している場合はエラー(何も処理しない)
300                                File ctxtXml = new File(  ctxtXmlDir + context + ".xml" );
301                                if( ctxtXml.exists() ) {
302                                        out.println( "        !!! Context XML File Already Installed File=[ " + ctxtXml.getAbsolutePath() + "] !!!" );
303                                        out.println( "        !!! Install Aborted !!! " );
304                                        return;
305                                }
306
307                                // webapps/[CONTEXT]が既に存在している場合はエラー(何も処理しない)
308//                              File webAppsDir = new File( appBase + context );                // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
309                                File webAppsDir = new File( APP_BASE + context );
310                                if( webAppsDir.exists() ) {
311                                        out.println( "        !!! Context Path Already Exists Path=[ " + webAppsDir.getAbsolutePath() + "] !!!" );
312                                        out.println( "        !!! Install Aborted !!! " );
313                                        return;
314                                }
315
316//                              out.println( "        This Archive includes SYSTEM ( " + ctxt.getName() + " ) for Install" );
317                                out.println( "        This Archive includes SYSTEM ( " + context + " ) for Install" );                  // 5.5.4.4 (2012/07/20)
318                        }
319                        // ファイルが含まれている場合はエラー(何も処理しない)
320                        else {
321//                              out.println( "        !!! This Archive is not Installer. Because include FILE not DIRECTORY. File=[ " + ctxt.getName() + "] !!!" );
322                                out.println( "        !!! This Archive is not Installer. Because include FILE not DIRECTORY. File=[ " + context + "] !!!" );    // 5.5.4.4 (2012/07/20)
323                                out.println( "        !!! Install Aborted !!! " );
324                                return;
325                        }
326                }
327
328                // アーカイブをコンテキストファイル以下にコピー
329                for( File ctxt : ctxts ) {
330                        String context = ctxt.getName();
331                        out.println( "      Start Enviroment Install ( " + context + " )" );
332
333                        // コンテキストのファイルをコピーします。
334//                      FileUtil.copyDirectry( tempDir + context, appBase + context );          // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
335                        FileUtil.copyDirectry( tempDir + context, APP_BASE + context );
336
337                        // [CONTEXT].xmlをTomcatのconf以下に展開します。
338                        FileUtil.copy( tempDir + context + FS + "WEB-INF" + FS + context + ".xml", ctxtXmlDir + context + ".xml" );
339
340                        // DBスクリプトをロードします。
341//                      loadXMLScript( "install", context );
342                        loadXMLScript( EXEC_TYPE.INSTALL , context );
343//                      connection.commit();
344//                      Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
345                        out.println( "      completed                ( " + context + " )" );
346                }
347                out.println( "      Install Process All Completed." );
348        }
349
350        /**
351         * インストール、更新用のXMLスクリプトをロードします。
352         *
353         * @og.rev 5.0.0.2 (2009/09/15) .xmlファイル以外は読み込まないように修正
354         * @og.rev 5.1.1.0 (2009/12/01) コメントを出して、処理中ということが判る様にします。
355         * @og.rev 5.1.9.0 (2010/08/01) DB非依存の定義・データの読み込み対応
356         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE , DBNAME を、共通に設定
357         * @og.rev 5.6.7.0 (2013/07/27) アプリケーション登録用とリソース登録用のコネクションを分ける
358         *
359         * @param       type    更新タイプ[EXEC_TYPE.INSTALL/EXEC_TYPE.UPDATE]
360         * @param       context コンテキスト名
361         */
362//      private void loadXMLScript( final String type, final String context ) throws SQLException {
363        private void loadXMLScript( final EXEC_TYPE type, final String context ) {
364//              final String FS       = File.separator ;
365//              final String APP_BASE = System.getenv( "APP_BASE" );            // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
366//              final String DBNAME   = connection.getMetaData().getDatabaseProductName().toLowerCase( Locale.JAPAN );
367
368                // DB名からスクリプトを格納しているフォルダを探します。
369//              String scriptBase = APP_BASE + FS + context.toLowerCase( Locale.JAPAN ) + FS + "db";
370                String scriptBase = APP_BASE + context.toLowerCase( Locale.JAPAN ) + FS + "db";
371                File[] dbDir = new File( scriptBase ).listFiles();
372                if( dbDir == null || dbDir.length == 0 ) {
373                        out.println( "             DB Folder not found. [" + scriptBase + "]"  );
374                        return;
375                }
376
377                String scriptPath = null;
378                for ( int i = 0; i < dbDir.length; i++ ) {
379                        if ( DBNAME.indexOf( dbDir[i].getName() ) >= 0 ) {
380                                scriptPath = dbDir[i].getAbsolutePath();
381                                break;
382                        }
383                }
384                if( scriptPath == null ) {
385                        out.println( "             !!! Script Folder for [ " + DBNAME + " ] not found !!!" );
386                        return;
387                }
388
389                // webapps/[CONTEXT]/db/[DBNAME]/
390//              execScripts( scriptPath, type );
391//              execScripts( type , scriptPath );                               // 5.5.4.4 (2012/07/20) typeのenum化と、引数の順番を親に合わす。
392                execScripts( type , scriptPath , defConn );             // 5.6.7.0 (2013/07/27) DBID=DEFAULT に登録
393
394                // 5.1.9.0 (2010/08/01) DB非依存の定義・データの読み込み対応
395                // webapps/[CONTEXT]/db/common/
396//              execScripts( scriptBase + FS + "common" + FS, type );
397//              execScripts( type , scriptBase + FS + "common" );                               // 5.5.4.4 (2012/07/20) typeのenum化と、引数の順番を親に合わす。
398                execScripts( type , scriptBase + FS + "common" , defConn );             // 5.6.7.0 (2013/07/27) DBID=DEFAULT に登録
399
400                // 5.6.7.0 (2013/07/27) DBID=RESOURCE に登録
401                // webapps/[CONTEXT]/db/resource/
402                execScripts( type , scriptBase + FS + "resource" , rscConn );   // 5.6.7.0 (2013/07/27) DBID=RESOURCE に登録
403
404//              // webapps/[CONTEXT]/db/xml 内のスクリプトを実行します
405//              File[] dataDir = new File( scriptBase + FS + "xml" ).listFiles();
406//              if( dataDir != null && dataDir.length > 0 ) {
407//                      for ( int i=0; i<dataDir.length; i++ ) {
408//                              String dtNm = dataDir[i].getName() ;
409//                              if( dtNm.endsWith( ".xml" ) ) {         // 5.0.0.2 (2009/09/15)
410//                                      Reader reader = new BufferedReader( FileUtil.getBufferedReader( dataDir[i], "UTF-8" ) );
411//                                      HybsXMLSave save = new HybsXMLSave( connection, dtNm );
412//                                      save.insertXML( reader );
413//                              }
414//                      }
415//                      out.println( "            DB Data Files Installed , [ " + dataDir.length + " ] files loaded " );
416//              }
417        }
418
419        /**
420         * XMLファイルで定義されたDBスクリプトを実行します。
421         *
422         * 引数のtypeに応じて、処理するフォルダが異なります。
423         *   type=INSTALL の場合は、[scriptPath]/xml/install と、[scriptPath]/xml/update 以下の xml ファイル
424         *   type=それ以外の場合は、[scriptPath]/xml/update 以下の xml ファイル
425         * です。
426         *
427         * 現時点では、scriptPath には、下記の 3種類のアドレスが渡され、それぞれ、登録するコネクションが異なります。
428         *   webapps/[CONTEXT]/db/[DBNAME]/                     DBID=DEFAULT
429         *   webapps/[CONTEXT]/db/common/                       DBID=DEFAULT
430         *   webapps/[CONTEXT]/db/resource/                     DBID=RESOURCE
431         *
432         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
433         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE を、共通に設定
434         * @og.rev 5.5.8.4 (2012/11/22) firebird対応。フォルダ単位commitを行う
435         * @og.rev 5.6.7.0 (2013/07/27) Connection引数追加。リソースとアプリを切り分ける。
436         * @og.rev 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
437         *
438         * @param       type            更新タイプ[EXEC_TYPE.INSTALL/EXEC_TYPE.UPDATE]
439         * @param       scriptPath      XMLファイルのあるパス
440         * @param       conn            コネクションオブジェクト
441         */
442//      private void execScripts( final String scriptPath, final String type ) {
443//      private void execScripts( final EXEC_TYPE type, final String scriptPath ) {
444        private void execScripts( final EXEC_TYPE type, final String scriptPath, final Connection conn ) {
445//              final String FS       = File.separator ;
446
447                // webapps/[CONTEXT]/db/[DBNAME]/xml/(install|update) 内のスクリプトを実行します
448                List<String> list = new ArrayList<String>();
449
450//              if( "install".equalsIgnoreCase( type ) ) {
451                if( type == EXEC_TYPE.INSTALL ) {
452                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "install" ), true, list );
453//                      FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update" + FS + "const" ), true, list );
454                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update"  ), true, list );
455                }
456                else {
457//                      FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update" + FS + "const" ), true, list );
458                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update"  ), true, list );
459
460                        /*******************************************************************************
461                         * updateの場合に、更新前のバージョンからの変更スクリプトを実行する機能が必要
462                         *******************************************************************************/
463                }
464
465                if( ! list.isEmpty() ) {
466                        String dir1 = null;             // 5.1.1.0 (2009/12/01)
467                        for ( String name : list ) {
468                                if( name.endsWith( ".xml" ) ) {         // 5.0.0.2 (2009/09/15)
469                                        File xml = new File( name );
470                                        // 5.1.1.0 (2009/12/01) 処理中コメント:フォルダ単位に表示
471                                        String dir2 = xml.getParent();
472                                        if( dir1 == null || !dir1.equalsIgnoreCase( dir2 ) ) {
473                                                out.println( "            processing ... " + dir2 );
474                                                dir1 = dir2;
475//                                              Closer.commit( connection );    // 5.5.8.4 (2012/11/22)
476                                                Closer.commit( conn );                  // 5.6.7.0 (2013/07/27) Connection引数追加
477                                        }
478
479                                        Reader reader = new BufferedReader( FileUtil.getBufferedReader( xml, "UTF-8" ) );
480//                                      HybsXMLSave save = new HybsXMLSave( connection, xml.getName() );
481                                        HybsXMLSave save = new HybsXMLSave( conn, xml.getName() );                      // 5.6.7.0 (2013/07/27) Connection引数追加
482                                        save.onExecErrException( false );               // 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
483                                        save.insertXML( reader );
484                                }
485                        }
486                        Closer.commit( conn );                  // 5.6.7.0 (2013/07/27) メソッド内でコミット処理を行う。
487                        out.println( "            DB Enviroment " + type + "ed , [ " + list.size() + " ] scripts loaded " );
488                }
489        }
490
491        /**
492         * 最後に起動された際のバージョン番号を取得します。(システムID='**')
493         *
494         * エンジンがまだインストールされていない等の原因でエラーが発生した場合は、
495         * "none"という文字列を返します。
496         *
497         * @og.rev 5.1.1.0 (2009/12/01) 実行エラー時に、rollback を追加(PostgreSQL対応)
498         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションから取り出します。
499         * @og.rev 5.7.2.0 (2014/01/10) テーブルが無いのに正常終了するケースがある為、ver の初期値を "none" にしておきます。
500         *
501         * @return      バージョン番号
502         */
503        private String getOldMaxVersion() {
504                // エンジンパラメータのエンジン情報(バージョン番号 + ビルドタイプ)を取得します。
505                Statement                       stmt            = null;
506                ResultSet                       resultSet       = null;
507//              String                          ver             = null;
508                String                          ver             = "none";                               // 5.7.2.0 (2014/01/10) 初期値を null ⇒ "none" へ変更。
509                try {
510//                      stmt = connection.createStatement();
511                        stmt = rscConn.createStatement();                                       // 5.6.7.0 (2013/07/27)
512                        resultSet = stmt.executeQuery( SEL_MAX_ENG );
513                        while( resultSet.next() ) {
514                                ver = resultSet.getString(1);
515                        }
516                }
517                catch( SQLException ex ) {
518//                      ver = "none";                                           // 5.7.2.0 (2014/01/10) 初期値を変更したため、設定不要。
519//                      Closer.rollback( connection );          // 5.1.1.0 (2009/12/01)
520                        Closer.rollback( rscConn );                     // 5.6.7.0 (2013/07/27)
521                }
522                finally {
523                        Closer.resultClose( resultSet );
524                        Closer.stmtClose( stmt );
525                }
526                return ver;
527        }
528
529        /**
530         * 最後に起動された際のバージョン番号を取得します。(システムID=各システム)
531         *
532         * @og.rev 5.1.1.0 (2009/12/01) 実行エラー時に、rollback を追加(PostgreSQL対応)
533         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションから取り出します。
534         *
535         * @param       systemId        システムID
536         * @param       hostUrl         ホストURL
537         *
538         * @return      バージョン番号
539         */
540        private String getOldSystemVersion( final String systemId, final String hostUrl ) {
541                // エンジンパラメータのエンジン情報(バージョン番号 + ビルドタイプ)を取得します。
542                PreparedStatement       pstmt           = null;
543                ResultSet                       resultSet       = null;
544                String                          ver             = null;
545                try {
546//                      pstmt = connection.prepareStatement( SEL_SYS_ENG );
547                        pstmt = rscConn.prepareStatement( SEL_SYS_ENG );                // 5.6.7.0 (2013/07/27)
548                        pstmt.setString( 1, systemId );
549                        pstmt.setString( 2, hostUrl );
550                        resultSet = pstmt.executeQuery();
551                        while( resultSet.next() ) {
552                                ver = resultSet.getString(1);
553                        }
554                }
555                catch( SQLException ex ) {
556//                      Closer.rollback( connection );          // 5.1.1.0 (2009/12/01)
557                        Closer.rollback( rscConn );                     // 5.6.7.0 (2013/07/27)
558                }
559                finally {
560                        Closer.resultClose( resultSet );
561                        Closer.stmtClose( pstmt );
562                }
563                return ver;
564        }
565
566        /**
567         * エンジン内部定義の初期リソース情報をDB(GE12)に登録します。
568         *
569         * 初期リソース情報は、KBSAKU='0' で登録されている情報で、一旦すべて削除
570         * してから、全てのリソース情報を追加するという形をとります。
571         * リソースは、すでに、Oracle XDK により XMLファイル化してあります。
572         * なお、この情報をDB登録する理由は、リソースの設定値を変えたい場合に、
573         * キーが判らない(JavaDOCからしか読み取れない)のでは不便な為に
574         * 用意しておくだけで、内部では SystemData オブジェクトとして定義
575         * されている値を使用するため、このデータベース値は、使用していません。
576         *
577         * @og.rev 4.3.6.6 (2009/05/15) バージョン判定部分を分離
578         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションに登録します。
579         * @og.rev 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
580         *
581         * @throws UnsupportedEncodingException エンコード名 "UTF-8" が存在しなかった場合。
582         */
583        private void dbXMLResourceInsert() throws UnsupportedEncodingException {
584                // 新設定値を全件INSERTします。
585                // common フォルダにセットして、ClassLoader で読み取る方法
586                ClassLoader loader = Thread.currentThread().getContextClassLoader();
587                InputStream stream = loader.getResourceAsStream( GE12_XML );
588
589                Reader reader = new BufferedReader( new InputStreamReader( stream,"UTF-8" ) );
590//              HybsXMLSave save = new HybsXMLSave( connection,"GE12" );
591                HybsXMLSave save = new HybsXMLSave( rscConn,"GE12" );                   // 5.6.7.0 (2013/07/27)
592                save.onExecErrException( false );               // 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
593                save.insertXML( reader );
594                int insCnt = save.getInsertCount();
595                int delCnt = save.getDeleteCount();
596
597                out.print( "        XML Engine Resource Reconfiguration " );
598                out.println( "DELETE=[" + delCnt + "],INSERT=[" + insCnt + "] finished." );
599
600                // 5.6.7.0 (2013/07/27) コミットをメソッドの中で処理します。
601                Closer.commit( rscConn );
602        }
603}