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.report2;
017
018import java.io.BufferedReader;
019import java.io.BufferedWriter;
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.FileNotFoundException;
023import java.io.FileOutputStream;
024import java.io.IOException;
025import java.io.OutputStreamWriter;
026import java.io.UnsupportedEncodingException;
027import java.nio.channels.FileChannel;
028import java.nio.charset.CharacterCodingException;                                       // 6.3.1.0 (2015/06/28)
029import java.util.List;
030import java.util.ArrayList;
031import java.util.Map;
032import java.util.HashMap;
033import java.util.concurrent.ConcurrentMap;                                                      // 6.4.3.3 (2016/03/04)
034import java.util.concurrent.ConcurrentHashMap;                                          // 6.4.3.1 (2016/02/12) refactoring
035import java.util.Locale;
036import java.util.Set;
037
038import org.opengion.fukurou.system.OgCharacterException ;                       // 6.5.0.1 (2016/10/21)
039import org.opengion.fukurou.model.NativeType;
040import org.opengion.fukurou.util.StringUtil;                                            // 6.2.0.0 (2015/02/27)
041import org.opengion.fukurou.system.Closer;
042import org.opengion.fukurou.util.FileUtil;
043import org.opengion.fukurou.util.QrcodeImage;
044import org.opengion.hayabusa.common.HybsSystem;
045import org.opengion.hayabusa.common.HybsSystemException;
046import org.opengion.hayabusa.db.DBTableModel;                                           // 6.1.1.0 (2015/01/17)
047import static org.opengion.fukurou.system.HybsConst.CR ;                        // 6.1.0.0 (2014/12/26)
048import static org.opengion.fukurou.system.HybsConst.FS ;                        // 8.0.3.0 (2021/12/17)
049import static org.opengion.fukurou.system.HybsConst.BUFFER_MIDDLE;      // 6.1.0.0 (2014/12/26) refactoring
050
051import org.opengion.hayabusa.report2.TagParser.SplitKey;                        // 8.0.3.0 (2021/12/17)
052
053/**
054 * 指定されたパスに存在するODSの各XMLファイルをパースし、帳票定義及び
055 * 帳票データから書き換えます。
056 * 書き換えは読み取り先と同じファイルであるため、一旦読み取った各XMLを
057 * メモリ上に格納したからパース後のXMLファイルの書き込みを行います。
058 *
059 * パース対象となるファイルは以下の3つです。
060 *  content.xml シートの中身を定義
061 *  meta.xml    メタデータを定義
062 *  style.xml   帳票ヘッダーフッターを定義
063 *
064 * content.xmlのパース処理として、まずxmlファイルをシート+行単位に分解します。
065 * その後、分解された行毎に帳票データを埋め込み、出力先のXMLに書き込みを行います。
066 * 書き込みは行単位に行われます。
067 *
068 * また、Calcの特性として、関数の引数に不正な引数が指定された場合、(Text関数の
069 * 引数にnullが指定された場合等)、エラー:XXXという文字が表示されます。
070 * ここでは、これを回避するため、全ての関数にisError関数を埋め込み、エラー表示を
071 * 行わないようにしています。
072 *
073 * @og.group 帳票システム
074 *
075 * @version  4.0
076 * @author   Hiroki.Nakamura
077 * @since    JDK1.6
078 */
079class OdsContentParser {
080
081        //======== content.xmlのパースで使用 ========================================
082        /* シートの開始終了タグ */
083        private static final String BODY_START_TAG = "<table:table ";
084        private static final String BODY_END_TAG = "</table:table>";
085
086        /* 行の開始終了タグ */
087        private static final String ROW_START_TAG = "<table:table-row ";
088
089        /* ページエンドカットの際に、行を非表示にするためのテーブル宣言 */
090        private static final String ROW_START_TAG_INVISIBLE = "<table:table-row table:visibility=\"collapse\" ";
091
092        /* セルの開始タグ */
093        private static final String TABLE_CELL_START_TAG = "<table:table-cell";
094        private static final String TABLE_CELL_END_TAG = "</table:table-cell>";
095
096        /* シート名を取得するための開始終了文字 */
097        private static final String SHEET_NAME_START = "table:name=\"";
098
099        /* オブジェクトの終了位置(シート名)を見つけるための開始文字 */
100        private static final String OBJECT_SEARCH_STR = "table:end-cell-address=\"";
101
102        /* 印刷範囲指定の開始終了文字 */
103        // 4.3.3.5 (2008/11/08) 空白ページ対策で追加
104        private static final String PRINT_RANGE_START = "table:print-ranges=\"";
105//      private static final String PRINT_RANGE_END = "\"";
106        private static final String END_KEY = "\"";                             // 8.0.3.0 (2021/12/17)
107
108        /* 表紙印刷用のページ名称 */
109        private static final String FIRST_PAGE_NAME = "FIRST";
110
111        /* シートブレイク用のキー 5.1.7.0 (2010/06/01) */
112        private static final String SHEET_BREAK = "SHEETBREAK";
113
114        /* 変数定義の開始終了文字及び区切り文字 */
115        private static final String VAR_START = "{@";
116        private static final String VAR_END = "}";
117//      private static final String VAR_CON = "_";              // 8.0.3.0 (2021/12/17) '_' で、キーと行番号の分離を、インナークラス化します。
118
119        /* ページエンドカットのカラム文字列 */
120        private static final String PAGE_END_CUT = "PAGEENDCUT";
121
122        /* ページブレイクのカラム文字列 */
123        private static final String PAGE_BREAK = "PAGEBREAK";
124
125        /* ページ番号出力用文字列 5.1.6.0 (2010/05/01) */
126        private static final String PAGE_NO= "PAGENO";
127
128        /* 行番号出力用文字列 5.1.6.0 (2010/05/01) */
129        private static final String ROW_NO= "ROWNO";
130
131        /* 画像のリンクを取得するための開始終了文字 */
132        private static final String DRAW_IMG_START_TAG = "<draw:image xlink:href=\"";
133        private static final String DRAW_IMG_END_TAG = "</draw:image>";
134//      private static final String DRAW_IMG_HREF_END = "\"";
135
136        /* 画像ファイルを保存するためのパス */
137        private static final String IMG_DIR = "Pictures";
138
139        /* QRコードを処理するためのカラム名 */
140        private static final String QRCODE_PREFIX = "QRCODE.";
141
142        /* 作成したQRコードのフォルダ名及び拡張子 */
143        private static final String QRCODE_FILETYPE = ".png";
144
145        /* 7.0.5.1 (2019/09/27) QRコードのパラメータをシステムリソースで設定できるようにします(ただし、staticとします) */
146        private static final int        QR_VERSION              = HybsSystem.sysInt( "REPORT_QR_VERSION" );                     // 7.0.5.1 (2019/09/27) バージョン
147        private static final char       QR_ENCMODE_CH   = HybsSystem.sys( "REPORT_QR_ENCMODE" ).charAt(0);      // 7.0.5.1 (2019/09/27) エンコードモード
148        private static final char       QR_ERRCRCT_CH   = HybsSystem.sys( "REPORT_QR_ERRCRCT" ).charAt(0);      // 7.0.5.1 (2019/09/27) エラー訂正レベル
149        private static final String QR_IMAGE_TYPE       = "PNG";                                                                                        // 7.0.5.1 (2019/09/27) 出力イメージのタイプ(PNG/JPEG)
150        private static final int        QR_PIXEL                = HybsSystem.sysInt( "REPORT_QR_PIXEL" );                       // 7.0.5.1 (2019/09/27) 1セル辺りの塗りつぶしピクセル数
151        private static final QrcodeImage.EncMode QR_ENCMODE = QrcodeImage.EncMode.get( QR_ENCMODE_CH ); // 7.0.5.1 (2019/09/27)
152        private static final QrcodeImage.ErrCrct QR_ERRCRCT = QrcodeImage.ErrCrct.get( QR_ERRCRCT_CH ); // 7.0.5.1 (2019/09/27)
153        private static final String     QR_TXT_ENC              = HybsSystem.sys( "REPORT_QR_TEXT_ENCODE" );            // 7.2.3.0 (2020/04/10) 帳票出力のQRコード作成時のテキストのエンコード指定
154
155        /* 4.3.3.5 (2008/11/08) 動的に画像を入れ替えるためのパスを記述するカラム名 */
156        private static final String IMG_PREFIX = "IMG.";
157
158        /* ファンクション定義を見つけるための開始終了文字 */
159        private static final String OOOC_FUNCTION_START = "oooc:=";
160        private static final String OOOC_FUNCTION_START_3 = "of:="; // 4.3.7.2 (2009/06/15) ODS仕様変更につき追加
161        private static final String OOOC_FUNCTION_END = ")\" ";
162
163        /* セル内の改行を定義する文字列 5.0.2.0 (2009/11/01) */
164        private static final String OOO_CR = "</text:p><text:p>";
165
166        /* グラフオブジェクトの書き換えを行うための開始終了文字 5.1.8.0 (2010/07/01) */
167        private static final String GRAPH_START_TAG = "<draw:frame ";
168        private static final String GRAPH_END_TAG = "</draw:frame>";
169
170        /* グラフの範囲指定の書き換えを行うための開始終了文字 5.1.8.0 (2010/07/01) */
171        private static final String GRAPH_UPDATE_RANGE_START = "draw:notify-on-update-of-ranges=\"";
172//      private static final String GRAPH_UPDATE_RANGE_END = "\"";
173
174        /* グラフのオブジェクトへのリンクの書き換えを行うための開始終了文字 5.1.8.0 (2010/07/01) */
175        private static final String GRAPH_HREF_START = "xlink:href=\"./";
176//      private static final String GRAPH_HREF_END = "\"";
177        private static final String GRAPH_OBJREPL = "ObjectReplacements";
178
179        /* グラフのオブジェクト毎のcontent.xmlに記述してあるシート名の書き換えを行うための開始終了文字 5.1.8.0 (2010/07/01) */
180        private static final String GRAPH_CONTENT_START = "-address=\"";
181//      private static final String GRAPH_CONTENT_END = "\"";
182
183        /* 生成したグラフのオブジェクトをMETA-INF/manifest.xmlに登録するための開始終了文字列 5.1.8.0 (2010/07/01) */
184        private static final String MANIFEST_START_TAG = "<manifest:file-entry ";
185        private static final String MANIFEST_END_TAG = "/>";                                    // XML なので、このまま。
186
187        /* 数値タイプ置き換え用の文字列 5.1.8.0 (2010/07/01) */
188        private static final String TABLE_CELL_STRING_TYPE = "office:value-type=\"string\"";
189        private static final String TABLE_CELL_FLOAT_TYPE = "office:value-type=\"float\"";
190        private static final String TABLE_CELL_FLOAT_VAL_START = "office:value=\"";
191//      private static final String TABLE_CELL_FLOAT_VAL_END = "\"";
192
193        /* テキスト文字列の開始終了文字列 5.1.8.0 (2010/07/01) */
194        private static final String TEXT_START_TAG = "<text:p>";
195        private static final String TEXT_END_TAG = "</text:p>";
196
197        /* コメント(アノテーション)を処理するためのカラム名 5.1.8.0 (2010/07/01) */
198        private static final String ANNOTATION_PREFIX = "ANO.";
199        private static final String TEXT_START_ANO_TAG = "<text:p"; // アノテーションの場合の置き換えを
200        private static final String TEXT_START_END_ANO_TAG = ">"; // アノテーションの場合の置き換えを
201
202        /* コメント(アノテーション)の開始・終了タグ 5.1.8.0 (2010/07/01) */
203        private static final String ANNOTATION_START_TAG = "<office:annotation";
204        private static final String ANNOTATION_END_TAG = "</office:annotation>";
205
206        /* オブジェクトを検索するための文字列 5.1.8.0 (2010/07/01) */
207//      private static final String DRAW_START_KEY = "<draw:";
208//      private static final String DRAW_END_KEY = "</draw:";
209        private static final String DRAW_START_TAG = "<draw:";
210        private static final String DRAW_END_TAG = "</draw:";
211
212        /* シートの開始終了タグ 5.2.2.0 (2010/11/01) */
213        private static final String STYLE_START_TAG = "<style:style ";
214        private static final String STYLE_END_TAG = "</style:style>";
215
216        /* シート名称 5.2.2.0 (2010/11/01) */
217        private static final String STYLE_NAME_START_TAG = "style:name=\"";
218//      private static final String STYLE_NAME_END_TAG = "\"";
219
220        /* テーブル内シート名称 5.2.2.0 (2010/11/01) */
221        private static final String TABLE_STYLE_NAME_START_TAG = "table:style-name=\"";
222//      private static final String TABLE_STYLE_NAME_END_TAG = "\""; // 5.6.3.1 (2013/04/05)
223
224        /* LibreOffice対応(数字が文字扱いの対応) 8.1.2.1 (2022/03/25) */
225        private static final String XMLNS_CALCEXT = "xmlns:calcext=\"";
226        //private static final String TABLE_CELL_CALCEXT = "calcext:value-type=\"";     // 一時的にコメント化
227
228        //===========================================================================
229
230        //======== meta.xmlのパースで使用 ===========================================
231        /* 総シートカウント数 */
232        private static final String TABLE_COUNT_START_TAG = "meta:table-count=\"";
233//      private static final String TABLE_COUNT_END_TAG = "\"";
234
235        /* 総セルカウント数 */
236        private static final String CELL_COUNT_START_TAG = "meta:cell-count=\"";
237//      private static final String CELL_COUNT_END_TAG = "\"";
238
239        /* 総オブジェクトカウント数 */
240        private static final String OBJECT_COUNT_START_TAG = "meta:object-count=\"";
241//      private static final String OBJECT_COUNT_END_TAG = "\"";
242        //===========================================================================
243
244        /*
245         * 処理中の行番号の状態
246         * NORMAL : 通常
247         * LASTROW : 最終行
248         * OVERFLOW : 終了
249         */
250        private static final int NORMAL   = 0;
251        private static final int LASTROW  = 1;
252        private static final int OVERFLOW = 2;
253        private int status = NORMAL;
254
255        /*
256         * 各雛形ファイルを処理する際の基準となる行数
257         * 初期>0 2行({&#064;XXX_1}まで)処理後>2 ・・・
258         * 各雛形で定義されている行番号 + [baseRow] の値がDBTableModel上の行番号に相当する
259         * currentMaxRowは各シート処理後の[baseRow]と同じ
260         */
261        private int currentBaseRow      ;
262        private int currentMaxRow       ;
263
264        /* 処理したページ数 */
265        private int pages       ;
266
267        /* 処理行がページエンドカットの対象かどうか */
268        private boolean isPageEndCut    ;                       // 4.3.1.1 (2008/08/23) ローカル変数化
269
270        /* ページブレイクの処理中かどうか */
271        private boolean isPageBreak             ;
272
273        /* XML宣言の文字列。各XMLで共通なのでクラス変数として定義 */
274        private String xmlHeader                ;
275
276        /* シートブレイク対象かどうか 5.1.7.0 (2010/06/01) */
277        private int sheetBreakClm = -1;
278
279        /* シート名カラム 5.7.6.2 (2014/05/16) */
280        private int sheetNameClm = -1;                                          // 今は、ページブレイクカラムと同じカラムを使用しています。
281
282        /* シートのヘッダー部分の再パースを行うかどうか  5.2.2.0 (2010/11/01) */
283        private boolean isNeedsReparse  ;
284
285        /* ページ名のマッピング(元のシート名に対する新しいシート名) 5.2.2.0 (2010/11/01) */
286        /** 6.4.3.1 (2016/02/12) PMD refactoring. HashMap → ConcurrentHashMap に置き換え。  */
287        private final ConcurrentMap<String,List<String>> pageNameMap = new ConcurrentHashMap<>();
288
289        /* ページ名に依存しているスタイル名称のリスト 5.2.2.0 (2010/11/01) */
290        private final List<String> repStyleList = new ArrayList<>();
291
292        /* manifest.xmlに追加が必要なオブジェクトのマップ 5.3.1.0 (2011/01/01) */
293        /** 6.4.3.1 (2016/02/12) PMD refactoring. HashMap → ConcurrentHashMap に置き換え。  */
294        private final ConcurrentMap<String,String> addObjMap = new ConcurrentHashMap<>();
295
296        private final ExecQueue queue;
297        private final String path;
298
299        private final boolean useChangeType ;           // 6.8.3.1 (2017/12/01)
300
301//      /* 8.0.3.0 (2021/12/17) ods→xlsx変換時のシート毎の行数 */
302//      【保留】private final List<Integer> sheetRows = new ArrayList<>();
303
304        /**
305         * コンストラクタ
306         *
307         * @og.rev 5.1.2.0 (2010/01/01) 処理した行数をQueueオブジェクトから取得(シート数が256を超えた場合の対応)
308         * @og.rev 6.8.3.1 (2017/12/01) ローカルリソースの文字型⇒数値型変換の処理の有無
309         *
310         * @param qu ExecQueueオブジェクト
311         * @param pt パス
312         */
313        OdsContentParser( final ExecQueue qu, final String pt ) {
314                queue = qu;
315                path = pt;
316
317                currentBaseRow = queue.getExecRowCnt();
318                useChangeType = !queue.isFglocal() || HybsSystem.sysBool( "REPORT_USE_CHANGETYPE" );            // 6.8.3.1 (2017/12/01)
319        }
320
321        /**
322         * パース処理を実行します。(1)
323         *
324         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
325         * @og.rev 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
326         */
327        public void exec() {
328                /*
329                 * 雛形ヘッダーフッターの定義
330                 * OOoではページ毎にヘッダーフッターが設定できないよう。
331                 * なので、全てヘッダー扱いで処理
332                 */
333                execStyles();                                   // (2)
334
335                /* 中身の変換 */
336                execContent();                                  // (3)
337
338                /* ヘッダー部分にシート情報がある場合に書き換え */
339                if( isNeedsReparse ) {
340                        /* ヘッダーファイルの再パース */
341                        execContentHeader();            // (4)
342                        /* ヘッダーファイルとそれ以降のファイルの連結 */
343                        execMergeContent();                     // (5)
344                }
345
346                /* メタデータの変換 */
347                execMeta();                                             // (6)
348
349                // 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
350                /* 追加した画像、オブジェクトをmanifest.xmlに追加 */
351                if( !addObjMap.isEmpty() ) {                    // 6.1.1.0 (2015/01/17) refactoring
352                        execManifest();                         // (7)
353                }
354        }
355
356//      /**
357//       * 【保留】シート毎の行数をリストで返します。
358//       *
359//       * @og.rev 8.0.3.0 (2021/12/17) ods→xlsx変換時のシート毎の行数
360//       *
361//       * @return  シート毎の行数リスト
362//       */
363//      public List<Integer> getSheetRowsList() {
364//              return sheetRows;
365//      }
366
367        /**
368         * 帳票処理キューを元に、content.xmlを書き換えます。(3)
369         * まず、XMLを一旦メモリ上に展開した後、シート単位に分解し、データの埋め込みを行います。
370         *
371         * @og.rev 4.3.0.0 (2008/07/18) ページ数が256を超えた場合のエラー処理
372         * @og.rev 5.0.0.2 (2009/09/15) LINECOPY機能追加
373         * @og.rev 5.1.2.0 (2010/01/01) 処理したページ数、行数をQueueオブジェクトにセット(シート数が256を超えた場合の対応)
374         * @og.rev 5.1.7.0 (2010/06/01) 複数シート対応
375         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
376         * @og.rev 5.7.6.2 (2014/05/16) PAGEBREAKカラムの値を、シート名として使う場合の処理追加
377         * @og.rev 5.7.6.3 (2014/05/23) PAGEBREAKカラムの値を、シート名として使う場合の、FIRST雛形への適用
378         * @og.rev 6.1.1.0 (2015/01/17) 内部ロジックの見直し。queue.getBody() を、ローカル変数で定義他。
379         * @og.rev 6.4.3.3 (2016/03/04) 気になったので、sheet.getOrigSheetName() を、変数に入れておきます。
380         * @og.rev 8.0.3.0 (2021/12/17) TagParser.tag2Array を使用します。
381         * @og.rev 8.1.2.1 (2022/03/25) LibreOffice対応(数字が文字扱いの対応)
382         */
383        private void execContent() {
384                final String fileName = path + "content.xml";
385                final String content = readOOoXml( fileName );
386                // ファイルを解析し、シート+行単位に分解
387//              final String[] tags = tag2Array( content, BODY_START_TAG, BODY_END_TAG );
388                final String[] tags = TagParser.tag2Array( content, BODY_START_TAG, BODY_END_TAG );             //
389
390                // 5.2.2.0 (2010/11/01) 条件付書式対応
391                // content.xmlのヘッダー部分のみ書き出し
392//              final String contentHeader = tags[0];                                                                   // 8.1.2.1 (2022/03/25) Modify
393                String contentHeader = tags[0];
394
395                // LibreOffice対応 8.1.2.1 (2022/03/25)
396                final int calcSt = contentHeader.indexOf( XMLNS_CALCEXT );
397                if( calcSt >= 0 ) {
398                        final int calcEd = contentHeader.indexOf( "\"", calcSt + XMLNS_CALCEXT.length() );
399                        contentHeader = contentHeader.replace( contentHeader.substring( calcSt - 1, calcEd + 1 ) , "" );
400                }
401
402                BufferedWriter bw = null;
403                try {
404                        bw = getWriter( fileName );
405                        bw.write( xmlHeader );
406                        bw.write( '\n' );
407                        bw.write( contentHeader );
408                        bw.flush();
409                }
410                catch( final IOException ex ) {
411                        queue.addMsg( "[ERROR]PARSE:error occurer while content.xml(header) " + fileName );
412                        throw new HybsSystemException( ex );
413                }
414                finally {
415                        Closer.ioClose( bw );
416                        bw = null;
417                }
418
419                final String contentFooter = tags[1];
420
421                final List<OdsSheet> firstSheets   = new ArrayList<>();
422                final Map<String, OdsSheet> sheetMap = new HashMap<>();
423
424                final DBTableModel bodyModel = queue.getBody();                         // 6.1.1.0 (2015/01/17)
425//              final int rowCount = bodyModel.getRowCount();                           // 6.1.1.0 (2015/01/17)
426
427                OdsSheet defaultSheet = null;
428                for( int i=2; i<tags.length; i++ ) {
429                        final OdsSheet sheet = new OdsSheet();
430
431                        // sheet.analyze( tags[i] );
432//                      sheet.analyze( tags[i],rowCount );                                              // 6.1.1.0 (2015/01/17) ループから出す。
433                        final String[] bodyTypes = queue.getBodyTypes();                // 8.0.3.0 (2021/12/17)
434                        sheet.analyze( tags[i],bodyTypes );                                             // 8.0.3.0 (2021/12/17)
435                        // 5.1.7.0 (2010/06/01) 複数シート対応
436                        final String sheetName = sheet.getSheetName();
437                        if( sheetName.startsWith( FIRST_PAGE_NAME ) ) {
438                                firstSheets.add( sheet );
439                        }
440                        else {
441                                sheetMap.put( sheetName, sheet );
442                                // 一番初めに見つかった表紙以外のシートをデフォルトシートとして設定
443                                if( defaultSheet == null ) {
444                                        defaultSheet = sheet;
445                                }
446                        }
447
448                        // 6.4.3.3 (2016/03/04) 気になったので、sheet.getOrigSheetName() を、変数に入れておきます。
449                        final String orgShtName = sheet.getOrigSheetName();
450
451                        // 5.2.2.0 (2010/11/01) 条件付書式対応
452                        if( !isNeedsReparse && contentHeader.indexOf( "=\"" + orgShtName + "." ) >= 0 ) {
453                                isNeedsReparse = true;
454                        }
455
456                        // 5.2.2.0 (2010/11/01) 条件付書式対応
457                        pageNameMap.put( orgShtName, new ArrayList<>() );
458                }
459
460                // content.xmlの書き出し
461                try {
462                        // 5.2.2.0 (2010/11/01) 条件付書式対応
463                        if( isNeedsReparse ) {
464                                // ヘッダーを再パースする場合は、ボディ部分を
465                                // content.xml.tmpに書き出して、後でマージする
466                                bw = getWriter( fileName + ".tmp" );
467                                getRepStyleList( contentHeader );
468                        }
469                        else {
470                                // ヘッダーを再パースしない場合は、ボディ部分を
471                                // content.xml追加モードで書き込みする
472                                bw = getWriter( fileName, true );
473                        }
474
475                        // 5.7.6.3 (2014/05/23) PAGEBREAKカラムの値を、シート名として使うかどうか。
476                        if( queue.isUseSheetName() ) {
477                                sheetNameClm = bodyModel.getColumnNo( PAGE_BREAK, false );      // 6.1.1.0 (2015/01/17)
478                        }
479
480                        final int rowCount = bodyModel.getRowCount();                                   // 6.1.1.0 (2015/01/17)
481
482                        // 表紙ページの出力
483                        if( queue.getExecPagesCnt() == 0 ) {
484                                for( final OdsSheet firstSheet : firstSheets ) {
485                                        if( currentBaseRow >= rowCount ) {                                              // 6.1.1.0 (2015/01/17) ループから出す。
486                                                break;
487                                        }
488                                        writeParsedSheet( firstSheet, bw );
489                                }
490                        }
491
492                        // 5.1.7.0 (2010/06/01) 複数シート対応
493                        sheetBreakClm = bodyModel.getColumnNo( SHEET_BREAK, false );    // 6.1.1.0 (2015/01/17)
494
495                        // 5.7.6.3 (2014/05/23) 表紙ページも、PAGEBREAKカラムの値を、シート名として使えるようにする。
496
497                        // 繰り返しページの出力
498                        while( currentBaseRow < rowCount ) {                                                    // 6.1.1.0 (2015/01/17) ループから出す。
499                                // 4.3.0.0 (2008/07/18) ページ数が256を超えた場合にエラーとする
500                                // 5.1.2.0 (2010/01/01) 256シートを超えた場合の対応
501                                if( pages >= ExecQueue.MAX_SHEETS_PER_FILE ) {
502                                        queue.setEnd( false );
503                                        break;
504                                }
505
506                                OdsSheet sheet = null;
507                                if( sheetBreakClm >= 0 ) {
508                                        final String sheetName = bodyModel.getValue( currentBaseRow, sheetBreakClm );   // 6.1.1.0 (2015/01/17)
509                                        if( sheetName != null && sheetName.length() > 0 ) {
510                                                sheet = sheetMap.get( sheetName );
511                                        }
512                                }
513                                if( sheet == null ) { sheet = defaultSheet; }
514
515                                writeParsedSheet( sheet, bw );
516                        }
517
518                        // 5.1.2.0 (2010/01/01) 256シートを超えた場合の対応
519                        queue.addExecPageCnt( pages );
520                        queue.setExecRowCnt( currentBaseRow );
521
522                        // フッター
523                        bw.write( contentFooter );
524                        bw.flush();
525                }
526                catch( final IOException ex ) {
527                        queue.addMsg( "[ERROR]PARSE:error occurer while write Parsed Sheet " + fileName );
528                        throw new HybsSystemException( ex );
529                }
530                finally {
531                        Closer.ioClose( bw );
532                }
533        }
534
535        /**
536         * シート単位にパースされた文書データを書き込みます
537         * 出力されるシート名には、ページ番号と基底となる行番号をセットします。
538         *
539         * @og.rev 4.2.4.0 (2008/07/04) 行単位にファイルに書き込むように変更
540         * @og.rev 5.2.0.0 (2010/09/01) 表紙の場合は、BODY部分のデータが含まれていなくてもOK
541         * @og.rev 5.2.1.0 (2010/10/01) シート名定義対応
542         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
543         * @og.rev 5.7.6.2 (2014/05/16) PAGEBREAKカラムの値を、シート名として使う場合の処理追加
544         * @og.rev 5.7.6.3 (2014/05/23) FIRST雛形シート名が、FIRST**** の場合、**** 部分をシート名に使う。
545         * @og.rev 6.4.3.3 (2016/03/04) 気になったので、sheet.getOrigSheetName() を、変数に入れておきます。
546         * @og.rev 7.3.0.1 (2021/01/22) 画像ファイルの置き方によって、ヘッダー部に {@IMG.XXX} が書かれることがある。
547         * @og.rev 8.0.3.0 (2021/12/17) COPY_LINE機能の追加
548         *
549         * @param sheet シート
550         * @param bw    BufferedWriterオブジェクト
551         * @throws IOException 書き込みに失敗した場合
552         */
553        private void writeParsedSheet( final OdsSheet sheet, final BufferedWriter bw ) throws IOException {
554                // シート名
555                String outputSheetName = null;
556
557                // 5.7.6.2 (2014/05/16) PAGEBREAKカラムの値を、シート名として使うかどうか。
558                if( sheetNameClm >= 0 ) {
559                        final String sheetName = queue.getBody().getValue( currentBaseRow, sheetNameClm );
560                        if( sheetName != null ) {
561                                outputSheetName = sheetName;
562                        }
563                }
564
565                // 5.7.6.3 (2014/05/23) FIRST雛形シート名が、FIRST**** の場合、**** 部分をシート名に使う。
566                if( outputSheetName == null ) {
567                        String sheetName = sheet.getSheetName();
568                        if( sheetName.startsWith( FIRST_PAGE_NAME ) ) {
569                                sheetName = sheetName.substring( FIRST_PAGE_NAME.length() ).trim();
570                                // 小細工。"FIRST_****" の場合は、"_" を外す。長さ0判定の前に行う。
571                                if( StringUtil.startsChar( sheetName , '_' ) ) {                // 6.2.0.0 (2015/02/27) 1文字 String.startsWith
572                                        sheetName = sheetName.substring( 1 );
573                                }
574
575                                // 長さ0の場合(例えば、FIRSTだけとか)は、設定しない。
576                                if( sheetName.length() > 0 ) { outputSheetName = sheetName; }
577                        }
578                }
579
580                // 従来からあるシート名の値
581                if( outputSheetName == null ) {
582                        if( sheet.getConfSheetName() == null ) {
583                                outputSheetName = "Page" + ( queue.getExecPagesCnt() + pages ) + "_Row" + currentBaseRow ;
584                        }
585                        else {
586                                outputSheetName = sheet.getConfSheetName() + ( queue.getExecPagesCnt() + pages + 1 ) ;
587                        }
588                }
589                // ページブレイク変数を初期化
590                isPageBreak = false;
591
592                // 6.4.3.3 (2016/03/04) 気になったので、sheet.getOrigSheetName() を、変数に入れておきます。
593                final String orgShtName = sheet.getOrigSheetName();
594
595                // シートのヘッダー部分を書き込み(シート名も書き換え)
596                String headerStr = sheet.getHeader().replace( SHEET_NAME_START + orgShtName, SHEET_NAME_START + outputSheetName );
597                // 印刷範囲指定部分のシート名を変更
598                // 4.3.3.5 (2008/11/08) 空白ページ出力の対策。印刷範囲のシート名書き換えを追加
599                final int printRangeStart = headerStr.indexOf( PRINT_RANGE_START );
600                if( printRangeStart >= 0 ) {
601//                      final int printRangeEnd = headerStr.indexOf( PRINT_RANGE_END, printRangeStart + PRINT_RANGE_START.length() );
602                        final int printRangeEnd = headerStr.indexOf( END_KEY, printRangeStart + PRINT_RANGE_START.length() );
603                        String rangeStr = headerStr.substring( printRangeStart, printRangeEnd );
604                        rangeStr = rangeStr.replace( orgShtName, outputSheetName );
605                        headerStr = headerStr.substring( 0, printRangeStart ) + rangeStr + headerStr.substring( printRangeEnd );
606                }
607
608                // 7.3.0.1 (2021/01/22) 画像ファイルの置き方によって、ヘッダー部に {@IMG.XXX} が書かれることがある。
609                writeParsedRow( headerStr, bw, orgShtName, outputSheetName );
610//              bw.write( headerStr );
611
612                // 8.0.3.0 (2021/12/17) COPYLINE機能の追加 シートのボディ部分を書き込み
613        //      【保留】sheetRows.add( sheet.getRowCnt() );
614                for( int i=0; i<sheet.getRowCnt(); i++ ) {                                                      // i はシートの行数
615                        final String row = sheet.getRow( i,currentBaseRow );
616                        writeParsedRow( row, bw, orgShtName, outputSheetName );
617                }
618
619//              // シートのボディ部分を書き込み
620//              for( final String row : sheet.getRows() ) {
621//                      writeParsedRow( row, bw, orgShtName, outputSheetName );
622//              }
623
624//              final String[] rows = sheet.getRows();
625//              for( int i=0; i<rows.length; i++ ) {
626//                      // 4.3.4.4 (2009/01/01)
627//                      writeParsedRow( rows[i], bw, orgShtName, outputSheetName );
628//              }
629                // {@XXXX}が埋め込まれていない場合はエラー
630                // 5.2.0.0 (2010/09/01) 表紙の場合は、BODY部分のデータが含まれていなくてもOK
631                if( currentBaseRow == currentMaxRow && !orgShtName.startsWith( FIRST_PAGE_NAME ) ) {
632                        queue.addMsg( "[ERROR]PARSE:No Data defined on Template ODS(" + queue.getListId() + ")" );
633                        throw new HybsSystemException();
634                }
635                currentBaseRow = currentMaxRow;
636
637                // シートのフッター部分を書き込み
638                bw.write( sheet.getFooter() );
639
640                pages++;
641
642                // 5.2.2.0 (2010/11/01) 条件付書式対応
643                pageNameMap.get( orgShtName ).add( outputSheetName );
644        }
645
646        /**
647         * 行単位にパースされた文書データを書き込みます。
648         *
649         * @og.rev 4.2.3.1 (2008/06/19) 関数エラーを表示させないため、ISERROR関数を埋め込み
650         * @og.rev 4.2.4.0 (2008/07/04) 行単位にファイルに書き込むように変更
651         * @og.rev 4.3.0.0 (2008/07/17) {@と}の整合性チェック追加
652         * @og.rev 4.3.0.0 (2008/07/22) 行最後の{@}整合性エラーハンドリング追加
653         * @og.rev 4.3.3.5 (2008/11/08) 画像の動的な入れ替えに対応
654         * @og.rev 5.1.8.0 (2010/07/01) パース方法の内部実装変更
655         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
656         * @og.rev 5.4.2.0 (2011/12/01) ページブレイク、シートブレイク中でもページエンドカットが適用されるようにする。
657         * @og.rev 5.6.3.1 (2013/04/05) 条件付書式の属性終了文字対応
658         * @og.rev 6.8.3.1 (2017/12/01) ローカルリソースの文字型⇒数値型変換の処理の有無
659         * @og.rev 8.0.3.0 (2021/12/17) "\n" 文字列を実際の改行コードに置換して設定します。
660         *
661         * @param row                           行データ
662         * @param bw                            BufferedWriterオブジェクト
663         * @param sheetNameOrig         元シート名
664         * @param sheetNameNew          新シート名
665         * @throws IOException 書き込みに失敗した場合
666         */
667        private void writeParsedRow( final String row, final BufferedWriter bw, final String sheetNameOrig, final String sheetNameNew ) throws IOException {
668                isPageEndCut = false;
669
670                String rowStr = new TagParser() {
671                        /**
672                         * 開始タグから終了タグまでの文字列の処理を定義します。
673                         *
674                         * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
675                         * @param buf 出力を行う文字列バッファ
676                         * @param offset 終了タグのオフセット(ここでは使っていません)
677                         */
678                        @Override
679                        protected void exec( final String str, final StringBuilder buf, final int offset ) {
680                                final String key = TagParser.checkKey( str, buf );
681
682                                // 4.3.0.0 (2008/07/15) "<"が入っていた場合には{@不整合}エラー
683                                if( key.indexOf( '<' ) >= 0 ){
684                                        queue.addMsg( "[ERROR]PARSE:{@と}の整合性が不正です。" + CR
685                                                        + "変数内の特定の文字列に書式設定がされている可能性があります。キー=" + key );
686                                        throw new HybsSystemException();
687                                }
688
689                                // QRコードの処理、処理後はoffsetが進むため、offsetを再セット
690                                if( key.startsWith( QRCODE_PREFIX ) ) {
691                                        setOffset( makeQRImage( row, offset, key.substring( QRCODE_PREFIX.length() ), buf ) );
692                                }
693                                // 画像置き換えの処理、処理後はoffsetが進むため、offsetを再セット
694                                else if( key.startsWith( IMG_PREFIX  ) ) {
695                                        setOffset( changeImage( row, offset, key.substring( IMG_PREFIX.length() ), buf ) );
696                                }
697                                // コメント(アノテーション)による置き換え処理、処理後はoffsetが進むため、offsetを再セット
698                                else if( key.startsWith( ANNOTATION_PREFIX ) ) {
699                                        setOffset( parseByAnnotation( row, offset, key.substring( ANNOTATION_PREFIX.length() ), buf ) );
700                                }
701                                else {
702                                        String val = getValue( key );
703                                        // 5.5.2.4 (2012/05/16) String key は使われていないので、削除します。
704                                        if( useChangeType ) {           // 6.8.3.1 (2017/12/01)
705                                                // 5.5.2.4 (2012/05/16) String key は使われていないので、削除します。
706                                                changeType( row, offset, val, getNativeType( key, val ), buf );
707                                        }
708                                        // 8.0.3.0 (2021/12/17) "\n" 文字列を実際の改行コードに置換して設定します。
709                                        if( val.indexOf( "\\n" ) >= 0 ) {
710                                                val = val.replace( "\\n" , "\n" );
711                                        }
712                                        buf.append( val );
713                                }
714
715                                // 処理行がページエンドカットの対象か
716                                if( queue.isFgcut() && PAGE_END_CUT.equals( key ) ) {
717                                        isPageEndCut = true;
718                                }
719                        }
720                }.doParse( row, VAR_START, VAR_END, false );
721
722                //==== ここからは後処理 =========================================================
723                /*
724                 * ページエンドカットの判定は最後で処理する。
725                 * {&#064;PAGEENDCUT}が行の最初に書かれている場合は、OVERFLOWになっていない可能性が
726                 * あるため行の途中では判断できない
727                 */
728                // 5.4.2.0 (2011/12/01) シートブレイク中でもページエンドカットが適用されるようにする。
729                // (通常のページブレイクは先読み判定のためページエンドカットすると、ブレイク発生行自身が
730                //  削除されてしまうため現時点では未対応)
731//              if( isPageEndCut && ( status == OVERFLOW || ( sheetBreakClm >= 0 && isPageBreak ) ) ) {
732                if( isPageEndCut && ( status == OVERFLOW || sheetBreakClm >= 0 && isPageBreak ) ) {                             // 6.9.7.0 (2018/05/14) PMD Useless parentheses.
733                        // ページエンドカットの場合は、非表示状態にする。
734                        rowStr = rowStr.replace( ROW_START_TAG, ROW_START_TAG_INVISIBLE ) ;
735                }
736
737                /*
738                 * オブジェクトで定義されているテーブル名を変更
739                 */
740                if( rowStr.indexOf( OBJECT_SEARCH_STR ) >= 0 ) {
741                        rowStr = rowStr.replace( OBJECT_SEARCH_STR + sheetNameOrig, OBJECT_SEARCH_STR + sheetNameNew );
742                }
743
744                /*
745                 * 関数エラーを表示されないため、ISERROR関数を埋め込み 4.2.3.1 (2008/06/19)
746                 */
747                rowStr = replaceOoocError( rowStr );
748
749                /*
750                 * グラフをシート毎にコピー 5.1.8.0 (2010/07/01)
751                 */
752                rowStr = replaceGraphInfo( rowStr, sheetNameOrig, sheetNameNew );
753
754                /*
755                 * アノテーション(コメント)を削除 5.1.8.0 (2010/07/01)
756                 * (コメントが存在すると起動が異常に遅くなる)
757                 */
758                if( rowStr.indexOf( ANNOTATION_START_TAG ) >= 0 ) {
759                        rowStr = new TagParser() {}.doParse( rowStr, ANNOTATION_START_TAG, ANNOTATION_END_TAG );
760                }
761
762                /*
763                 * 条件付書式対応 5.2.2.0 (2010/11/01)
764                 * テーブル内に存在するスタイル名称を書き換え
765                 */
766                if( isNeedsReparse ) {
767                        for( final String name : repStyleList ) {
768                                // 5.6.3.1 (2013/04/05) 属性終了追加
769                                final String from = TABLE_STYLE_NAME_START_TAG + name + END_KEY ;
770                                final String to   = TABLE_STYLE_NAME_START_TAG + name + "_" + sheetNameNew + END_KEY ;
771
772//                              if( rowStr.indexOf( TABLE_STYLE_NAME_START_TAG + name + TABLE_STYLE_NAME_END_TAG ) >= 0 ) {
773//                                      rowStr = rowStr.replace( TABLE_STYLE_NAME_START_TAG + name + TABLE_STYLE_NAME_END_TAG,
774//                                                                                       TABLE_STYLE_NAME_START_TAG + name + "_" + sheetNameNew + TABLE_STYLE_NAME_END_TAG );
775//                              }
776
777                                if( rowStr.indexOf( from ) >= 0 ) {
778                                        rowStr = rowStr.replace( from, to );
779                                }
780                        }
781                }
782                //==============================================================================
783
784                bw.write( rowStr );
785        }
786
787        /**
788         * 帳票データに応じて、カラムの属性を変更(文字型⇒数値型)に変更します。
789         *
790         * @og.rev 5.1.8.0 (2010/07/01) 新規作成
791         * @og.rev 5.5.2.4 (2012/05/16) String key は使われていないので、削除します。
792         * @og.rev 8.1.2.1 (2022/03/25) LibreOffice対応(数字が文字扱いの対応)
793         *
794         * @param row                   行データ
795         * @param curOffset             オフセット
796         * @param val                   設定値
797         * @param type                  ネイティブタイプ
798         * @param sb                    StringBuilderオブジェクト
799         */
800        private void changeType( final String row, final int curOffset
801                                                        , final String val, final NativeType type, final StringBuilder sb ) {
802                if( val == null || val.isEmpty() ) {
803                        return;
804                }
805                // 書き換え対象は数値型のみ
806                if( type != NativeType.INT && type != NativeType.LONG && type != NativeType.DOUBLE ) {
807                        return;
808                }
809                // 処理対象がセルでない(オブジェクト)は書き換えしない
810                if( !isCell( row, curOffset ) ) {
811                        return;
812                }
813
814                // セルの文字が{@xxxx_n}のみであった場合だけ、数値定義の判定を行う。
815                // (関数内に{@xxxx_n}等があった場合は、判定しない(<text:p>{@xxxx_n}</text:p>の場合のみ))
816                if( sb.lastIndexOf( TEXT_START_TAG ) + TEXT_START_TAG.length() == sb.length()
817                        && row.indexOf( TEXT_END_TAG, curOffset ) == curOffset ) {
818                        final int typeIdx = sb.lastIndexOf( TABLE_CELL_STRING_TYPE );
819                        final int cellIdx = sb.lastIndexOf( TABLE_CELL_START_TAG );
820                        if( typeIdx >= 0 && cellIdx >= 0 && typeIdx > cellIdx ) {
821                                // office:value-type="string" を office:value-type="float" office:value="xxx" に変換
822                                final int endIdx    = typeIdx + TABLE_CELL_STRING_TYPE.length() ;
823//                              final String repStr = TABLE_CELL_FLOAT_TYPE + " " + TABLE_CELL_FLOAT_VAL_START + val + END_KEY ;        // 8.1.2.1 (2022/03/25) Modify
824                                final String valNew = val.replace( ",", "" );                                   // カンマ除去 8.1.2.1 (2022/03/25) Add
825                                final String repStr = TABLE_CELL_FLOAT_TYPE + " " + TABLE_CELL_FLOAT_VAL_START + valNew + END_KEY ;
826
827//                              sb.replace( typeIdx, typeIdx + TABLE_CELL_STRING_TYPE.length()
828//                                      ,TABLE_CELL_FLOAT_TYPE + " " + TABLE_CELL_FLOAT_VAL_START + val + TABLE_CELL_FLOAT_VAL_END );
829                                sb.replace( typeIdx, endIdx, repStr );
830
831                        //      // LibreOffice対応 8.1.2.1 (2022/03/25) 一時的にコメント化
832                        //      final int calcSt = sb.lastIndexOf( TABLE_CELL_CALCEXT );
833                        //      if( calcSt >= 0 ) {
834                        //              final int calcEd = sb.indexOf( "\"", calcSt + TABLE_CELL_CALCEXT.length() );
835                        //              sb.delete( calcSt - 1, calcEd + 1 );
836                        //      }
837                        }
838                }
839        }
840
841        /**
842         * 引数に指定された文字列のNativeタイプを返します。
843         *
844         * リソース使用時は、各DBTypeで定義されたNativeタイプを、
845         * 未使用時は、値からNativeタイプを取得して返します。
846         *
847         * @og.rev 5.1.8.0 (2010/07/01) NativeType#getType(String) のメソッドを使用するように変更。
848         * @og.rev 5.10.5.1 (2018/11/09) intだけでなくlongの0始まりも文字列として扱う
849         * @og.rev 8.0.3.0 (2021/12/17) アンダーバーで、キーと行番号の分離を、インナークラス化します。
850         *
851         * @param key   キー
852         * @param val   文字列
853         *
854         * @return  NATIVEの型の識別コード
855         * @og.rtnNotNull
856         * @see org.opengion.fukurou.model.NativeType
857         */
858        private NativeType getNativeType( final String key, final String val ) {
859                if( val == null || val.isEmpty() ) {
860                        return NativeType.STRING;
861                }
862
863                NativeType type = null;
864                if( queue.isFglocal() ) {
865//                      String name = key;
866//                      final int conOffset = key.lastIndexOf( VAR_CON );
867//                      if( conOffset >= 0 ) {
868//                              int rownum = -1;
869//                              try {
870//                                      rownum = Integer.parseInt( name.substring( conOffset + VAR_CON.length(), name.length() ) );             // 6.0.2.4 (2014/10/17) メソッド間違い
871//                              }
872//                              // '_'以降の文字が数字でない場合は、'_'以降の文字もカラム名の一部として扱う
873//                              catch( final NumberFormatException ex ) {
874//                                      // 6.4.1.1 (2016/01/16) PMD refactoring. Avoid empty catch blocks
875//                                      final String errMsg = "'_'以降の文字をカラム名の一部として扱います。カラム名=[" + key + "]" + CR + ex.getMessage() ;
876//                                      System.err.println( errMsg );
877//                              }
878//                              if( rownum >= 0 ) {
879//                                      name = name.substring( 0, conOffset );
880//                              }
881//                      }
882//                      final int col = queue.getBody().getColumnNo( name, false );
883                        final SplitKey spKey = new SplitKey( key );             // 8.0.3.0 (2021/12/17)
884                        final int col = queue.getBody().getColumnNo( spKey.name, false );
885                        if( col >= 0 ) {
886                                type = queue.getBody().getDBColumn( col ).getNativeType();
887                        }
888                }
889
890                if( type == null ) {
891                        // ,は削除した状態で判定
892                        final String repVal = val.replace( ",", "" );
893                        type = NativeType.getType( repVal );                    // 5.1.8.0 (2010/07/01) NativeType#getType(String) のメソッドを使用
894                        // 整数型で、0nnnとなっている場合は、文字列をして扱う
895//                      if( type == NativeType.INT && repVal.length() >= 2 && repVal.charAt(0) == '0' ) {
896                        if( ( type == NativeType.INT || type == NativeType.LONG ) && repVal.length() >= 2 && repVal.charAt(0) == '0' ) { // 5.10.5.1 (2018/11/09) LONGを含む
897                                type = NativeType.STRING;
898                        }
899                }
900
901                return type;
902        }
903
904        /**
905         * コメント(アノテーションによる置き換え処理を行います)
906         * この処理では、offsetを進めるため、戻り値として処理後のoffsetを返します。
907         *
908         * @og.rev 5.1.8.0 (2010/07/01) 新規作成
909         * @og.rev 6.8.3.1 (2017/12/01) ローカルリソースの文字型⇒数値型変換の処理の有無
910         *
911         * @param row                   行データ
912         * @param curOffset             オフセット
913         * @param key                   キー
914         * @param sb                    StringBuilderオブジェクト
915         *
916         * @return 処理後のオフセット
917         */
918        private int parseByAnnotation( final String row, final int curOffset, final String key, final StringBuilder sb ) {
919                int offset = curOffset;
920                final boolean isCell = isCell( row, offset );
921
922                // セルの場合のみ置き換えの判定を行う(オブジェクトの場合は判定しない)
923                if( isCell ) {
924                        final int cellStrIdx = sb.lastIndexOf( TABLE_CELL_START_TAG, offset );
925                        // office:value-type="float" office:value="xxx" を office:value-type="string" に変換
926                        // 数値型の場合は、後で再度変換を行う。
927                        // (文字型に変換しておかないと、値がnullの場合でも"0"が表示されてしまうため)
928                        final int floatIdx = sb.indexOf( TABLE_CELL_FLOAT_TYPE, cellStrIdx );
929                        if( floatIdx >= 0 ) {
930                                sb.replace( floatIdx, floatIdx + TABLE_CELL_FLOAT_TYPE.length(), TABLE_CELL_STRING_TYPE );
931
932                                final int floatStrIdx = sb.indexOf( TABLE_CELL_FLOAT_VAL_START, floatIdx );
933                                if( floatStrIdx >= 0 ) {
934//                                      final int floatEndIdx = sb.indexOf( TABLE_CELL_FLOAT_VAL_END, floatStrIdx + TABLE_CELL_FLOAT_VAL_START.length() );
935                                        final int floatEndIdx = sb.indexOf( END_KEY, floatStrIdx + TABLE_CELL_FLOAT_VAL_START.length() );
936                                        if( floatEndIdx >= 0 ) {
937//                                              sb.replace( floatStrIdx, floatEndIdx + TABLE_CELL_FLOAT_VAL_END.length(), "" );
938                                                sb.replace( floatStrIdx, floatEndIdx + 1, "" );
939
940                                        //      // LibreOffice対応 8.1.2.1 (2022/03/25)
941                                        //      final int calcSt = sb.indexOf( TABLE_CELL_CALCEXT, floatEndIdx );
942                                        //      if( calcSt >= 0 ) {
943                                        //              final int calcEd = sb.indexOf( "\"", calcSt + TABLE_CELL_CALCEXT.length() );
944                                        //              sb.delete( calcSt - 1, calcEd + 1 );
945                                        //      }
946                                        }
947                                }
948                        }
949                }
950
951                // アノテーションの値から、セルの文字列部分を置き換え
952                final int endIdx = isCell ? row.indexOf( TABLE_CELL_END_TAG, offset ) : row.indexOf( DRAW_END_TAG, offset );
953                if( endIdx >= 0 ) {
954                        int textStrIdx = row.indexOf( TEXT_START_ANO_TAG, offset );
955                        // セルのコメントの場合、<text:pで検索すると、オブジェクトのテキストが検索されている可能性がある。
956                        // このため、セルの<text:pが見つかるまで検索を繰り返す
957                        if( isCell ) {
958                                while( !isCell( row, textStrIdx ) && textStrIdx >= 0 ) {
959                                        textStrIdx = row.indexOf( TEXT_START_ANO_TAG, textStrIdx + 1 );
960                                }
961                        }
962                        if( textStrIdx >= 0 && textStrIdx < endIdx ) {
963                                // セルのコメントの場合、</text:p>で検索すると、オブジェクトのテキストが検索されている可能性がある。
964                                // このため、セルの</text:p>が見つかるまで検索を繰り返す
965                                int textEndIdx = row.lastIndexOf( TEXT_END_TAG, endIdx );
966                                if( isCell ) {
967                                        while( !isCell( row, textEndIdx ) && textEndIdx >= 0  ) {
968                                                textEndIdx = row.lastIndexOf( TEXT_END_TAG, textEndIdx - 1 );
969                                        }
970                                }
971                                if( textEndIdx >= 0 && textStrIdx < textEndIdx && textEndIdx < endIdx ) {
972                                        // <text:p xxxx> の xxxx> の部分(style定義など)を書き込み
973                                        final int textStyleEnd = row.indexOf( TEXT_START_END_ANO_TAG, textStrIdx + TEXT_START_ANO_TAG.length() ) + TEXT_START_END_ANO_TAG.length();
974                                        sb.append( row.substring( offset, textStyleEnd ) );
975
976                                        // <text:pの中身(spanタグなどを取り除いた状態の文字列
977                                        final String textVal = TagParser.checkKey( row.substring( textStyleEnd, textEndIdx ), sb );
978                                        // 取得したテキスト内にタグ文字が含まれている場合は、処理しない
979                                        if( textVal.indexOf( '<' ) < 0 && textVal.indexOf( '>' ) < 0 ) {
980                                                // <text:p xxxx>を書き出し
981                                                final String val = getValue( key );
982                                                if( useChangeType ) {           // 6.8.3.1 (2017/12/01)
983                                                        // 5.5.2.4 (2012/05/16) String key は使われていないので、削除します。
984                                                        changeType( row, textEndIdx, val, getNativeType( key, textVal ), sb );
985                                                }
986                                                sb.append( val );
987                                        }
988                                        offset = textEndIdx;
989                                }
990                        }
991                }
992
993                return offset;
994        }
995
996        /**
997         * 現在のオフセットがセルかどうかを返します。
998         *
999         * trueの場合はセルを、falseの場合はオブジェクトを意味します。
1000         *
1001         * セルとして判定されるための条件は以下の通りです。
1002         *  現在のoffsetを基準として、
1003         *  ①前に<draw:(オブジェクトの開始)が見つからない
1004         *  ②前に<table:table-cell(セルの始まり)が<draw:(オブジェクトの始まり)より後方にある
1005         *  ③後に</draw:(オブジェクトの終わり)が見つからない
1006         *  ④後に</draw:(オブジェクトの終わり)が</table:table-cell>(セルの終わり)より後方にある
1007         *
1008         * @param row           行データ
1009         * @param offset        オフセット
1010         *
1011         * @return 現在のオフセットがセルかどうか(falseの場合はオブジェクト)
1012         */
1013        private boolean isCell( final String row, final int offset ) {
1014                final int drawStartOffset = row.lastIndexOf( DRAW_START_TAG, offset );
1015                if( drawStartOffset < 0 ) {
1016                        return true;
1017                }
1018                else {
1019                        final int cellStartOffset = row.lastIndexOf( TABLE_CELL_START_TAG, offset );
1020                        if( drawStartOffset < cellStartOffset ) {
1021                                return true;
1022                        }
1023                        else {
1024                                final int drawEndOffset = row.indexOf( DRAW_END_TAG, offset );
1025                                if( drawEndOffset < 0 ) {
1026                                        return true;
1027                                }
1028                                else {
1029                                        final int cellEndOffset = row.indexOf( TABLE_CELL_END_TAG, offset );
1030                                        // 5.1.8.0 (2010/07/01) Avoid unnecessary if..then..else statements when returning a boolean
1031                                        return cellEndOffset >= 0 && cellEndOffset < drawEndOffset ;
1032                                }
1033                        }
1034                }
1035        }
1036
1037        /**
1038         * QRコードを作成します。
1039         * この処理では、offsetを進めるため、戻り値として処理後のoffsetを返します。
1040         *
1041         * @og.rev 4.3.1.1 (2008/08/23) mkdirs の戻り値判定
1042         * @og.rev 4.3.3.5 (2008/11/08) ↑の判定は存在チェックを行ってから処理する。ファイル名に処理行を付加
1043         * @og.rev 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1044         * @og.rev 7.0.5.1 (2019/09/27) QRコードのパラメータをシステムリソースで設定できるようにします(ただし、staticとします)
1045         * @og.rev 7.2.3.0 (2020/04/10) QRコードのパラメータをシステムリソースで設定(帳票出力のQRコード作成時のテキストのエンコード指定)
1046         * @og.rev 8.3.0.0 (2022/08/01) '<','>','&'のメタ文字変換をするかどうかを指定します。
1047         *
1048         * @param row                   行データ
1049         * @param curOffset             オフセット
1050         * @param key                   キー
1051         * @param sb                    StringBuilderオブジェクト
1052         *
1053         * @return 処理後のオフセット
1054         */
1055        private int makeQRImage( final String row, final int curOffset, final String key, final StringBuilder sb ) {
1056                int offset = curOffset;
1057
1058                // {@QRCODE.XXXX}から実際に画像のパスが書かれている部分までを書き込む
1059                offset = row.indexOf( DRAW_IMG_START_TAG, offset ) + DRAW_IMG_START_TAG.length();
1060                sb.append( row.substring( curOffset, offset ) );
1061                // 画像のパスの終了インデックスを求める
1062//              offset = row.indexOf( DRAW_IMG_HREF_END, offset ) + DRAW_IMG_HREF_END.length();
1063                offset = row.indexOf( END_KEY, offset ) + 1;
1064
1065                // QRCODEの画像ファイル名を求め書き込む
1066                // 4.3.3.5 (2008/11/08) ファイル名に処理行を付加
1067                final String fileName = IMG_DIR + '/' + key + "_" + currentBaseRow + QRCODE_FILETYPE;
1068//              sb.append( fileName ).append( DRAW_IMG_HREF_END );
1069                sb.append( fileName ).append( END_KEY );
1070
1071//              // QRCODEに書き込む値を求める             … 8.3.0.0 (2022/08/01) QrcodeImage 作成直前に移動
1072//              final String value = getValue( key );
1073
1074                // QRCODEの作成
1075                // 4.3.3.5 (2008/11/08) ファイル名に処理行を付加
1076                final String fileNameAbs =
1077//                      new File( path ).getAbsolutePath() + File.separator + IMG_DIR + File.separator + key + "_" + currentBaseRow + QRCODE_FILETYPE;
1078                        new File( path ).getAbsolutePath() + FS + IMG_DIR + FS + key + "_" + currentBaseRow + QRCODE_FILETYPE;
1079
1080                // 画像リンクが無効となっている場合は、Picturesのフォルダが作成されていない可能性がある
1081                // 4.3.1.1 (2008/08/23) mkdirs の戻り値判定
1082                // 4.3.3.5 (2008/11/08) 存在チェック追加
1083                // 6.9.7.0 (2018/05/14) PMD These nested if statements could be combined
1084//              if( !new File( fileNameAbs ).getParentFile().exists() ) {
1085//                      if( new File( fileNameAbs ).getParentFile().mkdirs() ) {
1086                if( !new File( fileNameAbs ).getParentFile().exists()
1087                        && new File( fileNameAbs ).getParentFile().mkdirs() ) {
1088                                System.err.println( fileNameAbs + " の ディレクトリ作成に失敗しました。" );
1089//                      }
1090                }
1091
1092                // QRCODEに書き込む値を求める
1093                final String value = getValue( key,false );             // 8.3.0.0 (2022/08/01) メタ文字変換 しない
1094
1095                final QrcodeImage qrImage = new QrcodeImage();
1096//              qrImage.init( value, fileNameAbs );
1097//              qrImage.init( value, fileNameAbs, QR_VERSION, QR_ENCMODE, QR_ERRCRCT, QR_IMAGE_TYPE, QR_PIXEL );                                // 7.0.5.1 (2019/09/27)
1098                qrImage.init( value, fileNameAbs, QR_VERSION, QR_ENCMODE, QR_ERRCRCT, QR_IMAGE_TYPE, QR_PIXEL, QR_TXT_ENC );    // 7.2.3.0 (2020/04/10)
1099                qrImage.saveImage();
1100
1101                // 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1102                addObjMap.put( fileName, QRCODE_FILETYPE.substring( 1 ) );
1103
1104                // 読み込みOffsetを返します
1105                return offset;
1106        }
1107
1108        /**
1109         * DBTableModelに設定されたパスから画像データを取得し、内部に取り込みます
1110         * この処理では、offsetを進めるため、戻り値として処理後のoffsetを返します。
1111         *
1112         * @og.rev 4.3.3.5 (2008/11/08) 新規追加
1113         * @og.rev 4.3.3.6 (2008/11/15) 画像パスが存在しない場合は、リンクタグ(draw:image)自体を削除
1114         * @og.rev 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1115         * @og.rev 7.3.0.1 (2021/01/22) 画像ファイル名が漢字の場合、うまくいかないので、置き換える。
1116         *
1117         * @param row                   行データ
1118         * @param curOffset             オフセット
1119         * @param key                   キー
1120         * @param sb                    StringBuilderオブジェクト
1121         *
1122         * @return 処理後のオフセット
1123         */
1124        private int changeImage( final String row, final int curOffset, final String key, final StringBuilder sb ) {
1125                int offset = curOffset;
1126                File imgFile = null;
1127
1128                // 画像ファイルを読み込むパスを求める
1129                final String value = getValue( key );
1130
1131                if( value != null && value.length() > 0 ) {
1132                        imgFile = new File( HybsSystem.url2dir( value ) );
1133                }
1134
1135                // 画像ファイルのパスが入っていて、実際に画像が存在する場合
1136                if( imgFile != null && imgFile.exists() ) {
1137                        // {@IMG.XXXX}から実際に画像のパスが書かれている部分までを書き込む
1138                        offset = row.indexOf( DRAW_IMG_START_TAG, offset ) + DRAW_IMG_START_TAG.length();
1139                        sb.append( row.substring( curOffset, offset ) );
1140
1141                        // 画像のパスの終了インデックスを求める
1142//                      offset = row.indexOf( DRAW_IMG_HREF_END, offset ) + DRAW_IMG_HREF_END.length();
1143                        offset = row.indexOf( END_KEY, offset ) + 1;
1144
1145                        // 7.3.0.1 (2021/01/22) 画像ファイル名が漢字の場合、うまくいかないので、置き換える。
1146//                      final String fileNameOut = IMG_DIR + '/' + imgFile.getName();
1147                        final String extension = value.substring( value.lastIndexOf('.') );             // 7.3.0.1 (2021/01/22) 拡張子( .付き )
1148                        // 7.3.0.1 (2021/01/22)  同一ファイルは同一名にしておきます。マイナスが気持ち悪いのでハッシュ値は絶対値にしておきます。
1149                        // 8.0.0.0 (2021/07/31) spotbugs:ハッシュコードが Integer.MIN_VALUE なら結果は同様に負です (Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE なので)。
1150//                      final String fileNameOut = IMG_DIR + '/' + Math.abs( imgFile.hashCode() ) + extension;
1151                        final String fileNameOut = IMG_DIR + '/' + Integer.toUnsignedString( imgFile.hashCode() ) + extension;
1152
1153//                      sb.append( fileNameOut ).append( DRAW_IMG_HREF_END );
1154                        sb.append( fileNameOut ).append( END_KEY );
1155
1156                        final File fileOutAbs = new File( path,fileNameOut );
1157                        if( !fileOutAbs.getParentFile().exists() && fileOutAbs.getParentFile().mkdirs() ) {
1158                                System.err.println( fileOutAbs + " の ディレクトリ作成に失敗しました。" );
1159                        }
1160
1161        //              final String fileNameOutAbs =
1162//                              new File( path ).getAbsolutePath() + File.separator + IMG_DIR + File.separator + imgFile.getName();
1163        //                      new File( path ).getAbsolutePath() + '/' + fileNameOut;
1164        //              // 6.9.7.0 (2018/05/14) PMD These nested if statements could be combined
1165//                      if( !new File( fileNameOutAbs ).getParentFile().exists() ) {
1166//                              if( new File( fileNameOutAbs ).getParentFile().mkdirs() ) {
1167        //              if( !new File( fileNameOutAbs ).getParentFile().exists()
1168        //                      && new File( fileNameOutAbs ).getParentFile().mkdirs() ) {
1169        //                              System.err.println( fileNameOutAbs + " の ディレクトリ作成に失敗しました。" );
1170//                              }
1171        //              }
1172        //              FileUtil.copy( imgFile, new File( fileNameOutAbs ) );           // imgFile → fileNameOutAbs copy
1173                        FileUtil.copy( imgFile, fileOutAbs );                                           // imgFile → fileOutAbs copy
1174
1175                        // 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1176                        addObjMap.put( fileNameOut, getSuffix( imgFile.getName() ) );
1177                }
1178                // 画像パスが設定されていない、又は画像が存在しない場合
1179                else {
1180                        // {@IMG.XXXX}から見て、<draw:image> ... </draw:image>までをスキップする
1181                        offset = row.indexOf( DRAW_IMG_START_TAG, offset );
1182                        sb.append( row.substring( curOffset, offset ) );
1183
1184                        offset = row.indexOf( DRAW_IMG_END_TAG, offset ) + DRAW_IMG_END_TAG.length();
1185                }
1186
1187                // 読み込みOffsetを返します
1188                return offset;
1189        }
1190
1191        /**
1192         * 変換後の行データで定義されている関数にISERROR関数を埋め込みます。
1193         *
1194         * これは、OOoの関数の動作として、不正な引数等が入力された場合(null値など)に、
1195         * エラー:xxxと表示されてしまうため、これを防ぐために関数エラーのハンドリングを行い、
1196         * エラーの場合は、空白文字を返すようにします。
1197         *
1198         * @og.rev 4.3.7.2 (2009/06/15) 開始文字が変更になったため対応
1199         * @og.rev 5.0.2.0 (2009/11/01) 関数内の"(quot)は、メタ文字に変換する
1200         * @og.rev 5.1.7.0 (2010/06/01) 関数の終わりが)出ない場合にエラーとなるバグを修正
1201         * @og.rev 5.1.8.0 (2010/07/01) パース方法の内部実装変更
1202         *
1203         * @param row   行データ
1204         *
1205         * @return 変換後の行データ
1206         */
1207        private String replaceOoocError( final String row ) {
1208                // 4.3.7.2 (2009/06/15) OOOC_FUNCTION_START3の条件判定追加。どちらか分からないので変数で受ける。
1209                final String functionStart;
1210                if( row.indexOf( OOOC_FUNCTION_START_3 ) >= 0 )         { functionStart = OOOC_FUNCTION_START_3; }
1211                else if( row.indexOf( OOOC_FUNCTION_START ) >= 0 )      { functionStart = OOOC_FUNCTION_START; }
1212                else { return row; }
1213
1214                final String rowStr = new TagParser() {
1215                        /**
1216                         * 開始タグから終了タグまでの文字列の処理を実行するかどうかを定義します。
1217                         *
1218                         * @param strOffset 開始タグのオフセット
1219                         * @param endOffset 終了タグのオフセット
1220                         *
1221                         * @return 処理を行うかどうか(true:処理を行う false:処理を行わない)
1222                         */
1223                        @Override
1224                        protected boolean checkIgnore( final int strOffset, final int endOffset ) {
1225                                // 5.1.7.0 (2010/06/01) 関数の終わりが)出ない場合にエラーとなるバグを修正
1226                                // 単なる行参照でも、of:=で始まるがこの場合は、関数でないため終わりが)でない
1227                                // このため、)が見つからないまたは、タグの終わり(>)が先に見つかった場合は、エラー関数を
1228                                // 埋め込まないようにする。
1229                                int tmpOffset = row.indexOf( ">", strOffset + 1 );
1230                                return endOffset >= 0 && endOffset < tmpOffset ;
1231                        }
1232
1233                        /**
1234                         * 開始タグから終了タグまでの文字列の処理を定義します。
1235                         *
1236                         * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
1237                         * @param buf 出力を行う文字列バッファ
1238                         * @param offset 終了タグのオフセット(ここでは使っていません)
1239                         */
1240                        @Override
1241                        protected void exec( final String str, final StringBuilder buf, final int offset ) {
1242                                String key = str.substring( functionStart.length(), str.length() - OOOC_FUNCTION_END.length() ) + ")";
1243                                key = key.replace( "\"", "&quot;&quot;" ).replace( OOO_CR, "" );
1244                                // 6.4.2.1 (2016/02/05) PMD refactoring.
1245                                buf.append( functionStart ).append( "IF(ISERROR(" ).append( key )
1246                                        .append( ");&quot;&quot;;" ).append( key ).append( OOOC_FUNCTION_END );
1247                        }
1248                }.doParse( row, functionStart, OOOC_FUNCTION_END );
1249
1250                return rowStr;
1251        }
1252
1253        /**
1254         * グラフ表示データ部分を更新します。
1255         *
1256         * @og.rev 5.1.8.0 (2010/07/01) 新規作成
1257         * @og.rev 5.3.1.0 (2011/01/01) OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1258         *
1259         * @param row           行データ
1260         * @param sheetOrig     元シート
1261         * @param sheetNew      新シート
1262         *
1263         * @return 変換後の行データ
1264         */
1265        private String replaceGraphInfo( final String row, final String sheetOrig, final String sheetNew  ) {
1266                if( row.indexOf( GRAPH_START_TAG ) < 0 || row.indexOf( GRAPH_UPDATE_RANGE_START ) < 0 ) { return row; }
1267
1268                // 7.2.9.5 (2020/11/28) PMD:Consider simply returning the value vs storing it in local variable 'XXXX'
1269                return new TagParser() {
1270//              final String rowStr = new TagParser() {
1271                        /**
1272                         * 開始タグから終了タグまでの文字列の処理を定義します。
1273                         *
1274                         * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
1275                         * @param buf 出力を行う文字列バッファ
1276                         * @param offset 終了タグのオフセット(ここでは使っていません)
1277                         */
1278                        @Override
1279                        protected void exec( final String str, final StringBuilder buf, final int offset ) {
1280                                // <draw:object ... /> の部分
1281                                String graphTag = str;
1282
1283                                if( graphTag.indexOf( GRAPH_UPDATE_RANGE_START ) >= 0 ) {
1284//                                      final String nameOrig = TagParser.getValueFromTag( graphTag, GRAPH_HREF_START, GRAPH_HREF_END );
1285                                        final String nameOrig = TagParser.getValueFromTag( graphTag, GRAPH_HREF_START, END_KEY );       // 8.0.3.0 (2021/12/17)
1286                                        if( new File( path + nameOrig ).exists() ) {
1287                                                final String nameNew = nameOrig + "_" + pages;
1288
1289                                                // グラフオブジェクトの定義ファイルをコピー(./Object X/* ⇒ ./Object X_n/*)
1290                                                FileUtil.copyDirectry( path + nameOrig, path + nameNew );
1291                                                graphTag = graphTag.replace( GRAPH_HREF_START + nameOrig, GRAPH_HREF_START + nameNew );
1292
1293                                                // グラフオブジェクトの画像イメージをコピー(./ObjectReplacements/Object X ⇒ ./ObjectReplacements/Object X_n)
1294                                                // ※実体はコピーしない(リンクの参照を無効にしておくことで、次回起動時にグラフの再描画が行われる)
1295                                                graphTag = graphTag.replace( GRAPH_HREF_START + GRAPH_OBJREPL + "/" + nameOrig, GRAPH_HREF_START + GRAPH_OBJREPL + "/" + nameNew );
1296
1297                                                // OpenOffice3.2対応 追加した画像をmanifest.xmlに登録する
1298                                                addObjMap.put( nameNew, "graph" );
1299
1300                                                // グラフオブジェクトの定義ファイルに記述されている定義ファイルをパースし、シート名と{@XXXX}を置き換え
1301//                                              parseGraphContent( path + nameNew + File.separator + "content.xml", sheetOrig, sheetNew );
1302                                                parseGraphContent( path + nameNew + FS + "content.xml", sheetOrig, sheetNew );
1303
1304                                                // グラフの参照範囲のシート名を置き換え
1305//                                              final String range = TagParser.getValueFromTag( str, GRAPH_UPDATE_RANGE_START, GRAPH_UPDATE_RANGE_END );
1306                                                final String range = TagParser.getValueFromTag( str, GRAPH_UPDATE_RANGE_START, END_KEY );       // 8.0.3.0 (2021/12/17)
1307                                                graphTag = graphTag.replace( GRAPH_UPDATE_RANGE_START + range, GRAPH_UPDATE_RANGE_START + range.replace( sheetOrig, sheetNew ) );
1308                                        }
1309                                }
1310
1311                                buf.append( graphTag );
1312                        }
1313                }.doParse( row, GRAPH_START_TAG, GRAPH_END_TAG );
1314
1315//              return rowStr;
1316        }
1317
1318        /**
1319         * グラフデータのcontent.xmlをパースします。
1320         *
1321         * @og.rev 5.1.8.0 (2010/07/01) 新規作成
1322         *
1323         * @param fileName      ファイル名
1324         * @param sheetOrig     元シート
1325         * @param sheetNew      新シート
1326         */
1327        private void parseGraphContent( final String fileName, final String sheetOrig, final String sheetNew  ) {
1328                String graphContent = readOOoXml( fileName );
1329
1330                // シート名の置き換え
1331                if( graphContent.indexOf( GRAPH_CONTENT_START ) >= 0 ) {
1332                        graphContent = new TagParser() {
1333                                /**
1334                                 * 開始タグから終了タグまでの文字列の処理を定義します。
1335                                 *
1336                                 * この実装では、何も処理を行いません。(切り出した文字列はアペンドされません)
1337                                 * サブクラスでオーバーライドして実際の処理を実装して下さい。
1338                                 *
1339                                 * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
1340                                 * @param buf 出力を行う文字列バッファ
1341                                 * @param offset 終了タグのオフセット(ここでは使っていません)
1342                                 */
1343                                @Override
1344                                protected void exec( final String str, final StringBuilder buf, final int offset ) {
1345                                        buf.append( str.replace( sheetOrig, sheetNew ) );
1346                                }
1347//                      }.doParse( graphContent, GRAPH_CONTENT_START, GRAPH_CONTENT_END );
1348                        }.doParse( graphContent, GRAPH_CONTENT_START, END_KEY );
1349                }
1350
1351                // {@XXXX}の置き換え
1352                if( graphContent.indexOf( VAR_START ) >= 0 ) {
1353                        graphContent = new TagParser() {
1354                                /**
1355                                 * 開始タグから終了タグまでの文字列の処理を定義します。
1356                                 *
1357                                 * この実装では、何も処理を行いません。(切り出した文字列はアペンドされません)
1358                                 * サブクラスでオーバーライドして実際の処理を実装して下さい。
1359                                 *
1360                                 * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
1361                                 * @param buf 出力を行う文字列バッファ
1362                                 * @param offset 終了タグのオフセット(ここでは使っていません)
1363                                 */
1364                                @Override
1365                                public void exec( final String str, final StringBuilder buf, final int offset ) {
1366                                        buf.append( getHeaderFooterValue( str ) );
1367                                }
1368                        }.doParse( graphContent, VAR_START, VAR_END, false );
1369                }
1370
1371                writeOOoXml( fileName, graphContent );
1372        }
1373
1374
1375        /**
1376         * 指定されたキーの値を返します。
1377         *
1378         * @og.rev 4.3.0.0 (2008/07/18) アンダースコアの処理変更
1379         * @og.rev 4.3.5.0 (2008/02/01) カラム名と行番号文字の位置は最後から検索する 4.3.3.4 (2008/11/01) 修正分
1380         * @og.rev 8.0.3.0 (2021/12/17) アンダーバーで、キーと行番号の分離を、インナークラス化します。
1381         * @og.rev 8.3.0.0 (2022/08/01) '<','>','&'のメタ文字変換をデフォルト実行します。
1382         *
1383         * @param key   キー
1384         *
1385         * @return 値
1386         */
1387        private String getValue( final String key ) {
1388                return getValue( key,true );
1389        }
1390
1391        /**
1392         * 指定されたキーの値を返します。
1393         *
1394         * @og.rev 4.3.0.0 (2008/07/18) アンダースコアの処理変更
1395         * @og.rev 4.3.5.0 (2008/02/01) カラム名と行番号文字の位置は最後から検索する 4.3.3.4 (2008/11/01) 修正分
1396         * @og.rev 8.0.3.0 (2021/12/17) アンダーバーで、キーと行番号の分離を、インナークラス化します。
1397         * @og.rev 8.3.0.0 (2022/08/01) '<','>','&'のメタ文字変換をするかどうかを指定します。
1398         *
1399         * @param key   キー
1400         * @param useChange     タ文字変換するかどうか[true:する]
1401         *
1402         * @return 値
1403         */
1404//      private String getValue( final String key ) {
1405        private String getValue( final String key,final boolean useChange ) {
1406//              final int conOffset = key.lastIndexOf( VAR_CON );
1407
1408//              String value = null;
1409                final String value ;
1410
1411//              if( conOffset < 0 ) {
1412                final SplitKey spKey = new SplitKey( key );             // 8.0.3.0 (2021/12/17)
1413                if( spKey.rownum < 0 ) {
1414                        value = getHeaderFooterValue( key );
1415                }
1416                else {
1417//                      final String name = key.substring( 0, conOffset );
1418//                      int rownum = -1;
1419//                      try {
1420//                              rownum = Integer.parseInt( key.substring( conOffset + VAR_CON.length(), key.length() ) ) + currentBaseRow;      // 6.0.2.4 (2014/10/17) メソッド間違い
1421//                      }
1422//                      catch( final NumberFormatException ex ) {
1423//                              // 4.3.0.0 (2008/07/18) エラーが起きてもなにもしない。
1424//                              // queue.addMsg( "[ERROR]雛形の変数定義が誤っています。カラム名=" + name + CR );
1425//                              // throw new Exception( ex );
1426//                              // 6.4.1.1 (2016/01/16) PMD refactoring. Avoid empty catch blocks
1427//                              final String errMsg = "雛形の変数定義で、行番号文字が取得できません。カラム名=[" + key + "]" + CR + ex.getMessage() ;
1428//                              System.err.println( errMsg );
1429//                      }
1430//
1431//                      // 4.3.0.0 (2008/07/18) アンダースコア後が数字に変換できない場合はヘッダフッタとして認識
1432//                      if( rownum < 0 ){
1433//                              value = getHeaderFooterValue( key );
1434//                      }
1435//                      else{
1436//                              value = getBodyValue( name, rownum );
1437                                value = getBodyValue( spKey.name, spKey.rownum + currentBaseRow );
1438//                      }
1439                }
1440
1441//              return checkValue( value );
1442                return checkValue( value,useChange );                   // 8.3.0.0 (2022/08/01)
1443        }
1444
1445        /**
1446         * 指定されたキーのヘッダー、フッター値を返します。
1447         *
1448         * @og.rev 4.3.6.0 (2009/04/01) レンデラー適用されていないバグを修正
1449         * @og.rev 5.0.2.0 (2009/11/01) ローカルリソースフラグを使用しない場合は、リソース変換を行わない。
1450         * @og.rev 5.1.6.0 (2010/05/01) ページNO出力対応
1451         * @og.rev 6.1.1.0 (2015/01/17) getRendererValue の代わりに、getWriteValue を使うように変更。
1452         * @og.rev 6.1.1.0 (2015/01/17) 内部ロジックの見直し。queue.getFooter(),queue.getHeader() を、ローカル変数で定義。
1453         *
1454         * @param key   キー
1455         *
1456         * @return 値
1457         */
1458        private String getHeaderFooterValue( final String key ) {
1459                String value = "";
1460
1461                // 5.1.6.0 (2010/05/01) ページNO出力対応
1462                if( PAGE_NO.equals( key ) ) {
1463                        value = String.valueOf( pages + 1 );
1464                }
1465                // 6.1.1.0 (2015/01/17) 内部ロジックの見直し。queue.getFooter(),queue.getHeader() を、ローカル変数で定義。
1466                else {
1467                        // 最後の行かオーバーフロー時はフッター。最後の行にきていない場合はヘッダー
1468                        final DBTableModel headerFooterModel = status >= LASTROW ? queue.getFooter() : queue.getHeader() ;
1469
1470                        if( headerFooterModel != null ) {
1471                                final int clmno = headerFooterModel.getColumnNo( key, false );
1472                                if( clmno >= 0 ) {
1473                                        value = headerFooterModel.getValue( 0, clmno );
1474                                        // 5.0.2.0 (2009/11/01) ローカルリソースフラグを使用しない場合は、リソース変換を行わない。
1475                                        if( queue.isFglocal() ) {
1476                                                // 4.3.6.0 (2009/04/01)
1477                                                // 6.1.1.0 (2015/01/17) getRendererValue の代わりに、getWriteValue を使うように変更。
1478                                                value = headerFooterModel.getDBColumn( clmno ).getWriteValue( value );
1479                                        }
1480                                }
1481                        }
1482                }
1483
1484                return value;
1485        }
1486
1487        /**
1488         * 指定された行番号、キーのボディー値を返します。
1489         *
1490         * @og.rev 4.3.6.0 (2009/04/01) レンデラー適用されていないバグを修正
1491         * @og.rev 4.3.6.2 (2009/04/15) 行番号のより小さいカラム定義を読んだ際に、内部カウンタがクリアされてしまうバグを修正
1492         * @og.rev 4.3.6.2 (2009/04/15) 一度オーバーフローした場合に移行が全て空文字で返ってしまうバグを修正
1493         * @og.rev 5.0.2.0 (2009/11/01) ローカルリソースフラグを使用しない場合は、リソース変換を行わない。
1494         * @og.rev 5.1.6.0 (2010/05/01) 行番号出力対応
1495         * @og.rev 5.1.7.0 (2010/06/01) 複数シート対応
1496         * @og.rev 5.1.9.0 (2010/08/01) 最終行で正しくシートブレイクされないバグを修正
1497         * @og.rev 6.1.1.0 (2015/01/17) getRendererValue の代わりに、getWriteValue を使うように変更。
1498         * @og.rev 6.1.1.0 (2015/01/17) 内部ロジックの見直し。queue.getBody() を、ローカル変数で定義他。
1499         *
1500         * @param key           キー
1501         * @param rownum        行番号
1502         *
1503         * @return キーのボディー値
1504         * @og.rtnNotNull
1505         */
1506        private String getBodyValue( final String key, final int rownum ) {
1507                // if( status == OVERFLOW || isPageBreak ) { return ""; }
1508                if( isPageBreak ) { return ""; } // 4.3.6.2 (2009/04/15) OVERFLOW時バグ修正
1509
1510                final DBTableModel bodyModel = queue.getBody();                         // 6.1.1.0 (2015/01/17)
1511
1512                final int clmno = bodyModel.getColumnNo( key, false );          // 6.1.1.0 (2015/01/17)
1513                if( clmno < 0 && !ROW_NO.equals( key ) ) { return ""; }
1514
1515                // 6.4.1.1 (2016/01/16) PMD refactoring. Avoid declaring a variable if it is unreferenced before a possible exit point.
1516                final int rowCount = bodyModel.getRowCount();                           // 6.1.1.0 (2015/01/17)
1517                // ページブレイク判定、先読みして判断
1518                if( PAGE_BREAK.equals( key ) ) {
1519                        // 6.9.7.0 (2018/05/14) PMD These nested if statements could be combined
1520//                      if( rownum < rowCount - 1 ) {                                                   // 6.1.1.0 (2015/01/17)
1521//                              if( !( bodyModel.getValue( rownum, clmno ).equals( bodyModel.getValue( rownum + 1, clmno ) ) ) ) {
1522                        if( rownum < rowCount - 1                                                       // 6.1.1.0 (2015/01/17)
1523                                && !( bodyModel.getValue( rownum, clmno ).equals( bodyModel.getValue( rownum + 1, clmno ) ) ) ) {
1524                                        isPageBreak = true;
1525//                              }
1526                        }
1527                        return "";
1528                }
1529
1530                // 5.1.7.0 (2010/06/01) 複数シート対応
1531                // シートブレイクは後読みして判断(前の行と異なっていた場合にブレイク)
1532                if( sheetBreakClm >= 0 ) {
1533                        // 5.1.9.0 (2010/08/01) 最終行で正しくシートブレイクされないバグを修正
1534                        // 6.9.7.0 (2018/05/14) PMD These nested if statements could be combined
1535//                      if( rownum < rowCount && currentBaseRow != rownum ) {
1536//                              if( !( bodyModel.getValue( currentBaseRow, sheetBreakClm ).equals( bodyModel.getValue( rownum, sheetBreakClm ) ) ) ) {
1537                        if( rownum < rowCount && currentBaseRow != rownum
1538                                && !( bodyModel.getValue( currentBaseRow, sheetBreakClm ).equals( bodyModel.getValue( rownum, sheetBreakClm ) ) ) ) {
1539                                        isPageBreak = true;
1540                                        return "";
1541//                              }
1542                        }
1543                }
1544
1545                if( rownum >= rowCount ) {                                                                      // 6.1.1.0 (2015/01/17)
1546                        status = OVERFLOW;
1547                        return "";
1548                }
1549
1550                if( rownum == rowCount - 1 ) {                                                          // 6.1.1.0 (2015/01/17)
1551                        // status = LASTROW;
1552                        status = Math.max( LASTROW, status ); // 4.3.6.2 (2009/04/15) 自身のステータスと比べて大きい方を返す
1553                }
1554
1555                String value = null;
1556                // 5.1.6.0 (2010/05/01) ページNO出力対応
1557                if( ROW_NO.equals( key ) ) {
1558                        value = String.valueOf( rownum + 1 );
1559                }
1560                else {
1561                        value = bodyModel.getValue( rownum, clmno );                    // 6.1.1.0 (2015/01/17)
1562                        // 5.0.2.0 (2009/11/01) ローカルリソースフラグを使用しない場合は、リソース変換を行わない。
1563                        if( queue.isFglocal() ) {
1564                                // 4.3.6.0 (2009/04/01)
1565                                // 6.1.1.0 (2015/01/17) getRendererValue の代わりに、getWriteValue を使うように変更。
1566                                value = bodyModel.getDBColumn( clmno ).getWriteValue( value );  // 6.1.1.0 (2015/01/17)
1567                        }
1568                }
1569
1570                // 4.3.6.2 (2009/04/15)
1571                if( currentMaxRow < rownum + 1 ) {
1572                        currentMaxRow = rownum + 1;
1573                }
1574
1575                return value;
1576        }
1577
1578        /**
1579         * 値に'<'や'>','&'が含まれていた場合にメタ文字に変換します。
1580         *
1581         * @og.rev 5.0.2.0 (2009/11/01) 改行Cの変換ロジックを追加
1582         * @og.rev 5.0.2.0 (2009/11/01) リソース変換時のspanタグを除去
1583         * @og.rev 8.3.0.0 (2022/08/01) '<','>','&'のメタ文字変換をするかどうかを指定します。
1584         *
1585         * @param value 変換前の値
1586         * @param useChange     タ文字変換するかどうか[true:する]
1587         *
1588         * @return 変換後の値
1589         * @og.rtnNotNull
1590         */
1591//      private String checkValue( final String value ) {
1592        private String checkValue( final String value,final boolean useChange ) {
1593                String rtn = value;
1594
1595                // 5.0.2.0 (2009/11/01)
1596                if( queue.isFglocal() ) {
1597                        // 6.0.2.5 (2014/10/31) refactoring
1598                        final int idx = rtn.indexOf( "<span" );
1599                        if( idx >= 0 ) {
1600                                final String spanStart = rtn.substring( idx, rtn.indexOf( '>', idx ) + 1 );
1601                                rtn = rtn.replace( spanStart, "" ).replace( "</span>", "" );
1602                        }
1603                }
1604
1605                if( useChange ) {                                                                       // 8.3.0.0 (2022/08/01)
1606                        if( rtn.indexOf( '&' ) >= 0 ) {
1607                                rtn = rtn.replace( "&", "&amp;" );
1608                        }
1609                        if( rtn.indexOf( '<' ) >= 0 ) {
1610                                rtn = rtn.replace( "<", "&lt;" );
1611                        }
1612                        if( rtn.indexOf( '>' ) >= 0 ) {
1613                                rtn = rtn.replace( ">", "&gt;" );
1614                        }
1615                        if( rtn.indexOf( '\n' ) >= 0 ) {
1616                                rtn = rtn.replace( "\r\n", "\n" ).replace( "\n", OOO_CR );
1617                        }
1618                }
1619
1620                return rtn;
1621        }
1622
1623//      /**
1624//       * 引数の文字列を指定された開始タグ、終了タグで解析し配列として返します。
1625//       * 開始タグより前の文字列は0番目に、終了タグより後の文字列は1番目に格納されます。
1626//       * 2番目以降に、開始タグ、終了タグの部分が格納されます。
1627//       *
1628//       * @og.rev 8.0.3.0 (2021/12/17) TagParser.tag2Array を使用します。
1629//       *
1630//       * @param str           文字列
1631//       * @param startTag      開始タグ
1632//       * @param endTag        終了タグ
1633//       *
1634//       * @return 解析結果の配列
1635//       * @og.rtnNotNull
1636//       */
1637//      private static String[] tag2Array( final String str, final String startTag, final String endTag ) {
1638//              String header = null;
1639//              String footer = null;
1640//              final List<String> body = new ArrayList<>();
1641//
1642//              int preOffset = -1;
1643//              int curOffset = 0;
1644//
1645//              while( true ) {
1646//                      curOffset = str.indexOf( startTag, preOffset + 1 );
1647//                      if( curOffset < 0 ) {
1648//                              curOffset = str.lastIndexOf( endTag ) + endTag.length();
1649//                              body.add( str.substring( preOffset, curOffset ) );
1650//
1651//                              footer = str.substring( curOffset );
1652//                              break;
1653//                      }
1654//                      else if( preOffset == -1 ) {
1655//                              header = str.substring( 0, curOffset );
1656//                      }
1657//                      else {
1658//                              body.add( str.substring( preOffset, curOffset ) );
1659//                      }
1660//                      preOffset = curOffset;
1661//              }
1662//
1663//              String[] arr = new String[body.size()+2];
1664//              arr[0] = header;
1665//              arr[1] = footer;
1666//              for( int i=0; i<body.size(); i++ ) {
1667//                      arr[i+2] = body.get(i);
1668//              }
1669//
1670//              return arr;
1671//      }
1672
1673        /**
1674         * 帳票処理キューを元に、style.xml(ヘッダー、フッター)を書き換えます。(2)
1675         *
1676         * @og.rev 5.1.8.0 (2010/07/01) パース方法の内部実装変更
1677         */
1678        private void execStyles() {
1679                final String fileName = path + "styles.xml";
1680                String content = readOOoXml( fileName );
1681
1682                if( content.indexOf( VAR_START ) < 0 ) { return; }
1683
1684                content = new TagParser() {
1685                        /**
1686                         * 開始タグから終了タグまでの文字列の処理を定義します。
1687                         *
1688                         * この実装では、何も処理を行いません。(切り出した文字列はアペンドされません)
1689                         * サブクラスでオーバーライドして実際の処理を実装して下さい。
1690                         *
1691                         * @param str 開始タグから終了タグまでの文字列(開始タグ・終了タグを含む)
1692                         * @param buf 出力を行う文字列バッファ
1693                         * @param offset 終了タグのオフセット(ここでは使っていません)
1694                         */
1695                        @Override
1696                        public void exec( final String str, final StringBuilder buf, final int offset ) {
1697                                buf.append( getHeaderFooterValue( str ) );
1698                        }
1699                }.doParse( readOOoXml( fileName ), VAR_START, VAR_END, false );
1700
1701                writeOOoXml( fileName, content );
1702        }
1703
1704        /**
1705         * 帳票処理キューを元に、meta.xmlを書き換えます。(6)
1706         *
1707         * @og.rev 5.1.6.0 (2010/05/01) 画面帳票作成機能対応(API経由では出力されないことがある)
1708         */
1709        private void execMeta() {
1710                final String fileName = path + "meta.xml";
1711
1712                String meta = readOOoXml( fileName );
1713
1714                // シート数書き換え
1715                // 5.1.6.0 (2010/05/01)
1716                if( meta.indexOf( TABLE_COUNT_START_TAG ) >=0 ){
1717//                      final String tableCount = TagParser.getValueFromTag( meta, TABLE_COUNT_START_TAG, TABLE_COUNT_END_TAG );
1718                        final String tableCount = TagParser.getValueFromTag( meta, TABLE_COUNT_START_TAG, END_KEY );    // 8.0.3.0 (2021/12/17)
1719                        meta = meta.replace( TABLE_COUNT_START_TAG + tableCount, TABLE_COUNT_START_TAG + pages );
1720                }
1721
1722                // セル数書き換え
1723                // 5.1.6.0 (2010/05/01)
1724                if( meta.indexOf( CELL_COUNT_START_TAG ) >=0 ){
1725//                      final String cellCount = TagParser.getValueFromTag( meta, CELL_COUNT_START_TAG, CELL_COUNT_END_TAG );
1726                        final String cellCount = TagParser.getValueFromTag( meta, CELL_COUNT_START_TAG, END_KEY );      // 8.0.3.0 (2021/12/17)
1727                        meta = meta.replace( CELL_COUNT_START_TAG + cellCount, CELL_COUNT_START_TAG + ( Integer.parseInt( cellCount ) * pages ) );
1728                }
1729
1730                // オブジェクト数書き換え
1731                // 5.1.6.0 (2010/05/01)
1732                if( meta.indexOf( OBJECT_COUNT_START_TAG ) >= 0 ){
1733//                      final String objectCount = TagParser.getValueFromTag( meta, OBJECT_COUNT_START_TAG, OBJECT_COUNT_END_TAG );
1734                        final String objectCount = TagParser.getValueFromTag( meta, OBJECT_COUNT_START_TAG, END_KEY );  // 8.0.3.0 (2021/12/17)
1735                        //4.2.4.0 (2008/06/02) 存在しない場合はnullで帰ってくるので無視する
1736                        if( objectCount != null){
1737                                meta = meta.replace( OBJECT_COUNT_START_TAG + objectCount, OBJECT_COUNT_START_TAG + ( Integer.parseInt( objectCount ) * pages ) );
1738                        }
1739                }
1740
1741                writeOOoXml( fileName, meta );
1742        }
1743
1744        /**
1745         * 書き換え対象のスタイルリストを取得します。
1746         *
1747         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
1748         * @og.rev 8.0.3.0 (2021/12/17) TagParser.tag2Array を使用します。
1749         *
1750         * @param header content.xmlのヘッダー
1751         */
1752        private void getRepStyleList( final String header ) {
1753//              final String[] tags = tag2Array( header, STYLE_START_TAG, STYLE_END_TAG );
1754                final String[] tags =TagParser.tag2Array( header, STYLE_START_TAG, STYLE_END_TAG );
1755                final Set<String> origNameSet = pageNameMap.keySet();
1756                for( int i=2; i<tags.length; i++ ) {
1757                        for( final String origName : origNameSet ) {
1758                                if( tags[i].indexOf( "=\"" + origName + "." ) >= 0 ) {
1759//                                      final String styleName = TagParser.getValueFromTag( tags[i], STYLE_NAME_START_TAG, STYLE_NAME_END_TAG );
1760                                        final String styleName = TagParser.getValueFromTag( tags[i], STYLE_NAME_START_TAG, END_KEY );   // 8.0.3.0 (2021/12/17)
1761                                        repStyleList.add( styleName );
1762                                        break;
1763                                }
1764                        }
1765                }
1766        }
1767
1768        /**
1769         * 帳票処理キューを元に、content.xmlを書き換えます。(4)
1770         * まず、XMLを一旦メモリ上に展開した後、シート単位に分解し、データの埋め込みを行います。
1771         *
1772         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
1773         * @og.rev 8.0.3.0 (2021/12/17) TagParser.tag2Array を使用します。
1774         */
1775        private void execContentHeader() {
1776                final String fileName = path + "content.xml";
1777                final String content = readOOoXml( fileName );
1778
1779                // ファイルの解析し、シート+行単位に分解
1780//              final String[] tags = tag2Array( content, STYLE_START_TAG, STYLE_END_TAG );
1781                final String[] tags = TagParser.tag2Array( content, STYLE_START_TAG, STYLE_END_TAG );
1782                final String header = tags[0];
1783                final String footer = tags[1];
1784
1785                BufferedWriter bw = null;
1786                try {
1787                        bw = getWriter( fileName );
1788                        bw.write( xmlHeader );
1789                        bw.write( '\n' );
1790                        bw.write( header );
1791
1792                        // スタイル情報にシート依存の情報がある場合は、ページ分だけコピーする。
1793                        // 6.3.9.0 (2015/11/06) entrySet イテレータではなく効率が悪い keySet イテレータを使用している
1794                        for( int i=2; i<tags.length; i++ ) {
1795                                boolean isReplace = false;
1796                                for( final Map.Entry<String,List<String>> entry : pageNameMap.entrySet() ) {
1797                                        final String origName = entry.getKey();
1798                                        if( tags[i].indexOf( "=\"" + origName + "." ) >= 0 ) {
1799                                                for( final String newName : entry.getValue() ) {
1800                                                        String styleStr = tags[i].replace( "=\"" + origName + "." , "=\"" + newName + "." );
1801                                                        // シート名の書き換え
1802//                                                      final String styleName = TagParser.getValueFromTag( styleStr, STYLE_NAME_START_TAG, STYLE_NAME_END_TAG );
1803                                                        final String styleName = TagParser.getValueFromTag( styleStr, STYLE_NAME_START_TAG, END_KEY );  // 8.0.3.0 (2021/12/17)
1804                                                        styleStr = styleStr.replace( STYLE_NAME_START_TAG + styleName, STYLE_NAME_START_TAG + styleName + "_" + newName );
1805                                                        bw.write( styleStr );
1806                                                        isReplace = true;
1807                                                }
1808                                                break;
1809                                        }
1810                                }
1811                                if( !isReplace ) {
1812                                        bw.write( tags[i] );
1813                                }
1814                        }
1815
1816                        bw.write( footer );
1817                        bw.flush();
1818                }
1819                catch( final IOException ex ) {
1820                        queue.addMsg( "[ERROR]PARSE:error occurer while write ReParsed Sheet " + fileName );
1821                        throw new HybsSystemException( ex );
1822                }
1823                finally {
1824                        Closer.ioClose( bw );
1825                }
1826        }
1827
1828        /**
1829         * content.xmlのヘッダー部分を出力したcontent.xmlに、ヘッダー部分以降を出力した content.xml.bakをマージします。(5)
1830         *
1831         * @og.rev 5.2.2.0 (2010/11/01) 条件付書式対応
1832         */
1833        private void execMergeContent() {
1834                FileChannel srcChannel = null;
1835                FileChannel destChannel = null;
1836                try {
1837                        srcChannel = new FileInputStream( path + "content.xml.tmp" ).getChannel();
1838                        destChannel = new FileOutputStream( path + "content.xml", true ).getChannel();
1839                        srcChannel.transferTo(0, srcChannel.size(), destChannel);
1840                }
1841                catch( final IOException ex ) {
1842                        queue.addMsg( "[ERROR]PARSE:error occurer while merge content.xml" );
1843                        throw new HybsSystemException( ex );
1844                }
1845                finally {
1846                        Closer.ioClose( srcChannel );
1847                        Closer.ioClose( destChannel );
1848                }
1849                FileUtil.deleteFiles( new File( path + "content.xml.tmp" ) );
1850        }
1851
1852        /**
1853         * META-INF/manifest.xmlに、追加したオブジェクト(グラフ、画像)を登録します。(7)
1854         *
1855         * @og.rev 5.3.1.0 (2011/12/01) 新規作成
1856         */
1857        private void execManifest() {
1858//              final String fileName = path + "META-INF" + File.separator + "manifest.xml";
1859                final String fileName = path + "META-INF" + FS + "manifest.xml";        // 8.0.3.0 (2021/12/17)
1860                final String[] conArr = TagParser.tag2Array( readOOoXml( fileName ), MANIFEST_START_TAG, MANIFEST_END_TAG );
1861
1862                final StringBuilder buf = new StringBuilder( BUFFER_MIDDLE );
1863                buf.append( conArr[0] );
1864                for( int i=2; i<conArr.length; i++ ) {
1865                        buf.append( conArr[i] );
1866                }
1867                for( final Map.Entry<String,String> entry : addObjMap.entrySet() ) {
1868                        if( "graph".equals( entry.getValue() ) ) {
1869                                buf.append( "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"" )
1870                                        .append( entry.getKey() )
1871                                        .append( "/content.xml\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"" )
1872                                        .append( entry.getKey() )
1873                                        .append( "/styles.xml\"/><manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"" )
1874                                        .append( entry.getKey() )
1875                                        .append( "/meta.xml\"/><manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.chart\" manifest:full-path=\"" )
1876                                        .append( entry.getKey() ).append( "/\"/>" );                                            // XML なので、このまま。
1877                        }
1878                        else {
1879                                buf.append( "<manifest:file-entry manifest:media-type=\"image/" )
1880                                        .append( entry.getValue() ).append( "\" manifest:full-path=\"" )
1881                                        .append( entry.getKey() ).append( "\"/>" );                                                     // XML なので、このまま。
1882                        }
1883                }
1884                buf.append( conArr[1] );
1885
1886                writeOOoXml( fileName, buf.toString() );
1887        }
1888
1889        /**
1890         * XMLファイルを読み取り、結果を返します。
1891         * OOoのXMLファイルは全て1行めがxml宣言で、2行目が内容全体という形式であるため、
1892         * ここでは、2行目の内容部分を返します。
1893         *
1894         * @og.rev 4.3.6.0 (2009/04/01) meta.xmlでコンテンツの部分が改行されている場合があるため、ループを回して読込み
1895         * @og.rev 6.2.0.0 (2015/02/27) new BufferedReader … を、FileUtil.getBufferedReader … に変更。
1896         * @og.rev 6.3.1.0 (2015/06/28) nioを使用すると UTF-8とShuft-JISで、エラーになる。
1897         * @og.rev 6.5.0.1 (2016/10/21) CharacterCodingException は、OgCharacterException に変換する。
1898         *
1899         * @param fileName      ファイル名
1900         *
1901         * @return 読み取った文字列
1902         * @og.rtnNotNull
1903         */
1904        private String readOOoXml( final String fileName ) {
1905                final File file = new File ( fileName );
1906
1907                BufferedReader br = null;
1908                String tmp = null;
1909                final StringBuilder buf = new StringBuilder( BUFFER_MIDDLE );
1910                try {
1911                        br = FileUtil.getBufferedReader( file, "UTF-8" );               // 6.2.0.0 (2015/02/27)
1912                        xmlHeader = br.readLine();
1913                        while( ( tmp = br.readLine() ) != null ) {                              // 4.3.6.0 (2009/04/01)
1914                                buf.append( tmp );
1915                        }
1916                }
1917                // 6.3.1.0 (2015/06/28) nioを使用すると UTF-8とShuft-JISで、エラーになる。
1918                catch( final CharacterCodingException ex ) {
1919                        final String errMsg = "文字のエンコード・エラーが発生しました。" + CR
1920                                                                +       "  ファイルのエンコードが指定のエンコードと異なります。" + CR
1921                                                                +       " [" + fileName + "] , Encode=[UTF-8]" ;
1922                        throw new OgCharacterException( errMsg,ex );    // 6.5.0.1 (2016/10/21)
1923                }
1924                catch( final IOException ex ) {
1925                        queue.addMsg( "[ERROR]PARSE:Failed to read " + fileName );
1926                        throw new HybsSystemException( ex );
1927                }
1928                finally {
1929                        Closer.ioClose( br );
1930                }
1931
1932                final String str = buf.toString();
1933                if( xmlHeader == null || xmlHeader.isEmpty() || str == null || str.isEmpty() ) {
1934                        queue.addMsg( "[ERROR]PARSE:Maybe " + fileName + " is Broken!" );
1935                        throw new HybsSystemException();
1936                }
1937
1938                return str;
1939        }
1940
1941        /**
1942         * XMLファイルを書き込みます。
1943         * OOoのXMLファイルは全て1行めがxml宣言で、2行目が内容全体という形式であるため、
1944         * ここでは、2行目の内容部分を渡すことで、XMLファイルを作成します。
1945         *
1946         * @param fileName 書き込むXMLファイル名
1947         * @param str 書き込む文字列
1948         */
1949        private void writeOOoXml( final String fileName, final String str ) {
1950                BufferedWriter bw = null;
1951                try {
1952                        bw = getWriter( fileName );
1953                        bw.write( xmlHeader );
1954                        bw.write( '\n' );
1955                        bw.write( str );
1956                        bw.flush();
1957                }
1958                catch( final IOException ex  ) {
1959                        queue.addMsg( "[ERROR]PARSE:Failed to write " + fileName );
1960                        throw new HybsSystemException( ex );
1961                }
1962                finally {
1963                        Closer.ioClose( bw );
1964                }
1965        }
1966
1967        /**
1968         * XMLファイル書き込み用のライターを返します。
1969         *
1970         * @param fileName ファイル名
1971         *
1972         * @return ライター
1973         * @og.rtnNotNull
1974         */
1975        private BufferedWriter getWriter( final String fileName ) {
1976                return getWriter( fileName, false );
1977        }
1978
1979        /**
1980         * XMLファイル書き込み用のライターを返します。
1981         *
1982         * @param fileName ファイル名
1983         * @param append アベンドするか
1984         *
1985         * @return ライター
1986         * @og.rtnNotNull
1987         */
1988        private BufferedWriter getWriter( final String fileName, final boolean append ) {
1989                final File file = new File ( fileName );
1990                BufferedWriter bw;
1991                try {
1992                        bw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file, append ), "UTF-8" ) );
1993                }
1994                catch( final UnsupportedEncodingException ex ) {
1995                        queue.addMsg( "[ERROR]PARSE:Input File is written by Unsupported Encoding" );
1996                        throw new HybsSystemException( ex );
1997                }
1998                catch( final FileNotFoundException ex ) {
1999                        queue.addMsg( "[ERROR]PARSE:File not Found" );
2000                        throw new HybsSystemException( ex );
2001                }
2002                return bw;
2003        }
2004
2005        /**
2006         * ファイル名から拡張子(小文字)を求めます。
2007         *
2008         * @param fileName 拡張子を取得する為のファイル名
2009         *
2010         * @return 拡張子(小文字)
2011         */
2012        public static String getSuffix( final String fileName ) {
2013                String suffix = null;
2014                if( fileName != null ) {
2015                        final int sufIdx = fileName.lastIndexOf( '.' );
2016                        if( sufIdx >= 0 ) {
2017                                suffix = fileName.substring( sufIdx + 1 ).toLowerCase( Locale.JAPAN );
2018                        }
2019                }
2020                return suffix;
2021        }
2022}