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     */
016    package org.opengion.hayabusa.report;
017    
018    import org.opengion.hayabusa.common.HybsSystem;
019    import org.opengion.hayabusa.common.HybsSystemException;
020    import org.opengion.fukurou.db.ConnectionFactory;
021    import org.opengion.fukurou.db.DBUtil;                                  // 5.5.5.1 (2012/08/07)
022    import org.opengion.fukurou.util.StringUtil;
023    import org.opengion.fukurou.util.FileUtil;
024    import org.opengion.fukurou.util.ApplicationInfo;
025    import org.opengion.fukurou.util.Closer;
026    
027    import java.io.File;
028    import java.io.IOException;
029    import java.util.List;
030    import java.util.Arrays;
031    
032    import java.sql.Connection;
033    import java.sql.PreparedStatement;
034    import java.sql.SQLException;
035    
036    /**
037     * 【EXCEL取込】雛形EXCELシートと、データEXCELシートからã?æŒ?®šã?DBにãƒ??タを登録するクラスクラスですã?
038     * 雛形EXCELシートã?、{@カラãƒ? で記述されており、このカラãƒ??EXCEL上ã?セルの位置をå?にã€?
039     * ãƒ??タEXCELシートから所定ã?ãƒ??タを読みこみã€?››形明細定義(GE57)でæŒ?®šã?ãƒ??ブルに
040     * 抜き出したãƒ??タを登録しますã?
041     * 雛形明細定義(GE57)では、シスãƒ?ƒ ID+帳票ID+シート番号をキーに、読み取る対応シートや
042     * シート毎にヘッãƒ??ãƒ??ブル、æ?細ãƒ??ブルのæŒ?®šã?繰返å¿??カラãƒ??してã�?�ªどによりã€?
043     * 読取る方式と、書き込ã‚?ƒ†ーブルを指定しますã?
044     *
045     * @og.rev 3.8.0.0 (2005/06/07) 新規追åŠ?
046     * @og.group 帳票シスãƒ?ƒ 
047     *
048     * @version  4.0
049     * @author   Kazuhiko Hasegawa
050     * @since    JDK5.0,
051     */
052    public class ExcelInsert {
053            private static final String CR = HybsSystem.CR ;
054    
055            private final StringBuilder errMsg ;
056    
057            // DBTableReport に対して設定する情報
058            private final String EXCELIN ;          // EXCEL ファイルの取込DIR ファイル名ã?、要求番号.xls
059    
060            // 受け渡し変数
061            private final String    SYSTEM_ID       ;
062            private final String    YKNO            ;
063            private final String    LISTID          ;
064            private final boolean   DEBUG           ;       // 3.8.5.0 (2006/03/06) ãƒ?ƒ�ãƒ?‚°用のフラグを追åŠ?
065    
066            // GE54,GE57 帳票定義、æ?細æƒ??
067            private String          MODELDIR        = null;         // GE54 雛形EXCELãƒ?‚£レクトリ
068            private String          MODELFILE       = null;         // GE54 雛形EXCELファイルå�?
069            private String[]        SHEETNO         = null;         // GE57 雛形EXCELシート番号
070            private String[]        SHEETREF        = null;         // GE57 ãƒ??タEXCELシート番号
071            private String[]        HEADDBID        = null;         // GE57 ヘッãƒ??ãƒ??ブル
072            private String[]        BODYDBID        = null;         // GE57 明細ãƒ??ブル
073            private String[]        LOOPCLM         = null;         // GE57 繰返å¿??カラãƒ?��
074    
075            private ExcelLayout layout = null;
076    
077            // GE54,GE57 の帳票定義æƒ??を取得するSQLæ–?�§すã?
078            private static final String GE54_GE57_SELECT =
079                    "SELECT A.MODELDIR,A.MODELFILE,B.SHEETNO,B.SHEETREF,B.HEADDBID,B.BODYDBID,B.LOOPCLM" +
080                    " FROM GE54 A INNER JOIN GE57 B" +
081                    " ON   A.SYSTEM_ID = B.SYSTEM_ID AND A.LISTID = B.LISTID" +
082                    " WHERE A.FGJ = '1' AND B.FGJ = '1'" +
083                    " AND  A.SYSTEM_ID = ?" +
084                    " AND  A.LISTID = ?" +
085                    " ORDER BY B.SHEETNO" ;
086    
087            /** コネクションにアプリケーションæƒ??を追記するかどã�?�‹æŒ?®?*/
088            public static final boolean USE_DB_APPLICATION_INFO  = HybsSystem.sysBool( "USE_DB_APPLICATION_INFO" ) ;
089    
090            // 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
091            private final ApplicationInfo appInfo;
092            private final String DBID = HybsSystem.sys( "RESOURCE_DBID" );          // 5.5.5.1 (2012/08/07) リソース系DBID 付け忘れ対å¿?
093    
094            /**
095             * コンストラクター
096             * 引数を受けとって、インスタンスを作æ?しますã?
097             *
098             * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
099             *
100             * @param system_id シスãƒ?ƒ ID
101             * @param ykno 要求番号
102             * @param listId 帳票ID
103             * @param excelinDir 出力ディレクトリ
104             * @param debug ãƒ?ƒ�ãƒ?‚°フラグ
105             */
106            public ExcelInsert( final String system_id, final String ykno, final String listId, final String excelinDir, final boolean debug ) {
107                    SYSTEM_ID = system_id;
108                    YKNO      = ykno;
109                    LISTID    = listId;
110                    EXCELIN   = excelinDir;
111                    DEBUG     = debug;
112                    errMsg    = new StringBuilder();
113    
114                    // 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
115                    if( USE_DB_APPLICATION_INFO ) {
116                            appInfo = new ApplicationInfo();
117                            // ユーザーID,IPアドレス,ホスト名
118                            appInfo.setClientInfo( SYSTEM_ID,HybsSystem.HOST_ADRS,HybsSystem.HOST_NAME );
119                            // 画面ID,操ä½?プログラãƒ?D
120                            appInfo.setModuleInfo( "ExcelInsert",YKNO,LISTID );
121                    }
122                    else {
123                            appInfo = null;
124                    }
125            }
126    
127            /**
128             * 変換処ç�?‚’実行しますã?
129             *
130             * @og.rev 3.8.0.9 (2005/10/17) エラーメãƒ?‚»ージ強åŒ?
131             *
132             * @return 結果 [true:正常/false:異常]
133             */
134            public boolean execute() {
135                    System.out.print( "ExcelInsert Started ... " );
136                    boolean flag ;
137    
138                    try {
139                            // 初期åŒ?GE54,GE57 帳票定義マスタよりå¿?¦�なæƒ??を取得しますã?
140                            flag = initialDataSet();
141                            if( flag ) { System.out.print( "INIT," ); }
142    
143                            // 雛型ファイルの存在チェãƒ?‚¯を行いますã?
144                            // 3.5.4.9 (2004/02/25) 存在チェãƒ?‚¯エラー(原因不æ?)の暫定対å¿?
145                            File templateExcel = null;
146                            if( flag ) {
147                                    templateExcel = FileUtil.checkFile( MODELDIR, MODELFILE + ".xls" );
148                                    flag = ( templateExcel != null ) ;              // チェãƒ?‚¯の結果ã�?null ならã?見つからなかったã?
149                                    // 3.8.0.9 (2005/10/17) エラーメãƒ?‚»ージ強åŒ?
150                                    if( flag ) { System.out.print( "MDL IN," ); }
151                                    else {
152                                            errMsg.append( "ExcelInsert MODELFILE Not Found Error!" ).append( CR );
153                                            errMsg.append( "==============================" ).append( CR );
154                                            errMsg.append( "MODELDIR=" ).append( MODELDIR ).append( CR ) ;
155                                            errMsg.append( "MODELFILE=" ).append( MODELFILE ).append( ".xls" ) ;
156                                            errMsg.append( CR ) ;
157                                    }
158                            }
159    
160                            // EXCELãƒ??タファイルの存在チェãƒ?‚¯を行いますã?
161                            File inputExcel = null;
162                            if( flag ) {
163                                    inputExcel = FileUtil.checkFile( EXCELIN, YKNO + ".xls" );
164                                    flag = ( inputExcel != null ) ;         // チェãƒ?‚¯の結果ã�?null ならã?見つからなかったã?
165                                    // 3.8.0.9 (2005/10/17) エラーメãƒ?‚»ージ強åŒ?
166                                    if( flag ) { System.out.print( "XLS IN," ); }
167                                    else {
168                                            errMsg.append( "ExcelInsert EXCELIN Not Found Error!" ).append( CR );
169                                            errMsg.append( "==============================" ).append( CR );
170                                            errMsg.append( "DIR=" ).append( EXCELIN ).append( CR ) ;
171                                            errMsg.append( "FILE=" ).append( YKNO ).append( ".xls" ) ;
172                                            errMsg.append( CR ) ;
173                                    }
174                            }
175    
176                            // 雛形ファイルより、å?ç�?¯¾象行å?を読み取りますã?
177                            if( flag ) {
178                                    flag = getModelData( templateExcel );
179                                    if( flag ) { System.out.print( "MDL DT," ); }
180                            }
181    
182                            // EXCELãƒ??タファイルを読取り、データベã?スに書き込みますã?
183                            if( flag ) {
184                                    flag = readAndInsertDB( inputExcel );
185                                    if( flag ) { System.out.print( "IN DB," ); }
186                            }
187                    }
188                    catch ( RuntimeException ex ) {
189                            errMsg.append( "ExcelInsert Execute Exception Error!" ).append( CR );
190                            errMsg.append( "==============================" ).append( CR );
191                            errMsg.append( StringUtil.stringStackTrace( ex ) ) ;
192                            errMsg.append( CR ) ;
193                            flag = false;
194                    }
195    
196                    System.out.println( "End." );
197                    return flag ;
198            }
199    
200            /**
201             * 初期ãƒ??タセãƒ?ƒˆを行いますã?
202             * ここでは、GE54,GE57 ãƒ??ブルよりå¿?¦�なæƒ??を取得しますã?
203             *
204             * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
205             * @og.rev 5.5.5.1 (2012/08/07) リソース系DBID 付け忘れ対ç­?
206             *
207             * @return 結果 [true:正常/false:異常]
208             */
209            private boolean initialDataSet() {
210                    String[] args = new String[] { SYSTEM_ID,LISTID };
211                    // A.MODELDIR,A.MODELFILE,B.SHEETNO,B.SHEETREF,B.HEADDBID,B.BODYDBID,B.LOOPCLM
212    //              String[][] vals = org.opengion.fukurou.db.DBUtil.dbExecute( GE54_GE57_SELECT,args,appInfo );    // 3.8.7.0 (2006/12/15)
213                    String[][] vals = DBUtil.dbExecute( GE54_GE57_SELECT,args,appInfo, DBID );      // 3.8.7.0 (2006/12/15)
214                    if( vals == null || vals.length == 0 ) {
215                            errMsg.append( "Data does not exist in GE54 table." ).append( CR );
216                            errMsg.append( "==============================" ).append( CR );
217                            errMsg.append( "SYSTEM_ID=[" ).append( SYSTEM_ID ).append( "] , " );
218                            errMsg.append( "LISTID=["    ).append( LISTID    ).append( "]" );
219                            errMsg.append( CR );
220                            return false;
221                    }
222    
223                    int maxRow = vals.length;               // 先ã?条件判断で、最ä½?1 件以上存在するã€?
224                    MODELDIR        = StringUtil.nval( vals[0][0],MODELDIR   );
225                    MODELFILE       = StringUtil.nval( vals[0][1],MODELFILE  );
226    
227                    if( MODELDIR  == null || MODELDIR.length()  == 0 ||
228                            MODELFILE == null || MODELFILE.length() == 0 ) {
229                            errMsg.append( "MODELDIR and MODELFILE is necessary in GE54 table." ).append( CR );
230                            errMsg.append( "==============================" ).append( CR );
231                            errMsg.append( "SYSTEM_ID=[" ).append( SYSTEM_ID ).append( "] , " );
232                            errMsg.append( "LISTID=["    ).append( LISTID    ).append( "] , " );
233                            errMsg.append( "MODELDIR=["  ).append( MODELDIR  ).append( "] , " );
234                            errMsg.append( "MODELFILE=[" ).append( MODELFILE ).append( "] " );
235                            errMsg.append( CR );
236                            return false;
237                    }
238    
239                    SHEETNO         = new String[maxRow];
240                    SHEETREF        = new String[maxRow];
241                    HEADDBID        = new String[maxRow];
242                    BODYDBID        = new String[maxRow];
243                    LOOPCLM         = new String[maxRow];
244    
245                    for( int row=0; row<maxRow; row++ ) {
246                            SHEETNO[row]    = StringUtil.nval( vals[row][2],null );
247                            SHEETREF[row]   = StringUtil.nval( vals[row][3],null );
248                            HEADDBID[row]   = StringUtil.nval( vals[row][4],null );
249                            BODYDBID[row]   = StringUtil.nval( vals[row][5],null );
250                            LOOPCLM[row]    = StringUtil.nval( vals[row][6],null );
251    
252                            // SHEETNO と SHEETREF は、どちらã?もã?å¿??
253                            // HEADDBID と BODYDBID は、どちらã?かã?å¿??
254                            if( SHEETNO[row] == null || SHEETREF[row] == null ||
255                                    ( HEADDBID[row] == null && BODYDBID[row] == null ) ) {
256                                    errMsg.append( "SHEETNO と SHEETREF は、どちらã?もã?å¿??" ).append( CR );
257                                    errMsg.append( "HEADDBID と BODYDBID は、どちらã?かã?å¿??" ).append( CR );
258                                    errMsg.append( "==============================" ).append( CR );
259                                    errMsg.append( "SYSTEM_ID=[" ).append( SYSTEM_ID     ).append( "] , " );
260                                    errMsg.append( "LISTID=["    ).append( LISTID        ).append( "] , " );
261                                    errMsg.append( "SHEETNO=["   ).append( SHEETNO[row]  ).append( "] , " );
262                                    errMsg.append( "SHEETREF=["  ).append( SHEETREF[row] ).append( "] , " );
263                                    errMsg.append( "HEADDBID=["  ).append( HEADDBID[row] ).append( "] , " );
264                                    errMsg.append( "BODYDBID=["  ).append( BODYDBID[row] ).append( "] " );
265                                    errMsg.append( CR );
266                                    return false;
267                            }
268                    }
269    
270                    return true;
271            }
272    
273            /**
274             * 雛形ファイルより、対象行å?を読み取りますã?
275             *
276             * @param       file    雛形ファイル
277             *
278             * @return 結果 [true:正常/false:異常]
279             */
280            private boolean getModelData( final File file ) {
281                    try {
282                            layout = HybsHSSFListener.makeExcelLayout( file,false );
283                    }
284                    catch( IOException ex ) {
285                            errMsg.append( "Template Excel File can not ModelData." ).append( CR );
286                            errMsg.append( "==============================" ).append( CR );
287                            errMsg.append( "File=" ).append( file.getAbsolutePath() );
288                            errMsg.append( StringUtil.stringStackTrace( ex ) );
289                            errMsg.append( CR );
290                            return false;
291                    }
292    
293                    return true;
294            }
295    
296            /**
297             * EXCELを読取り、データベã?スに書き込みますã?
298             *
299             * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
300             *
301             * @param       file    EXCELファイル
302             *
303             * @return 結果 [true:正常/false:異常]
304             */
305            private boolean readAndInsertDB( final File file ) {
306    
307                    ExcelDataPickup pickup = new ExcelDataPickup( layout,file,DEBUG );
308    
309                    // 実際のãƒ??タシートã?枚数
310                    int sheetSize = pickup.getSheetSize();
311                    // SHEETREF に対して、実際に割り当てなおしたシート対å¿?
312                    int[] reference = makeSheetReference( sheetSize,SHEETREF );
313    
314                    DatabaseExecute exec = new DatabaseExecute();
315                    exec.setApplicationInfo( appInfo );             // 3.8.7.0 (2006/12/15)
316                    int ykno = Integer.parseInt(YKNO) ;
317                    for( int shNo=0; shNo<sheetSize; shNo++ ) {
318                            int ref = reference[shNo];
319                            if( ref < 0 ) { continue; }  // 処ç�?¯¾象å¤?
320    
321                            pickup.execute( Integer.parseInt( SHEETNO[ref] ),shNo,LOOPCLM[ref] ) ;
322    
323                            String headerQuery = layout.getHeaderInsertQuery( HEADDBID[ref] );
324                            if( headerQuery != null ) {
325                                    exec.setStatement( headerQuery );
326    
327                                    String[] headerData = layout.getHeaderInsertData( SYSTEM_ID,ykno,shNo );
328                                    exec.dbExecute( headerData );
329                            }
330    
331                            String bodyQuery = layout.getBodyInsertQuery( BODYDBID[ref] );
332                            if( bodyQuery != null ) {
333                                    exec.setStatement( bodyQuery );
334    
335                                    List<String[]> bodyData  = layout.getBodyInsertData( SYSTEM_ID,ykno,shNo );
336                                    for( int j=0; j<bodyData.size(); j++ ) {
337    //                                      exec.dbExecute( (String[])bodyData.get(j) );
338                                            exec.dbExecute( bodyData.get(j) );
339                                    }
340                            }
341                    }
342                    exec.commit();
343                    pickup.close();
344    
345                    return true;
346            }
347    
348            /**
349             * GE57 にæŒ?®šã?SHEETNOとSHEETREF配å?より、実際にアクセスするシート番号に対応したリファレンス配å?を求めますã?
350             * SHEETNO はã€?››形EXCELの使用するシート番号を指定しますã?SHEETREFは、その雛形シートを
351             * 利用して処ç�?�™るデータEXCELのシートをæŒ?®šしますã?シート番号はã€?¼�から始まりますã?
352             * こã?、データEXCELシーãƒ?SHEETREF)は、単ä¸?•°、カンマ結合、LASTæ–?­?でæŒ?®šしますã?
353             * 単ä¸?•°?š雛形シートと?‘対?‘で対応するデータEXCELシート番号
354             * カンマ結合??,4,5 ã‚??2,5 などのè¤?•°シートをひとつの雛形シートで処ç�?�™るå?合に設定しますã?
355             * LASTæ–?­—ï¼?,LAST ã‚?LAST と記述することで、それ以降ã?全ãƒ??タシートを雛形シートで処ç�?�—ますã?
356             *
357             * ここでは、SHEETREF配å? を実際のãƒ??タEXCELシート数åˆ??配å?に再é?置しã?そã?å…??アドレスã‚?
358             * æŒ?�™リファレンスæƒ??を返しますã?
359             * こã?リファレンスæƒ??をå?に、SHEETNO,HEADDBID,BODYDBID,LOOPCLM などのå…??配å?にアクセスしã?
360             * 設定å?を取得してきますã?
361             *
362             * ä¾?
363             *  SHEETNO  = { "1","2"  ,"3","4"  ,"6" };
364             *  SHEETREF = { "1","2,6","4","5,3","8,LAST" };
365             *  HEADDBID = { "A","B"  ,"C","D"  ,"E" };
366             *  ãƒ??タシート数=11
367             *
368             * i=[0]  , No=[1], REF=[1]
369             * i=[1]  , No=[2], REF=[2,6]
370             * i=[2]  , No=[3], REF=[4]
371             * i=[3]  , No=[4], REF=[5,3]
372             * i=[4]  , No=[6], REF=[8,LAST]
373             * =========================
374             * REF=[0]  , Ref=[-1], SHEETNO[]   = -  , HEADDBID[]   = -
375             * REF=[1]  , Ref=[0],  SHEETNO[[0]]=[1] , HEADDBID[[0]]=[A]
376             * REF=[2]  , Ref=[1],  SHEETNO[[1]]=[2] , HEADDBID[[1]]=[B]
377             * REF=[3]  , Ref=[3],  SHEETNO[[3]]=[4] , HEADDBID[[3]]=[D]
378             * REF=[4]  , Ref=[2],  SHEETNO[[2]]=[3] , HEADDBID[[2]]=[C]
379             * REF=[5]  , Ref=[3],  SHEETNO[[3]]=[4] , HEADDBID[[3]]=[D]
380             * REF=[6]  , Ref=[1],  SHEETNO[[1]]=[2] , HEADDBID[[1]]=[B]
381             * REF=[7]  , Ref=[-1], SHEETNO[]   = -  , HEADDBID[]   = -
382             * REF=[8]  , Ref=[4],  SHEETNO[[4]]=[6] , HEADDBID[[4]]=[E]
383             * REF=[9]  , Ref=[4],  SHEETNO[[4]]=[6] , HEADDBID[[4]]=[E]
384             * REF=[10] , Ref=[4],  SHEETNO[[4]]=[6] , HEADDBID[[4]]=[E]
385             *
386             * @param       size    ãƒ??タシートã?総件数
387             * @param       sheetRef        ãƒ??タEXCELシートã?対応するé?åˆ?単ä¸?•°、カンマ結合、LASTæ–?­?が使用可能)
388             *
389             * @return      ãƒ??タ件数åˆ?�«再é?置したã€?››形EXCELシート番号配å?。使用しなã�??合ã?ã€?1 がセãƒ?ƒˆã€?
390             */
391            private int[] makeSheetReference( final int size,final String[] sheetRef ) {
392    
393                    int[] reference = new int[size];
394                    Arrays.fill( reference ,-1 );
395    
396                    int maxNo = -1;
397                    for( int i=0; i<sheetRef.length; i++ ) {
398                            String[] temp = StringUtil.csv2Array( sheetRef[i] );
399                            for( int j=0; j<temp.length; j++ ) {
400                                    if( temp[j].equals( "LAST" ) ) {
401                                            for( int k=maxNo; k<size; k++ ) {
402                                                    reference[k]  = i ;
403                                            }
404                                            i=size;
405                                            break;
406                                    }
407                                    else {
408                                            int no = Integer.parseInt(temp[j]) ;
409                                            if( no < size ) {
410                                                    reference[no]  = i ;
411                                                    if( maxNo < no ) { maxNo = no+1; }
412                                            }
413                                            else {
414                                                    String errMsg = "ãƒ??タシートと雛形明細定義の対応ができませんã€?
415                                                                    + " ãƒ??タシート総件数=[" + size + "] "
416                                                                    + " sheetRef[" + i + "]=" + sheetRef[i] ;
417                                                    throw new HybsSystemException( errMsg );
418                                            }
419                                    }
420                            }
421                    }
422                    return reference ;
423            }
424    
425            /**
426             * エラーが存在した場合に、エラーメãƒ?‚»ージを返しますã?
427             *
428             * @return エラーメãƒ?‚»ージ String
429             */
430            public String getErrMsg() {
431                    return errMsg.toString();
432            }
433    }
434    
435    /**
436     * 連続しã�?ãƒ??タベã?ス処ç�?‚’行う為の、管ç�??ç�?‚¯ラスですã?
437     * ExcelInsert でのコーãƒ?‚£ングをå?けるためã�?�‘のクラスですã?
438     *
439     * オブジェクト作æ?時に、DEFAULT 接続をå†?ƒ¨にキープし、setStatement( String )で
440     * PreparedStatementオブジェクトを作æ?しますã?こã?メソãƒ?ƒ‰を呼ぶまではã€?
441     * 同じ PreparedStatementオブジェクトを使ã�?¶šけますã?
442     * dbExecute( String[] ) メソãƒ?ƒ‰で、PreparedStatement に設定する引数配å?をセãƒ?ƒˆしますã?
443     * こã?段階では、commit もã?PreparedStatementのclose も行いませんのでã€??続してã€?
444     * dbExecute( String[] ) メソãƒ?ƒ‰を呼び出すことが可能ですã?
445     * æœ?¾Œに、commit() で、Connection は、ã?ールに返されますã?
446     *
447     * エラー時ã?、rollback() して、Connection は、ç?æ£?�•れますã?
448     *
449     * @og.group 帳票シスãƒ?ƒ 
450     *
451     * @version  4.0
452     * @author   Kazuhiko Hasegawa
453     * @since    JDK5.0,
454     */
455    class DatabaseExecute {
456            // 4.0.0.0 (2007/10/10) dbid の初期値をã?"DEFAULT" から null に変更
457    //      private static final String connID = "DEFAULT" ;
458            private static final String DBID = null ;
459    
460            private Connection conn = null;
461            private PreparedStatement pstmt = null;
462            private String   tempSql  = null;       // エラー時にSQLæ–?‚’表示させるå?合に使用しますã?
463            private ApplicationInfo appInfo = null;
464    
465            /**
466             * アクセスログ取得ã?為,ApplicationInfoオブジェクトを設定しますã?
467             *
468             * @og.rev 3.8.7.0 (2006/12/15) 新規追åŠ?
469             *
470             * @param   appInfo ApplicationInfo
471             */
472            public void setApplicationInfo( final ApplicationInfo appInfo ) {
473                    this.appInfo = appInfo;
474            }
475    
476            /**
477             * PreparedStatementオブジェクトを作æ?しますã?
478             * 次に、このメソãƒ?ƒ‰を呼ぶまでは、同ã�?PreparedStatementオブジェクトを使ã�?¶šけますã?
479             *
480             * @og.rev 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
481             * @og.rev 4.0.0.1 (2007/12/03) try ??catch ??finally をきちんと行うã€?
482             *
483             * @param stmt String
484             */
485            public void setStatement( final String stmt ) {
486                    boolean errFlag = true ;
487                    tempSql = stmt;
488                    try {
489                            // 3.8.7.0 (2006/12/15) アクセスログ取得ã?為,ApplicationInfoオブジェクトを設å®?
490                            if( conn == null ) { conn = ConnectionFactory.connection( DBID,appInfo ); }
491                            Closer.stmtClose( pstmt );
492                            pstmt = conn.prepareStatement( stmt );
493                            errFlag = false ;
494                    }
495                    catch (SQLException ex) {
496                            String errMsg = "Statement を作æ?できませんでしたã€? + HybsSystem.CR
497                                                    + "SQL=[" + stmt + "]"
498                                                    + ex.getMessage() + ":" + ex.getSQLState() ;
499                            throw new HybsSystemException( errMsg,ex );
500                    }
501                    finally {
502                            if( errFlag ) { errorFinally(); }
503                    }
504            }
505    
506            /**
507             * Connection ã‚?commit しますã?
508             * こã?オブジェクトを終äº?�™る最後に行いますã?
509             *
510             */
511            public void commit() {
512                    boolean errFlag = true ;
513                    try {
514                            conn.commit();
515                            errFlag = false ;
516                    }
517                    catch (SQLException ex) {
518                            Closer.rollback( conn );
519                            String errMsg = "Connection をコミットできませんでしたã€? + HybsSystem.CR
520                                                    + ex.getMessage() + ":" + ex.getSQLState() ;
521                            throw new HybsSystemException( errMsg,ex );
522                    }
523                    finally {
524                            Closer.stmtClose( pstmt );
525                            if( errFlag ) { ConnectionFactory.remove( conn,DBID ); }
526                            else {                  ConnectionFactory.close( conn,DBID );  }
527                            conn = null;
528                    }
529            }
530    
531            /**
532             * PreparedStatement に設定する引数配å?をセãƒ?ƒˆしますã?
533             *
534             * こã?段階では、commit もã?PreparedStatementのclose も行いませんのでã€??続してã€?
535             * dbExecute( String[] ) メソãƒ?ƒ‰を呼び出すことが可能ですã?
536             *
537             * @param   args オブジェクトã?引数配å?
538             */
539            public void dbExecute( final String[] args ) {
540                    // System.out.println( StringUtil.array2csv( args ) );
541    
542                    boolean errFlag = true ;
543                    try {
544                            for( int i=0; i<args.length; i++ ) {
545                                    pstmt.setString( i+1,args[i] );
546                            }
547                            pstmt.execute();
548                            errFlag = false ;
549                    }
550                    catch (SQLException ex) {
551                            String errMsg = "ãƒ??タベã?ス処ç�?‚’実行できませんでしたã€? + HybsSystem.CR
552                                                    + "ARGS=[" + StringUtil.array2csv( args ) + "]" + HybsSystem.CR
553                                                    + "SQL=[" + tempSql + "]"
554                                                    + ex.getMessage() + ":" + ex.getSQLState() ;
555                            throw new HybsSystemException( errMsg,ex );
556                    }
557                    finally {
558                            if( errFlag ) { errorFinally(); }
559                    }
560            }
561    
562            /**
563             * エラー発生時の処ç�?
564             *
565             * PreparedStatement のクローズと、Connection の破æ£?‚’行いますã?
566             */
567            private void errorFinally() {
568                    Closer.stmtClose( pstmt );
569                    pstmt = null;
570                    Closer.rollback( conn );
571                    ConnectionFactory.remove( conn,DBID );
572                    conn = null;
573            }
574    }