001    /*
002     * Copyright (c) 2009 The openGion Project.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
013     * either express or implied. See the License for the specific language
014     * governing permissions and limitations under the License.
015     */
016    package org.opengion.fukurou.xml;
017    
018    import java.io.File;
019    import java.io.IOException;
020    import java.io.BufferedReader;
021    import java.util.Map;
022    import java.util.WeakHashMap;
023    
024    import org.opengion.fukurou.util.FileUtil;
025    import org.opengion.fukurou.util.Closer;
026    import org.opengion.fukurou.util.LogWriter;
027    
028    /**
029     * こã?クラスは、jspファイルのXSLT変換に特化したã?Readerオブジェクトを作æ?するクラスですã?
030     * jspファイル に記述されるã?jsp:directive.include を見つけて、そのファイル属æ?に
031     * 記述されてã�?‚‹ファイルをã?インクルードしますã?
032     * Tomcat の特性上ã?インクルード時のファイルはã€?¼?­‰ã?エスケープを処ç�?�—ておく
033     * å¿?¦�がありますã?
034     * エスケープã?前å?ç�??、jsp:root タグのあるなしで判定しますã?
035     * 現時点ではã€?& , < , <= , > , >= を前処ç�?�—ますã?
036     *
037     * JSP では、og:head タグでã€?lt;html> をå?力したり、htmlend.jsp インクルードで
038     * </body></html> をå?力してã�?�¾すが、フレーãƒ?‚„、フォワードなど、整合æ?ã�?
039     * 取れなã�?‚±ースがありますã?で、XML処ç�?”¨としてã€?lt;html> をå?力してã�?�¾せんã€?
040     * 変換結果をã?正式な HTML ファイルとして再利用されるå?合ã?、ご注意くã�?�•ã�??
041     *
042     * なおã?こã?クラスは、ã?ルチスレãƒ?ƒ‰対応されてã�?�¾せんã€?
043     *
044     * @og.rev 4.0.0.2 (2007/12/10) 新規追åŠ?
045     *
046     * @version  4.0
047     * @author   Kazuhiko Hasegawa
048     * @since    JDK5.0,
049     */
050    public class JspIncludeReader {
051            private static final String CR = System.getProperty("line.separator");
052    
053            // 5.6.7.1 (2013/08/09) includeしたファイルをキャãƒ?‚·ュしておきますã?
054            private static final Map<String,String> includeFiles = new WeakHashMap<String,String>();
055    
056            // 5.6.7.1 (2013/08/09) ãƒ?ƒ�ãƒ?‚°用にincludeしたファイルを保存しておきますã?
057            private StringBuilder incFiles = new StringBuilder();
058    
059            // タグの属æ?の値のみを抜きå?してã�?�¾すã?特にã€?>& を含ã‚??合ã?
060            // 5.2.1.0 (2010/10/01) 仮å»?­¢
061            //      private static final Pattern ptn = Pattern.compile( "=[ \t]*\"([^\"]*[<>&].[^\"]*)\"" );
062    
063            /**
064             *      JSP のインクルードをè€??した、Reader オブジェクトを返しますã?
065             *
066             * @param file File
067             * @param encode String
068             *
069             * @return Reader
070             */
071    //      public Reader getReader( final File file,final String encode ) {
072    //              return new StringReader( getString( file,encode,false ) );
073    //      }
074    
075            /**
076             * JSP のインクルードをè€??した、JSPファイルをã?String で返しますã?
077             * こã?メソãƒ?ƒ‰は、å?部で再帰定義されてã�?�¾すã?つまりã?jsp:directive.include
078             * æ–?­—å?が見つかったå?合ã?、その代わりに、ファイル名を取å?して、もã�?¸?º¦
079             * こã?メソãƒ?ƒ‰を呼び出しますã?インクルードファイルとの関連をチェãƒ?‚¯する為に
080             * ãƒ?ƒŸーのspanタグをå?れておきますã?
081             * &lt;span type="jsp:directive" include="ファイルå�?&gt;&lt;!-- --&gt;&lt;/span&gt;
082             * ただしã?ソースチェãƒ?‚¯時にã€?
083             * Ver4 以降で、インクルードファイルに、XML宣è¨?�¨、jsp:root を付与するケースがありますã?
084             * 擬似çš?�«取り込ã‚?�¨きには、XML宣è¨??削除しますã?
085             *
086             * @og.rev 5.2.1.0 (2010/10/01) directive.include で、XMLタグとroot タグは取り込まなã�??
087             * @og.rev 5.2.1.0 (2010/10/01) エスケープå?ç�??引数をå»?­¢しますã?
088             * @og.rev 5.6.5.2 (2013/06/21) 小細工å†?®¹の変更。replaceAll にするのと、スペã?スまたã?タブを使用しますã?
089             * @og.rev 5.6.7.1 (2013/08/09) コメントã?処ç�??バグ修正。includeファイル名保存ã?
090             * @og.rev 5.6.7.1 (2013/08/09) includeファイルが存在しなã�??合ã?、gf共有から取得するã?
091             * @og.rev 5.6.7.2 (2013/08/16) includeファイルを取り込ã‚??合ã?代わりのspanタグをå?力しておきますã?
092             * @og.rev 5.6.7.4 (2013/08/30) includeファイルの先é?のpageEncodingæŒ?®šã?チェãƒ?‚¯用 span タグの出åŠ?
093             *
094             * @param       file    JSPファイル
095             * @param       encode  ファイルのエンコーãƒ?
096             *
097             * @return      インクルードをè€??した、JSPファイル
098             */
099    //      public String getString( final File file,final String encode,final boolean isEscape ) {
100            public String getString( final File file,final String encode ) {
101                    StringBuilder buf = new StringBuilder() ;
102                    BufferedReader reader = FileUtil.getBufferedReader( file,encode );
103    
104                    // ファイルがã?jsp 直下かどã�?�‹を判断しますã?
105                    String parentFile = file.getParent() ;
106                    boolean isUnder = parentFile.endsWith( "\\jsp" );
107    
108                    int  cmntIn    = -1;
109                    int  cmntOut   = -1;
110                    boolean isCmnt = false;
111                    boolean isEscape = true;        // エスケープするかどã�?�‹(true:する/false:しなã�?
112                    try {
113                            String line ;
114                            while((line = reader.readLine()) != null) {
115                                    // 5.2.1.0 (2010/10/01) directive.include で、XMLタグは取り込まなã�??
116                                    if( line.indexOf( "<?xml" ) >= 0 && line.indexOf( "?>" ) >= 0 ) { continue; }
117                                    // jsp:root があれã?、エスケープå?ç�?‚’行わなã�?
118                                    if( line.indexOf( "<jsp:root" ) >= 0 ) { isEscape = false; }
119    
120                                    // コメントã?削除
121                                    cmntIn  = line.indexOf( "<!--" );
122                                    cmntOut = line.indexOf( "-->" );
123                                    if( cmntIn >= 0 && cmntOut >= 0 ) {
124    //                                      line = line.substring( 0,cmntIn ) + line.substring( cmntOut );
125                                            line = line.substring( 0,cmntIn ) + line.substring( cmntOut+3 );        // 5.6.7.1 (2013/08/09) コメントã?処ç�??バグ修正
126                                    }
127                                    else if( cmntIn >= 0 && cmntOut < 0 ) {
128                                            line = line.substring( 0,cmntIn );
129                                            isCmnt = true;
130                                    }
131                                    else if( cmntIn < 0  && cmntOut >= 0 ) {
132    //                                      line = line.substring( cmntOut );
133                                            line = line.substring( cmntOut+3 );                     // 5.6.7.1 (2013/08/09) コメントã?処ç�??バグ修正
134                                            isCmnt = false;
135                                    }
136                                    else if( isCmnt && cmntIn < 0 && cmntOut < 0 ) { continue; }
137    
138                                    // 特殊å?ç�?¼šog:head で html タグをå?力してã�?‚‹ã€?
139            //                      if( line.indexOf( "<og:head" ) >= 0 ) {
140            //                              buf.append( "<html>" );
141            //                      }
142    
143                                    if( isEscape ) {
144                                            // 5.6.5.2 (2013/06/21) 小細工å†?®¹の変更。replaceAll にするのと、スペã?スまたã?タブを使用しますã?
145                                            // & , < , <= , > , >= を前処ç�?�—ますã?
146    //                                      line = line.replace( "&"  ,"&amp;" );           // ちã‚?�£と小細工
147    //                                      line = line.replace( " < "," &lt; " );           // ちã‚?�£と小細工
148    //                                      line = line.replace( " > "," &gt; " );           // ちã‚?�£と小細工
149    //                                      line = line.replace( " <="," &lt;=" );           // ちã‚?�£と小細工
150    //                                      line = line.replace( " >="," &gt;=" );           // ちã‚?�£と小細工
151                                            line = line.replaceAll( "&"  ,"&amp;" );                                // ちã‚?�£と小細工
152                                            line = line.replaceAll( "[ \\t]<[ \\t]"," &lt; " );              // ちã‚?�£と小細工
153                                            line = line.replaceAll( "[ \\t]>[ \\t]"," &gt; " );              // ちã‚?�£と小細工
154                                            line = line.replaceAll( "[ \\t]<="," &lt;=" );                   // ちã‚?�£と小細工
155                                            line = line.replaceAll( "[ \\t]>="," &gt;=" );                   // ちã‚?�£と小細工
156            // 5.2.1.0 (2010/10/01) 仮å»?­¢
157            //                              Matcher mtch = ptn.matcher( line );
158            //                              int adrs = 0;
159            //                              StringBuilder buf2 = new StringBuilder();
160            //                              while( mtch.find(adrs) ) {
161            //                                      String grp = mtch.group(1);
162            //                                      String htm = StringUtil.htmlFilter( grp );
163            //                                      int in = mtch.start(1);
164            //                                      buf2.append( line.substring( adrs,in ) ).append( htm );
165            //                                      adrs = mtch.end(1);
166            //                              }
167            //                              buf2.append( line.substring( adrs ) );
168            //                              line = buf2.toString();
169                                    }
170    
171                                    int st = line.indexOf( "<jsp:directive.include" );
172                                    if( st < 0 ) { buf.append( line ); } // include が無ければ、そのまま追åŠ?
173                                    else {
174                                            buf.append( line.substring( 0,st ) );
175                                            int fin = line.indexOf( '\"',st );              // ファイルのæœ??
176                                            int fout= line.indexOf( '\"',fin+1 );   // ファイルのæœ?¾?
177                                            String fname = line.substring( fin+1,fout );    // ファイルå�?
178    
179                                            // 5.6.7.2 (2013/08/16) includeファイルを取り込ã‚??合ã?代わりのspanタグをå?力しておきますã?
180                                            buf.append( "<span type=\"jsp:directive\"" )
181                                                    .append( " include=\"" ).append( fname ).append( "\" ><!-- --></span>" ) ;
182    
183                                            // htmlend.jsp の インクルードã?行わなã�??
184                                            if( fname.endsWith( "htmlend.jsp" ) ) {
185                                                    if( buf.indexOf( "<body" ) >= 0 && buf.indexOf( "</body>" ) < 0 ) {
186                                                            buf.append( "</body>" );
187                                                    }
188    
189            //                                      if( buf.indexOf( "<html" ) >= 0 ) {
190            //                                              buf.append( "</html>" );
191            //                                      }
192                                            }
193                                            else {
194                                                    // 5.6.7.1 (2013/08/09) ãƒ?ƒ�ãƒ?‚°用にincludeしたファイルを保存しておきますã?
195                                                    if( incFiles.length() > 0 ) { incFiles.append( " , " ); }
196                                                    incFiles.append( fname );
197    
198                                                    // 5.6.7.1 (2013/08/09) includeしたファイルをキャãƒ?‚·ュから検索しますã?
199                                                    String fileData = includeFiles.get( fname );    // キャãƒ?‚·ュを検索(fname がキー)
200                                                    if( fileData == null ) {
201                                                            // ちã‚?�£と小細工
202                                                            String fname2 = fname ;
203                                                            // include するファイルはã€?jsp/ からの絶対パスã€?
204                                                            // jsp 直下ã?場合ã?ã€?/ 、それ以外ã?ã€?./ と置き換えますã?
205                                                            if( isUnder ) { fname2 = fname2.replace( "/jsp/","./" ); }
206                                                            else              { fname2 = fname2.replace( "/jsp/","../" ); }
207                                                            // 5.6.7.1 (2013/08/09) includeファイルが存在しなã�??合ã?、gf共有から取得するã?
208                                                            File newfile = new File( parentFile,fname2 );
209                                                            if( !newfile.exists() ) {
210                                                                    if( fname2.contains( "/common/" ) || fname2.contains( "/menu/" ) ) {
211                                                                            // 本当ã? classPathから、取得すべきã?
212                                                                            // 今ã?、実行環å¢??相対パスの位置に、gf/jsp/common,menu のファイルがå¿?¦�ã?
213                                                                            fname2 = ( isUnder )
214                                                                                                    ?       "./../../gf/jsp/"  + fname2.substring( 2 )
215                                                                                                    :       "../../../gf/jsp/" + fname2.substring( 3 ) ;
216                                                                            newfile = new File( parentFile,fname2 );                // ここでなければ、エラーになるã?
217                                                                    }
218                                                            }
219                                                            fileData = getString( newfile,encode );
220                                                            // 5.6.7.4 (2013/08/30) includeファイルの先é?のpageEncodingæŒ?®šã?チェãƒ?‚¯用 span タグの出åŠ?
221                                                            // インクルードファイルの先é?には、pageEncoding="UTF-8" 宣è¨?�Œå¿?¦?UTF-8かどã�?�‹は未チェãƒ?‚¯)
222                                                            if( ! fileData.startsWith( "<jsp:directive.page pageEncoding" ) ) {
223                                                                    // チェãƒ?‚¯用のspanタグをå?力しておきますã?
224                                                                    buf.append( "<span type=\"jsp:directive\"" )
225                                                                            .append( " pageEncoding=\"non\" file=\"" ).append( fname ).append( "\" ><!-- --></span>" ) ;
226                                                            }
227    
228                                                            // 5.6.7.1 (2013/08/09) includeしたファイルをキャãƒ?‚·ュしておきますã?
229                                                            includeFiles.put( fname,fileData );                     // includeファイルをキャãƒ?‚·ュ(fname がキー)
230                                                    }
231    
232    //                                              buf.append( getString( newfile,encode ) );
233                                                    buf.append( fileData );
234                                            }
235                                            int tagout = line.indexOf( "/>",fout+1 );    // タグのæœ?¾?
236    
237                                            buf.append( line.substring( tagout+2 ) );
238                                    }
239    
240                                    // og:commonForward を見つけた場合ã?、最後に html タグをå?力するã?
241            //                      if( line.indexOf( "<og:commonForward" ) >= 0 ) {
242            //                              buf.append( "</html>" );
243            //                      }
244    
245                                    buf.append( CR );
246                            }
247                    }
248                    catch( IOException ex ) {
249                            LogWriter.log( ex );
250                    }
251                    finally {
252                            Closer.ioClose( reader );
253                    }
254                    return buf.toString();
255            }
256    
257            /**
258             * インクルードしたファイルå�?相対パス)のリスト文字å?を返しますã?
259             * 通常は、XSLT変換処ç�?�§エラーが発生したå?合ã?、includeファイルの整合æ?ã�?
260             * おかしい場合が多いので、デバッグæƒ??として利用しますã?
261             * ただしã?エラー発生時の位置特定まではできませんã€?
262             *
263             * こã?å†?ƒ¨変数は、インスタンス変数ですã?で、includeファイルのキャãƒ?‚·ュとは寿命が異なりますã?
264             *
265             * @og.rev 5.6.7.1 (2013/08/09) 新規追åŠ?
266             *
267             * @return includeファイル名ã?リスト文字å?
268             */
269            public String getIncludeFiles() {
270                    return incFiles.toString();
271            }
272    
273            /**
274             * インクルードしたファイルのキャãƒ?‚·ュをクリアしますã?
275             * キャãƒ?‚·ュは、インスタンスではなくã?スタãƒ?‚£ãƒ?‚¯変数で管ç�?�—てã�?�¾すã?
276             * よって、ä¸??の処ç�??初めとæœ?¾Œにクリアしておいてくださいã€?
277             *
278             * @og.rev 5.6.7.1 (2013/08/09) 新規追åŠ?
279             */
280            public static void cacheClear() {
281                    includeFiles.clear();
282            }
283    
284            /**
285             * ãƒ?‚¹ト用の main メソãƒ?ƒ‰
286             *
287             * @param       args    コマンド引数配å?
288             */
289            public static void main( final String[] args ) {
290                    JspIncludeReader reader = new JspIncludeReader();
291    //              String xml = reader.getString( new File( args[0] ),"UTF-8",false );
292                    String xml = reader.getString( new File( args[0] ),"UTF-8" );
293    
294                    if( args.length > 1 ) {
295                            java.io.PrintWriter writer = FileUtil.getPrintWriter( new File( args[1] ),"UTF-8" );
296                            writer.print( xml );
297                            Closer.ioClose( writer );
298                    }
299                    else {
300                            System.out.println( xml );
301                    }
302            }
303    }