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