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         *
145         * @param       defConn アプリケーション登録用コネクション
146         * @param       rscConn リソース登録用コネクション
147         * @param       out     表示用のWriter
148         */
149//      public SystemInstaller( final Connection conn, final PrintWriter out ) {
150        public SystemInstaller( final Connection defConn, final Connection rscConn, final PrintWriter out ) {
151//              connection = conn;
152                this.defConn = defConn;                 // 5.6.7.0 (2013/07/27) アプリケーション登録用
153                this.rscConn = rscConn;                 // 5.6.7.0 (2013/07/27) リソース登録用
154                this.out = out;
155
156//              VERSION = BuildNumber.ENGINE_INFO;
157
158                // 5.6.7.0 (2013/07/27) ProductName は、DBUtil 経由で取得する。
159//              String dbName ;
160//              try {
161//                      dbName = connection.getMetaData().getDatabaseProductName().toLowerCase( Locale.JAPAN );
162//              }
163//              catch( SQLException ex ) {
164//                      out.println( "        -> DatabaseProductName is NONE " + ex.getMessage() );
165//                      dbName = "none";
166//              }
167//              DBNAME = dbName;
168
169                DBNAME = DBUtil.getProductName( defConn );              // 5.6.7.0 (2013/07/27) DBID=DEFAULT  のDB名
170        }
171
172        /**
173         * システムの初期自動インストール・自動更新を行います。
174         *
175         * 詳細は、クラスドキュメントを参照して下さい。
176         *
177         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
178         * @og.rev 5.5.4.4 (2012/07/20) VERSIONは、直接 BuildNumber.ENGINE_INFO を使用。
179         *
180         * @param systemId システムID
181         * @param context コンテキスト名
182         * @param hostUrl ホスト文字列
183         * @throws UnsupportedEncodingException エンコード名 "UTF-8" が存在しなかった場合。
184         * @see   #dbXMLResourceInsert()
185         */
186//      public void autoInsUpd( final String systemId, final String context, final String hostUrl ) throws SQLException, UnsupportedEncodingException  {
187        public void autoInsUpd( final String systemId, final String context, final String hostUrl ) throws UnsupportedEncodingException  {
188                String oldMaxVersion = getOldMaxVersion();
189                String oldSystemVersion = getOldSystemVersion( systemId, hostUrl );
190
191                out.println( "    System Version Information ( " + systemId + " )" );
192//              out.println( "      Load Version [ " + VERSION + " ]" );
193                out.println( "      Load Version [ " + BuildNumber.ENGINE_INFO + " ]" );                // 5.5.4.4 (2012/07/20)
194                out.println( "        -> Resource Version[ " + oldMaxVersion + " ]" );
195                out.println( "        -> System   Version[ " + oldSystemVersion + " ]" );
196
197                // 初期自動インストール
198                if( "none".equalsIgnoreCase( oldMaxVersion ) ) {
199                        out.println( "      !!! openGion ENVIROMENT IS NOT INSTALLED !!!" );
200
201                        String INSTALL_CONTEXTS = System.getenv( "INSTALL_CONTEXTS" );
202                        if( INSTALL_CONTEXTS == null || INSTALL_CONTEXTS.length() == 0 ) {
203                                out.println( "        !!! \"INSTALL_CONTEXT\" IS NOT CONFIGURED\" !!!" );
204                                out.println( "        !!! \"SET ENRIVOMENT PARAMETER NAMED \"INSTALL_CONTEXT\" ON INIT_SCRIPT !!!" );
205                                return;
206                        }
207                        out.println( "      Start Initiall Enviroment Install : install type ( " + INSTALL_CONTEXTS + " )" );
208                        String[] insSys = StringUtil.csv2Array( INSTALL_CONTEXTS );
209                        for( int i=0; i<insSys.length; i++ ) {
210                                out.println( "        install    ( " + insSys[i] + " )" );
211//                              loadXMLScript( "install", insSys[i] );
212                                loadXMLScript( EXEC_TYPE.INSTALL, insSys[i] );
213//                              connection.commit();
214//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
215                                out.println( "        completed  ( " + insSys[i] + " )" );
216                        }
217
218                        out.println( "      Start SystemParameter reload" );
219                        dbXMLResourceInsert();
220//                      connection.commit();
221//                      Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
222                        out.println( "      completed" );
223                }
224                // 自動更新
225                else {
226//                      if ( oldSystemVersion == null || oldSystemVersion.compareTo( VERSION ) < 0 ){
227                        if ( oldSystemVersion == null || oldSystemVersion.compareTo( BuildNumber.ENGINE_INFO ) < 0 ){                // 5.5.4.4 (2012/07/20)
228                                out.println( "      Start Enviroment Update ( " + context + " )" );
229//                              loadXMLScript( "update", context );
230                                loadXMLScript( EXEC_TYPE.UPDATE , context );
231//                              connection.commit();
232//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
233                                out.println( "      completed               ( " + context + " )" );
234                        }
235
236//                      if( oldMaxVersion == null || oldMaxVersion.compareTo( VERSION ) < 0 ){
237                        if( oldMaxVersion == null || oldMaxVersion.compareTo( BuildNumber.ENGINE_INFO ) < 0 ){                               // 5.5.4.4 (2012/07/20)
238                                out.println( "      Start SystemParameter Reload" );
239                                dbXMLResourceInsert();
240//                              connection.commit();
241//                              Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
242                                out.println( "      completed" );
243                        }
244                }
245        }
246
247        /**
248         * システムの自動インストールを行います。
249         *
250         * 詳細は、クラスドキュメントを参照して下さい。
251         *
252         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
253         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE を、共通に設定
254         *
255         * @param buildArchive コンテキストのアーカイブファイル
256         */
257//      public void install( final File buildArchive ) throws SQLException {
258        public void install( final File buildArchive ) {
259//              final String FS       = File.separator ;
260//              final String tempDir  = HybsSystem.sys( "REAL_PATH" ) + HybsSystem.sys( "FILE_URL" ) + String.valueOf( System.currentTimeMillis() + FS );
261                final String tempDir  = HybsSystem.sys( "REAL_PATH" ) + HybsSystem.sys( "FILE_URL" ) + System.currentTimeMillis() + FS;
262                final String ctxtXmlDir = System.getenv( "CATALINA_HOME" ) + FS + "conf" + FS + System.getenv( "ENGINE_NAME" ) + FS + "localhost" + FS;
263//              final String appBase  = System.getenv( "APP_BASE" ) + FS;               // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
264
265                out.println( "      Check Archive File and Enviroment" );
266
267                // アーカイブの存在チェック
268                if( !buildArchive.exists() ) {
269                        out.println( "        !!! Archive File does not exists File=[ " + buildArchive.getAbsolutePath() + "] !!!" );
270                        out.println( "        !!! Install Aborted !!! " );
271                        return;
272                }
273
274                // アーカイブを一時ファイルに展開します。
275                ZipFileUtil.unCompress( tempDir, buildArchive.getAbsolutePath() );
276
277                // アーカイブの内容チェック
278                File[] ctxts = new File( tempDir ).listFiles();
279                for( File ctxt : ctxts ) {
280                        // 5.1.9.0 (2010/08/01) if の条件を入れ替えます。(Avoid if (x != y) ..; else ..;)
281                        String context = ctxt.getName();
282                        if( ctxt.isDirectory() ) {
283//                              String context = ctxt.getName();
284
285                                // アーカイブ中に[CONTEXT].xmlが存在していない場合はエラー(何も処理しない)
286                                File srcCtxtXml = new File( tempDir + context + FS + "WEB-INF" + FS + context + ".xml" );
287                                if( !srcCtxtXml.exists() ) {
288                                        out.println( "        !!! Context XML Does not exists =[ " + srcCtxtXml.getAbsolutePath() + "] !!!" );
289                                        out.println( "        !!! Install Aborted !!! " );
290                                        return;
291                                }
292
293                                // [CONTEXT].xmlが既に存在している場合はエラー(何も処理しない)
294                                File ctxtXml = new File(  ctxtXmlDir + context + ".xml" );
295                                if( ctxtXml.exists() ) {
296                                        out.println( "        !!! Context XML File Already Installed File=[ " + ctxtXml.getAbsolutePath() + "] !!!" );
297                                        out.println( "        !!! Install Aborted !!! " );
298                                        return;
299                                }
300
301                                // webapps/[CONTEXT]が既に存在している場合はエラー(何も処理しない)
302//                              File webAppsDir = new File( appBase + context );                // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
303                                File webAppsDir = new File( APP_BASE + context );
304                                if( webAppsDir.exists() ) {
305                                        out.println( "        !!! Context Path Already Exists Path=[ " + webAppsDir.getAbsolutePath() + "] !!!" );
306                                        out.println( "        !!! Install Aborted !!! " );
307                                        return;
308                                }
309
310//                              out.println( "        This Archive includes SYSTEM ( " + ctxt.getName() + " ) for Install" );
311                                out.println( "        This Archive includes SYSTEM ( " + context + " ) for Install" );                  // 5.5.4.4 (2012/07/20)
312                        }
313                        // ファイルが含まれている場合はエラー(何も処理しない)
314                        else {
315//                              out.println( "        !!! This Archive is not Installer. Because include FILE not DIRECTORY. File=[ " + ctxt.getName() + "] !!!" );
316                                out.println( "        !!! This Archive is not Installer. Because include FILE not DIRECTORY. File=[ " + context + "] !!!" );    // 5.5.4.4 (2012/07/20)
317                                out.println( "        !!! Install Aborted !!! " );
318                                return;
319                        }
320                }
321
322                // アーカイブをコンテキストファイル以下にコピー
323                for( File ctxt : ctxts ) {
324                        String context = ctxt.getName();
325                        out.println( "      Start Enviroment Install ( " + context + " )" );
326
327                        // コンテキストのファイルをコピーします。
328//                      FileUtil.copyDirectry( tempDir + context, appBase + context );          // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
329                        FileUtil.copyDirectry( tempDir + context, APP_BASE + context );
330
331                        // [CONTEXT].xmlをTomcatのconf以下に展開します。
332                        FileUtil.copy( tempDir + context + FS + "WEB-INF" + FS + context + ".xml", ctxtXmlDir + context + ".xml" );
333
334                        // DBスクリプトをロードします。
335//                      loadXMLScript( "install", context );
336                        loadXMLScript( EXEC_TYPE.INSTALL , context );
337//                      connection.commit();
338//                      Closer.commit( connection );                            // 5.5.4.4 (2012/07/20) commit で、SQLException を発生させない。
339                        out.println( "      completed                ( " + context + " )" );
340                }
341                out.println( "      Install Process All Completed." );
342        }
343
344        /**
345         * インストール、更新用のXMLスクリプトをロードします。
346         *
347         * @og.rev 5.0.0.2 (2009/09/15) .xmlファイル以外は読み込まないように修正
348         * @og.rev 5.1.1.0 (2009/12/01) コメントを出して、処理中ということが判る様にします。
349         * @og.rev 5.1.9.0 (2010/08/01) DB非依存の定義・データの読み込み対応
350         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE , DBNAME を、共通に設定
351         * @og.rev 5.6.7.0 (2013/07/27) アプリケーション登録用とリソース登録用のコネクションを分ける
352         *
353         * @param       type    更新タイプ[EXEC_TYPE.INSTALL/EXEC_TYPE.UPDATE]
354         * @param       context コンテキスト名
355         */
356//      private void loadXMLScript( final String type, final String context ) throws SQLException {
357        private void loadXMLScript( final EXEC_TYPE type, final String context ) {
358//              final String FS       = File.separator ;
359//              final String APP_BASE = System.getenv( "APP_BASE" );            // 5.5.4.4 (2012/07/20) APP_BASE を共通に設定
360//              final String DBNAME   = connection.getMetaData().getDatabaseProductName().toLowerCase( Locale.JAPAN );
361
362                // DB名からスクリプトを格納しているフォルダを探します。
363//              String scriptBase = APP_BASE + FS + context.toLowerCase( Locale.JAPAN ) + FS + "db";
364                String scriptBase = APP_BASE + context.toLowerCase( Locale.JAPAN ) + FS + "db";
365                File[] dbDir = new File( scriptBase ).listFiles();
366                if( dbDir == null || dbDir.length == 0 ) {
367                        out.println( "             DB Folder not found. [" + scriptBase + "]"  );
368                        return;
369                }
370
371                String scriptPath = null;
372                for ( int i = 0; i < dbDir.length; i++ ) {
373                        if ( DBNAME.indexOf( dbDir[i].getName() ) >= 0 ) {
374                                scriptPath = dbDir[i].getAbsolutePath();
375                                break;
376                        }
377                }
378                if( scriptPath == null ) {
379                        out.println( "             !!! Script Folder for [ " + DBNAME + " ] not found !!!" );
380                        return;
381                }
382
383                // webapps/[CONTEXT]/db/[DBNAME]/
384//              execScripts( scriptPath, type );
385//              execScripts( type , scriptPath );                               // 5.5.4.4 (2012/07/20) typeのenum化と、引数の順番を親に合わす。
386                execScripts( type , scriptPath , defConn );             // 5.6.7.0 (2013/07/27) DBID=DEFAULT に登録
387
388                // 5.1.9.0 (2010/08/01) DB非依存の定義・データの読み込み対応
389                // webapps/[CONTEXT]/db/common/
390//              execScripts( scriptBase + FS + "common" + FS, type );
391//              execScripts( type , scriptBase + FS + "common" );                               // 5.5.4.4 (2012/07/20) typeのenum化と、引数の順番を親に合わす。
392                execScripts( type , scriptBase + FS + "common" , defConn );             // 5.6.7.0 (2013/07/27) DBID=DEFAULT に登録
393
394                // 5.6.7.0 (2013/07/27) DBID=RESOURCE に登録
395                // webapps/[CONTEXT]/db/resource/
396                execScripts( type , scriptBase + FS + "resource" , rscConn );   // 5.6.7.0 (2013/07/27) DBID=RESOURCE に登録
397
398//              // webapps/[CONTEXT]/db/xml 内のスクリプトを実行します
399//              File[] dataDir = new File( scriptBase + FS + "xml" ).listFiles();
400//              if( dataDir != null && dataDir.length > 0 ) {
401//                      for ( int i=0; i<dataDir.length; i++ ) {
402//                              String dtNm = dataDir[i].getName() ;
403//                              if( dtNm.endsWith( ".xml" ) ) {         // 5.0.0.2 (2009/09/15)
404//                                      Reader reader = new BufferedReader( FileUtil.getBufferedReader( dataDir[i], "UTF-8" ) );
405//                                      HybsXMLSave save = new HybsXMLSave( connection, dtNm );
406//                                      save.insertXML( reader );
407//                              }
408//                      }
409//                      out.println( "            DB Data Files Installed , [ " + dataDir.length + " ] files loaded " );
410//              }
411        }
412
413        /**
414         * XMLファイルで定義されたDBスクリプトを実行します。
415         *
416         * 引数のtypeに応じて、処理するフォルダが異なります。
417         *   type=INSTALL の場合は、[scriptPath]/xml/install と、[scriptPath]/xml/update 以下の xml ファイル
418         *   type=それ以外の場合は、[scriptPath]/xml/update 以下の xml ファイル
419         * です。
420         *
421         * 現時点では、scriptPath には、下記の 3種類のアドレスが渡され、それぞれ、登録するコネクションが異なります。
422         *   webapps/[CONTEXT]/db/[DBNAME]/                     DBID=DEFAULT
423         *   webapps/[CONTEXT]/db/common/                       DBID=DEFAULT
424         *   webapps/[CONTEXT]/db/resource/                     DBID=RESOURCE
425         *
426         * @og.rev 5.1.9.0 (2010/08/01) 新規作成
427         * @og.rev 5.5.4.4 (2012/07/20) FS , APP_BASE を、共通に設定
428         * @og.rev 5.5.8.4 (2012/11/22) firebird対応。フォルダ単位commitを行う
429         * @og.rev 5.6.7.0 (2013/07/27) Connection引数追加。リソースとアプリを切り分ける。
430         * @og.rev 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
431         *
432         * @param       type            更新タイプ[EXEC_TYPE.INSTALL/EXEC_TYPE.UPDATE]
433         * @param       scriptPath      XMLファイルのあるパス
434         * @param       conn            コネクションオブジェクト
435         */
436//      private void execScripts( final String scriptPath, final String type ) {
437//      private void execScripts( final EXEC_TYPE type, final String scriptPath ) {
438        private void execScripts( final EXEC_TYPE type, final String scriptPath, final Connection conn ) {
439//              final String FS       = File.separator ;
440
441                // webapps/[CONTEXT]/db/[DBNAME]/xml/(install|update) 内のスクリプトを実行します
442                List<String> list = new ArrayList<String>();
443
444//              if( "install".equalsIgnoreCase( type ) ) {
445                if( type == EXEC_TYPE.INSTALL ) {
446                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "install" ), true, list );
447//                      FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update" + FS + "const" ), true, list );
448                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update"  ), true, list );
449                }
450                else {
451//                      FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update" + FS + "const" ), true, list );
452                        FileUtil.getFileList( new File( scriptPath  + FS + "xml" + FS + "update"  ), true, list );
453
454                        /*******************************************************************************
455                         * updateの場合に、更新前のバージョンからの変更スクリプトを実行する機能が必要
456                         *******************************************************************************/
457                }
458
459                if( ! list.isEmpty() ) {
460                        String dir1 = null;             // 5.1.1.0 (2009/12/01)
461                        for ( String name : list ) {
462                                if( name.endsWith( ".xml" ) ) {         // 5.0.0.2 (2009/09/15)
463                                        File xml = new File( name );
464                                        // 5.1.1.0 (2009/12/01) 処理中コメント:フォルダ単位に表示
465                                        String dir2 = xml.getParent();
466                                        if( dir1 == null || !dir1.equalsIgnoreCase( dir2 ) ) {
467                                                out.println( "            processing ... " + dir2 );
468                                                dir1 = dir2;
469//                                              Closer.commit( connection );    // 5.5.8.4 (2012/11/22)
470                                                Closer.commit( conn );                  // 5.6.7.0 (2013/07/27) Connection引数追加
471                                        }
472
473                                        Reader reader = new BufferedReader( FileUtil.getBufferedReader( xml, "UTF-8" ) );
474//                                      HybsXMLSave save = new HybsXMLSave( connection, xml.getName() );
475                                        HybsXMLSave save = new HybsXMLSave( conn, xml.getName() );                      // 5.6.7.0 (2013/07/27) Connection引数追加
476                                        save.onExecErrException( false );               // 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
477                                        save.insertXML( reader );
478                                }
479                        }
480                        Closer.commit( conn );                  // 5.6.7.0 (2013/07/27) メソッド内でコミット処理を行う。
481                        out.println( "            DB Enviroment " + type + "ed , [ " + list.size() + " ] scripts loaded " );
482                }
483        }
484
485        /**
486         * 最後に起動された際のバージョン番号を取得します。(システムID='**')
487         *
488         * エンジンがまだインストールされていない等の原因でエラーが発生した場合は、
489         * "none"という文字列を返します。
490         *
491         * @og.rev 5.1.1.0 (2009/12/01) 実行エラー時に、rollback を追加(PostgreSQL対応)
492         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションから取り出します。
493         * @og.rev 5.7.2.0 (2014/01/10) テーブルが無いのに正常終了するケースがある為、ver の初期値を "none" にしておきます。
494         *
495         * @return      バージョン番号
496         */
497        private String getOldMaxVersion() {
498                // エンジンパラメータのエンジン情報(バージョン番号 + ビルドタイプ)を取得します。
499                Statement                       stmt            = null;
500                ResultSet                       resultSet       = null;
501//              String                          ver             = null;
502                String                          ver             = "none";                               // 5.7.2.0 (2014/01/10) 初期値を null ⇒ "none" へ変更。
503                try {
504//                      stmt = connection.createStatement();
505                        stmt = rscConn.createStatement();                                       // 5.6.7.0 (2013/07/27)
506                        resultSet = stmt.executeQuery( SEL_MAX_ENG );
507                        while( resultSet.next() ) {
508                                ver = resultSet.getString(1);
509                        }
510                }
511                catch( SQLException ex ) {
512//                      ver = "none";                                           // 5.7.2.0 (2014/01/10) 初期値を変更したため、設定不要。
513//                      Closer.rollback( connection );          // 5.1.1.0 (2009/12/01)
514                        Closer.rollback( rscConn );                     // 5.6.7.0 (2013/07/27)
515                }
516                finally {
517                        Closer.resultClose( resultSet );
518                        Closer.stmtClose( stmt );
519                }
520                return ver;
521        }
522
523        /**
524         * 最後に起動された際のバージョン番号を取得します。(システムID=各システム)
525         *
526         * @og.rev 5.1.1.0 (2009/12/01) 実行エラー時に、rollback を追加(PostgreSQL対応)
527         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションから取り出します。
528         *
529         * @param       systemId        システムID
530         * @param       hostUrl         ホストURL
531         *
532         * @return      バージョン番号
533         */
534        private String getOldSystemVersion( final String systemId, final String hostUrl ) {
535                // エンジンパラメータのエンジン情報(バージョン番号 + ビルドタイプ)を取得します。
536                PreparedStatement       pstmt           = null;
537                ResultSet                       resultSet       = null;
538                String                          ver             = null;
539                try {
540//                      pstmt = connection.prepareStatement( SEL_SYS_ENG );
541                        pstmt = rscConn.prepareStatement( SEL_SYS_ENG );                // 5.6.7.0 (2013/07/27)
542                        pstmt.setString( 1, systemId );
543                        pstmt.setString( 2, hostUrl );
544                        resultSet = pstmt.executeQuery();
545                        while( resultSet.next() ) {
546                                ver = resultSet.getString(1);
547                        }
548                }
549                catch( SQLException ex ) {
550//                      Closer.rollback( connection );          // 5.1.1.0 (2009/12/01)
551                        Closer.rollback( rscConn );                     // 5.6.7.0 (2013/07/27)
552                }
553                finally {
554                        Closer.resultClose( resultSet );
555                        Closer.stmtClose( pstmt );
556                }
557                return ver;
558        }
559
560        /**
561         * エンジン内部定義の初期リソース情報をDB(GE12)に登録します。
562         *
563         * 初期リソース情報は、KBSAKU='0' で登録されている情報で、一旦すべて削除
564         * してから、全てのリソース情報を追加するという形をとります。
565         * リソースは、すでに、Oracle XDK により XMLファイル化してあります。
566         * なお、この情報をDB登録する理由は、リソースの設定値を変えたい場合に、
567         * キーが判らない(JavaDOCからしか読み取れない)のでは不便な為に
568         * 用意しておくだけで、内部では SystemData オブジェクトとして定義
569         * されている値を使用するため、このデータベース値は、使用していません。
570         *
571         * @og.rev 4.3.6.6 (2009/05/15) バージョン判定部分を分離
572         * @og.rev 5.6.7.0 (2013/07/27) リソース用コネクションに登録します。
573         * @og.rev 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
574         *
575         * @throws UnsupportedEncodingException エンコード名 "UTF-8" が存在しなかった場合。
576         */
577        private void dbXMLResourceInsert() throws UnsupportedEncodingException {
578                // 新設定値を全件INSERTします。
579                // common フォルダにセットして、ClassLoader で読み取る方法
580                ClassLoader loader = Thread.currentThread().getContextClassLoader();
581                InputStream stream = loader.getResourceAsStream( GE12_XML );
582
583                Reader reader = new BufferedReader( new InputStreamReader( stream,"UTF-8" ) );
584//              HybsXMLSave save = new HybsXMLSave( connection,"GE12" );
585                HybsXMLSave save = new HybsXMLSave( rscConn,"GE12" );                   // 5.6.7.0 (2013/07/27)
586                save.onExecErrException( false );               // 5.6.9.2 (2013/10/18) EXEC_SQL のエラー時に Exception を発行しない。
587                save.insertXML( reader );
588                int insCnt = save.getInsertCount();
589                int delCnt = save.getDeleteCount();
590
591                out.print( "        XML Engine Resource Reconfiguration " );
592                out.println( "DELETE=[" + delCnt + "],INSERT=[" + insCnt + "] finished." );
593
594                // 5.6.7.0 (2013/07/27) コミットをメソッドの中で処理します。
595                Closer.commit( rscConn );
596        }
597}